webrtcstreamer.js 9.5 KB

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