webrtcstreamer.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. var WebRtcStreamer = (function() {
  2. /**
  3. * Interface with WebRTC-streamer API
  4. * @constructor
  5. * @param {string} videoElement - id of the video element tag
  6. * @param {string} srvurl - url of webrtc-streamer (default is current location)
  7. */
  8. var WebRtcStreamer = function WebRtcStreamer (videoElement, srvurl) {
  9. if (typeof videoElement === "string") {
  10. this.videoElement = document.getElementById(videoElement);
  11. } else {
  12. this.videoElement = videoElement;
  13. }
  14. this.srvurl = srvurl || location.protocol+"//"+window.location.hostname+":"+window.location.port;
  15. this.pc = null;
  16. this.mediaConstraints = { offerToReceiveAudio: true, offerToReceiveVideo: true };
  17. this.iceServers = null;
  18. this.earlyCandidates = [];
  19. }
  20. WebRtcStreamer.prototype._handleHttpErrors = function (response) {
  21. if (!response.ok) {
  22. throw Error(response.statusText);
  23. }
  24. return response;
  25. }
  26. /**
  27. * Connect a WebRTC Stream to videoElement
  28. * @param {string} videourl - id of WebRTC video stream
  29. * @param {string} audiourl - id of WebRTC audio stream
  30. * @param {string} options - options of WebRTC call
  31. * @param {string} stream - local stream to send
  32. */
  33. WebRtcStreamer.prototype.connect =async function(videourl, audiourl, options, localstream) {
  34. this.disconnect();
  35. // getIceServers is not already received
  36. if (!this.iceServers) {
  37. console.log("Get IceServers");
  38. try {
  39. fetch(this.srvurl + "/api/getIceServers")
  40. .then(this._handleHttpErrors)
  41. .then((response) => { return response.json() })
  42. .then((response) => this.onReceiveGetIceServers(response, videourl, audiourl, options, localstream))
  43. .catch((error) => {
  44. // new Error('WebRtcStreamer connect error')
  45. return this.onError("getIceServers " + error)
  46. })
  47. // const response = await fetch(this.srvurl + "/api/getIceServers")
  48. // const res = this._handleHttpErrors(response).json()
  49. // this.onReceiveGetIceServers(res, videourl, audiourl, options, localstream)
  50. } catch (error) {
  51. // this.onError("getIceServers " + error)
  52. throw new Error('WebRtcStreamer connect error')
  53. }
  54. } else {
  55. this.onReceiveGetIceServers(this.iceServers, videourl, audiourl, options, localstream);
  56. }
  57. }
  58. /**
  59. * Disconnect a WebRTC Stream and clear videoElement source
  60. */
  61. WebRtcStreamer.prototype.disconnect = function() {
  62. if (this.videoElement?.srcObject) {
  63. this.videoElement.srcObject.getTracks().forEach(track => {
  64. track.stop()
  65. this.videoElement.srcObject.removeTrack(track);
  66. });
  67. }
  68. if (this.pc) {
  69. fetch(this.srvurl + "/api/hangup?peerid=" + this.pc.peerid)
  70. .then(this._handleHttpErrors)
  71. .catch( (error) => this.onError("hangup " + error ))
  72. try {
  73. this.pc.close();
  74. }
  75. catch (e) {
  76. console.log ("Failure close peer connection:" + e);
  77. }
  78. this.pc = null;
  79. }
  80. }
  81. /*
  82. * GetIceServers callback
  83. */
  84. WebRtcStreamer.prototype.onReceiveGetIceServers = function(iceServers, videourl, audiourl, options, stream) {
  85. this.iceServers = iceServers;
  86. this.pcConfig = iceServers || {"iceServers": [] };
  87. try {
  88. this.createPeerConnection();
  89. var callurl = this.srvurl + "/api/call?peerid=" + this.pc.peerid + "&url=" + encodeURIComponent(videourl);
  90. if (audiourl) {
  91. callurl += "&audiourl="+encodeURIComponent(audiourl);
  92. }
  93. if (options) {
  94. callurl += "&options="+encodeURIComponent(options);
  95. }
  96. if (stream) {
  97. this.pc.addStream(stream);
  98. }
  99. // clear early candidates
  100. this.earlyCandidates.length = 0;
  101. // create Offer
  102. this.pc.createOffer(this.mediaConstraints).then((sessionDescription) => {
  103. console.log("Create offer:" + JSON.stringify(sessionDescription));
  104. this.pc.setLocalDescription(sessionDescription)
  105. .then(() => {
  106. fetch(callurl, { method: "POST", body: JSON.stringify(sessionDescription) })
  107. .then(this._handleHttpErrors)
  108. .then( (response) => (response.json()) )
  109. .catch( (error) => this.onError("call " + error ))
  110. .then( (response) => this.onReceiveCall(response) )
  111. .catch( (error) => this.onError("call " + error ))
  112. }, (error) => {
  113. console.log ("setLocalDescription error:" + JSON.stringify(error));
  114. });
  115. }, (error) => {
  116. alert("Create offer error:" + JSON.stringify(error));
  117. });
  118. } catch (e) {
  119. this.disconnect();
  120. alert("connect error: " + e);
  121. }
  122. }
  123. WebRtcStreamer.prototype.getIceCandidate = function() {
  124. fetch(this.srvurl + "/api/getIceCandidate?peerid=" + this.pc.peerid)
  125. .then(this._handleHttpErrors)
  126. .then( (response) => (response.json()) )
  127. .then( (response) => this.onReceiveCandidate(response))
  128. .catch( (error) => this.onError("getIceCandidate " + error ))
  129. }
  130. /*
  131. * create RTCPeerConnection
  132. */
  133. WebRtcStreamer.prototype.createPeerConnection = function() {
  134. console.log("createPeerConnection config: " + JSON.stringify(this.pcConfig));
  135. this.pc = new RTCPeerConnection(this.pcConfig);
  136. var pc = this.pc;
  137. pc.peerid = Math.random();
  138. pc.onicecandidate = (evt) => this.onIceCandidate(evt);
  139. pc.onaddstream = (evt) => this.onAddStream(evt);
  140. pc.oniceconnectionstatechange = (evt) => {
  141. console.log("oniceconnectionstatechange state: " + pc.iceConnectionState);
  142. if (this.videoElement) {
  143. if (pc.iceConnectionState === "connected") {
  144. this.videoElement.style.opacity = "1.0";
  145. }
  146. else if (pc.iceConnectionState === "disconnected") {
  147. this.videoElement.style.opacity = "0.25";
  148. }
  149. else if ( (pc.iceConnectionState === "failed") || (pc.iceConnectionState === "closed") ) {
  150. this.videoElement.style.opacity = "0.5";
  151. } else if (pc.iceConnectionState === "new") {
  152. this.getIceCandidate();
  153. }
  154. }
  155. }
  156. pc.ondatachannel = function(evt) {
  157. console.log("remote datachannel created:"+JSON.stringify(evt));
  158. evt.channel.onopen = function () {
  159. console.log("remote datachannel open");
  160. this.send("remote channel openned");
  161. }
  162. evt.channel.onmessage = function (event) {
  163. console.log("remote datachannel recv:"+JSON.stringify(event.data));
  164. }
  165. }
  166. pc.onicegatheringstatechange = function() {
  167. if (pc.iceGatheringState === "complete") {
  168. const recvs = pc.getReceivers();
  169. recvs.forEach((recv) => {
  170. if (recv.track && recv.track.kind === "video") {
  171. console.log("codecs:" + JSON.stringify(recv.getParameters().codecs))
  172. }
  173. });
  174. }
  175. }
  176. try {
  177. var dataChannel = pc.createDataChannel("ClientDataChannel");
  178. dataChannel.onopen = function() {
  179. console.log("local datachannel open");
  180. this.send("local channel openned");
  181. }
  182. dataChannel.onmessage = function(evt) {
  183. console.log("local datachannel recv:"+JSON.stringify(evt.data));
  184. }
  185. } catch (e) {
  186. console.log("Cannor create datachannel error: " + e);
  187. }
  188. console.log("Created RTCPeerConnnection with config: " + JSON.stringify(this.pcConfig) );
  189. return pc;
  190. }
  191. /*
  192. * RTCPeerConnection IceCandidate callback
  193. */
  194. WebRtcStreamer.prototype.onIceCandidate = function (event) {
  195. if (event.candidate) {
  196. if (this.pc.currentRemoteDescription) {
  197. this.addIceCandidate(this.pc.peerid, event.candidate);
  198. } else {
  199. this.earlyCandidates.push(event.candidate);
  200. }
  201. }
  202. else {
  203. console.log("End of candidates.");
  204. }
  205. }
  206. WebRtcStreamer.prototype.addIceCandidate = function(peerid, candidate) {
  207. fetch(this.srvurl + "/api/addIceCandidate?peerid="+peerid, { method: "POST", body: JSON.stringify(candidate) })
  208. .then(this._handleHttpErrors)
  209. .then( (response) => (response.json()) )
  210. .then( (response) => {console.log("addIceCandidate ok:" + response)})
  211. .catch( (error) => this.onError("addIceCandidate " + error ))
  212. }
  213. /*
  214. * RTCPeerConnection AddTrack callback
  215. */
  216. WebRtcStreamer.prototype.onAddStream = function(event) {
  217. console.log("Remote track added:" + JSON.stringify(event));
  218. this.videoElement.srcObject = event.stream;
  219. var promise = this.videoElement.play();
  220. if (promise !== undefined) {
  221. promise.catch((error) => {
  222. console.warn("error:"+error);
  223. this.videoElement.setAttribute("controls", true);
  224. });
  225. }
  226. }
  227. /*
  228. * AJAX /call callback
  229. */
  230. WebRtcStreamer.prototype.onReceiveCall = function(dataJson) {
  231. console.log("offer: " + JSON.stringify(dataJson));
  232. var descr = new RTCSessionDescription(dataJson);
  233. this.pc.setRemoteDescription(descr).then(() => {
  234. console.log ("setRemoteDescription ok");
  235. while (this.earlyCandidates.length) {
  236. var candidate = this.earlyCandidates.shift();
  237. this.addIceCandidate(this.pc.peerid, candidate);
  238. }
  239. this.getIceCandidate()
  240. }
  241. , (error) => {
  242. console.log ("setRemoteDescription error:" + JSON.stringify(error));
  243. });
  244. }
  245. /*
  246. * AJAX /getIceCandidate callback
  247. */
  248. WebRtcStreamer.prototype.onReceiveCandidate = function(dataJson) {
  249. console.log("candidate: " + JSON.stringify(dataJson));
  250. if (dataJson) {
  251. for (var i=0; i<dataJson.length; i++) {
  252. var candidate = new RTCIceCandidate(dataJson[i]);
  253. console.log("Adding ICE candidate :" + JSON.stringify(candidate) );
  254. this.pc.addIceCandidate(candidate).then( () => { console.log ("addIceCandidate OK"); }
  255. , (error) => { console.log ("addIceCandidate error:" + JSON.stringify(error)); } );
  256. }
  257. this.pc.addIceCandidate();
  258. }
  259. }
  260. /*
  261. * AJAX callback for Error
  262. */
  263. WebRtcStreamer.prototype.onError = function(status) {
  264. console.log("onError:" + status);
  265. throw new Error('视频播放错误')
  266. }
  267. return WebRtcStreamer;
  268. })();
  269. if (typeof window !== 'undefined' && typeof window.document !== 'undefined') {
  270. window.WebRtcStreamer = WebRtcStreamer;
  271. }
  272. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  273. module.exports = WebRtcStreamer;
  274. }