jswebrtc.min.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. var JSWebrtc = {
  2. Player: null,
  3. VideoElement: null,
  4. CreateVideoElements: function () {
  5. var elements = document.querySelectorAll(".jswebrtc");
  6. for (var i = 0; i < elements.length; i++) {
  7. new JSWebrtc.VideoElement(elements[i])
  8. }
  9. },
  10. FillQuery: function (query_string, obj) {
  11. obj.user_query = {};
  12. if (query_string.length == 0) return;
  13. if (query_string.indexOf("?") >= 0) query_string = query_string.split("?")[1];
  14. var queries = query_string.split("&");
  15. for (var i = 0; i < queries.length; i++) {
  16. var query = queries[i].split("=");
  17. obj[query[0]] = query[1];
  18. obj.user_query[query[0]] = query[1]
  19. }
  20. if (obj.domain) obj.vhost = obj.domain
  21. },
  22. ParseUrl: function (rtmp_url) {
  23. var a = document.createElement("a");
  24. a.href = rtmp_url.replace("rtmp://", "http://").replace("webrtc://", "http://").replace("rtc://",
  25. "http://");
  26. var vhost = a.hostname;
  27. var app = a.pathname.substr(1, a.pathname.lastIndexOf("/") - 1);
  28. var stream = a.pathname.substr(a.pathname.lastIndexOf("/") + 1);
  29. app = app.replace("...vhost...", "?vhost=");
  30. if (app.indexOf("?") >= 0) {
  31. var params = app.substr(app.indexOf("?"));
  32. app = app.substr(0, app.indexOf("?"));
  33. if (params.indexOf("vhost=") > 0) {
  34. vhost = params.substr(params.indexOf("vhost=") + "vhost=".length);
  35. if (vhost.indexOf("&") > 0) {
  36. vhost = vhost.substr(0, vhost.indexOf("&"))
  37. }
  38. }
  39. }
  40. if (a.hostname == vhost) {
  41. var re = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/;
  42. if (re.test(a.hostname)) vhost = "__defaultVhost__"
  43. }
  44. var schema = "rtmp";
  45. if (rtmp_url.indexOf("://") > 0) schema = rtmp_url.substr(0, rtmp_url.indexOf("://"));
  46. var port = a.port;
  47. // console.log("vhost---------"+window.location.host)
  48. if (!port) {
  49. if (schema === "http") {
  50. port = 80
  51. } else if (schema === "https") {
  52. port = 443
  53. } else if (schema === "rtmp") {
  54. port = 1935
  55. } else if (schema === "webrtc" || schema === "rtc") {
  56. port = 1985
  57. }
  58. }
  59. if(window.location.host == 'cloud.long-chi.com') {
  60. port = 443
  61. }
  62. var ret = {
  63. url: rtmp_url,
  64. schema: schema,
  65. server: a.hostname,
  66. port: port,
  67. vhost: vhost,
  68. app: app,
  69. stream: stream
  70. };
  71. JSWebrtc.FillQuery(a.search, ret);
  72. return ret
  73. },
  74. HttpPost: function (url, data) {
  75. return new Promise(function (resolve, reject) {
  76. var xhr = new XMLHttpRequest;
  77. xhr.onreadystatechange = function () {
  78. if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
  79. var respone = JSON.parse(xhr.responseText);
  80. xhr.onreadystatechange = new Function;
  81. xhr = null;
  82. resolve(respone)
  83. }
  84. };
  85. xhr.open("POST", url, true);
  86. xhr.timeout = 5e3;
  87. xhr.responseType = "text";
  88. xhr.setRequestHeader("Content-Type", "application/json");
  89. xhr.send(data)
  90. })
  91. }
  92. };
  93. if (document.readyState === "complete") {
  94. JSWebrtc.CreateVideoElements()
  95. } else {
  96. document.addEventListener("DOMContentLoaded", JSWebrtc.CreateVideoElements)
  97. }
  98. JSWebrtc.VideoElement = function () {
  99. "use strict";
  100. var VideoElement = function (element) {
  101. var url = element.dataset.url;
  102. if (!url) {
  103. throw "VideoElement has no `data-url` attribute"
  104. }
  105. var addStyles = function (element, styles) {
  106. for (var name in styles) {
  107. element.style[name] = styles[name]
  108. }
  109. };
  110. this.container = element;
  111. addStyles(this.container, {
  112. display: "inline-block",
  113. position: "relative",
  114. minWidth: "80px",
  115. minHeight: "80px"
  116. });
  117. this.video = document.createElement("video");
  118. this.video.width = 960;
  119. this.video.height = 540;
  120. addStyles(this.video, {
  121. display: "block",
  122. width: "100%"
  123. });
  124. this.container.appendChild(this.video);
  125. this.playButton = document.createElement("div");
  126. this.playButton.innerHTML = VideoElement.PLAY_BUTTON;
  127. addStyles(this.playButton, {
  128. zIndex: 2,
  129. position: "absolute",
  130. top: "0",
  131. bottom: "0",
  132. left: "0",
  133. right: "0",
  134. maxWidth: "75px",
  135. maxHeight: "75px",
  136. margin: "auto",
  137. opacity: "0.7",
  138. cursor: "pointer"
  139. });
  140. this.container.appendChild(this.playButton);
  141. var options = {
  142. video: this.video
  143. };
  144. for (var option in element.dataset) {
  145. try {
  146. options[option] = JSON.parse(element.dataset[option])
  147. } catch (err) {
  148. options[option] = element.dataset[option]
  149. }
  150. }
  151. this.player = new JSWebrtc.Player(url, options);
  152. element.playerInstance = this.player;
  153. if (options.poster && !options.autoplay) {
  154. options.decodeFirstFrame = false;
  155. this.poster = new Image;
  156. this.poster.src = options.poster;
  157. this.poster.addEventListener("load", this.posterLoaded);
  158. addStyles(this.poster, {
  159. display: "block",
  160. zIndex: 1,
  161. position: "absolute",
  162. top: 0,
  163. left: 0,
  164. bottom: 0,
  165. right: 0
  166. });
  167. this.container.appendChild(this.poster)
  168. }
  169. if (!this.player.options.streaming) {
  170. this.container.addEventListener("click", this.onClick.bind(this))
  171. }
  172. if (options.autoplay) {
  173. this.playButton.style.display = "none"
  174. }
  175. if (this.player.audioOut && !this.player.audioOut.unlocked) {
  176. var unlockAudioElement = this.container;
  177. if (options.autoplay) {
  178. this.unmuteButton = document.createElement("div");
  179. this.unmuteButton.innerHTML = VideoElement.UNMUTE_BUTTON;
  180. addStyles(this.unmuteButton, {
  181. zIndex: 2,
  182. position: "absolute",
  183. bottom: "10px",
  184. right: "20px",
  185. width: "75px",
  186. height: "75px",
  187. margin: "auto",
  188. opacity: "0.7",
  189. cursor: "pointer"
  190. });
  191. this.container.appendChild(this.unmuteButton);
  192. unlockAudioElement = this.unmuteButton
  193. }
  194. this.unlockAudioBound = this.onUnlockAudio.bind(this, unlockAudioElement);
  195. unlockAudioElement.addEventListener("touchstart", this.unlockAudioBound, false);
  196. unlockAudioElement.addEventListener("click", this.unlockAudioBound, true)
  197. }
  198. };
  199. VideoElement.prototype.onUnlockAudio = function (element, ev) {
  200. if (this.unmuteButton) {
  201. ev.preventDefault();
  202. ev.stopPropagation()
  203. }
  204. this.player.audioOut.unlock(function () {
  205. if (this.unmuteButton) {
  206. this.unmuteButton.style.display = "none"
  207. }
  208. element.removeEventListener("touchstart", this.unlockAudioBound);
  209. element.removeEventListener("click", this.unlockAudioBound)
  210. }.bind(this))
  211. };
  212. VideoElement.prototype.onClick = function (ev) {
  213. if (this.player.isPlaying) {
  214. this.player.pause();
  215. this.playButton.style.display = "block"
  216. } else {
  217. this.player.play();
  218. this.playButton.style.display = "none";
  219. if (this.poster) {
  220. this.poster.style.display = "none"
  221. }
  222. }
  223. };
  224. VideoElement.PLAY_BUTTON = '<svg style="max-width: 75px; max-height: 75px;" ' +
  225. 'viewBox="0 0 200 200" alt="Play video">' + '<circle cx="100" cy="100" r="90" fill="none" ' +
  226. 'stroke-width="15" stroke="#fff"/>' + '<polygon points="70, 55 70, 145 145, 100" fill="#fff"/>' + "</svg>";
  227. VideoElement.UNMUTE_BUTTON = '<svg style="max-width: 75px; max-height: 75px;" viewBox="0 0 75 75">' +
  228. '<polygon class="audio-speaker" stroke="none" fill="#fff" ' +
  229. 'points="39,13 22,28 6,28 6,47 21,47 39,62 39,13"/>' + '<g stroke="#fff" stroke-width="5">' +
  230. '<path d="M 49,50 69,26"/>' + '<path d="M 69,50 49,26"/>' + "</g>" + "</svg>";
  231. return VideoElement
  232. }();
  233. JSWebrtc.Player = function () {
  234. "use strict";
  235. var Player = function (url, options) {
  236. this.options = options || {};
  237. if (!url.match(/^webrtc?:\/\//)) {
  238. throw "JSWebrtc just work with webrtc"
  239. }
  240. if (!this.options.video) {
  241. throw "VideoElement is null"
  242. }
  243. this.urlParams = JSWebrtc.ParseUrl(url);
  244. this.pc = null;
  245. this.autoplay = !!options.autoplay || false;
  246. this.paused = true;
  247. if (this.autoplay) this.options.video.muted = true;
  248. this.startLoading()
  249. };
  250. Player.prototype.startLoading = function () {
  251. var _self = this;
  252. if (_self.pc) {
  253. _self.pc.close()
  254. }
  255. _self.pc = new RTCPeerConnection(null);
  256. _self.pc.ontrack = function (event) {
  257. _self.options.video["srcObject"] = event.streams[0]
  258. };
  259. _self.pc.addTransceiver("audio", {
  260. direction: "recvonly"
  261. });
  262. _self.pc.addTransceiver("video", {
  263. direction: "recvonly"
  264. });
  265. _self.pc.createOffer().then(function (offer) {
  266. return _self.pc.setLocalDescription(offer).then(function () {
  267. return offer
  268. })
  269. }).then(function (offer) {
  270. return new Promise(function (resolve, reject) {
  271. var port = _self.urlParams.port || 1985;
  272. var api = _self.urlParams.user_query.play || "/rtc/v1/play/";
  273. if (api.lastIndexOf("/") != api.length - 1) {
  274. api += "/"
  275. }
  276. var url = "http://" + _self.urlParams.server + ":" + port + api;
  277. if(window.location.host == 'cloud.long-chi.com') {
  278. url = 'https://cloud.long-chi.com/rtc/v1/play/'
  279. }
  280. for (var key in _self.urlParams.user_query) {
  281. if (key != "api" && key != "play") {
  282. url += "&" + key + "=" + _self.urlParams.user_query[key]
  283. }
  284. }
  285. var data = {
  286. api: url,
  287. streamurl: _self.urlParams.url,
  288. clientip: null,
  289. sdp: offer.sdp
  290. };
  291. console.log("offer: " + JSON.stringify(data));
  292. JSWebrtc.HttpPost(url, JSON.stringify(data)).then(function (res) {
  293. console.log("answer: " + JSON.stringify(res));
  294. resolve(res.sdp)
  295. }, function (rej) {
  296. reject(rej)
  297. })
  298. })
  299. }).then(function (answer) {
  300. return _self.pc.setRemoteDescription(new RTCSessionDescription({
  301. type: "answer",
  302. sdp: answer
  303. }))
  304. }).catch(function (reason) {
  305. throw reason
  306. });
  307. if (this.autoplay) {
  308. this.play()
  309. }
  310. };
  311. Player.prototype.play = function (ev) {
  312. if (this.animationId) {
  313. return
  314. }
  315. this.animationId = requestAnimationFrame(this.update.bind(this));
  316. this.paused = false
  317. };
  318. Player.prototype.pause = function (ev) {
  319. if (this.paused) {
  320. return
  321. }
  322. cancelAnimationFrame(this.animationId);
  323. this.animationId = null;
  324. this.isPlaying = false;
  325. this.paused = true;
  326. this.options.video.pause();
  327. if (this.options.onPause) {
  328. this.options.onPause(this)
  329. }
  330. };
  331. Player.prototype.stop = function (ev) {
  332. this.pause()
  333. };
  334. Player.prototype.destroy = function () {
  335. this.pause();
  336. this.pc && this.pc.close() && this.pc.destroy();
  337. this.audioOut && this.audioOut.destroy()
  338. };
  339. Player.prototype.update = function () {
  340. this.animationId = requestAnimationFrame(this.update.bind(this));
  341. if (this.options.video.readyState < 4) {
  342. return
  343. }
  344. if (!this.isPlaying) {
  345. this.isPlaying = true;
  346. this.options.video.play();
  347. if (this.options.onPlay) {
  348. this.options.onPlay(this)
  349. }
  350. }
  351. };
  352. return Player
  353. }();