webrtcstreamer.js 9.4 KB

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