webrtcstreamer.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. WebRtcStreamer.prototype.filterPreferredCodec = function(sdp, prefmime) {
  72. const lines = sdp.split('\n');
  73. const [prefkind, prefcodec] = prefmime.toLowerCase().split('/');
  74. let currentMediaType = null;
  75. let sdpSections = [];
  76. let currentSection = [];
  77. // Group lines into sections
  78. lines.forEach(line => {
  79. if (line.startsWith('m=')) {
  80. if (currentSection.length) {
  81. sdpSections.push(currentSection);
  82. }
  83. currentSection = [line];
  84. } else {
  85. currentSection.push(line);
  86. }
  87. });
  88. sdpSections.push(currentSection);
  89. // Process each section
  90. const processedSections = sdpSections.map(section => {
  91. const firstLine = section[0];
  92. if (!firstLine.startsWith('m=' + prefkind)) {
  93. return section.join('\n');
  94. }
  95. // Get payload types for preferred codec
  96. const rtpLines = section.filter(line => line.startsWith('a=rtpmap:'));
  97. const preferredPayloads = rtpLines
  98. .filter(line => line.toLowerCase().includes(prefcodec))
  99. .map(line => line.split(':')[1].split(' ')[0]);
  100. if (preferredPayloads.length === 0) {
  101. return section.join('\n');
  102. }
  103. // Modify m= line to only include preferred payloads
  104. const mLine = firstLine.split(' ');
  105. const newMLine = [...mLine.slice(0,3), ...preferredPayloads].join(' ');
  106. // Filter related attributes
  107. const filteredLines = section.filter(line => {
  108. if (line === firstLine) return false;
  109. if (line.startsWith('a=rtpmap:')) {
  110. return preferredPayloads.some(payload => line.startsWith(`a=rtpmap:${payload}`));
  111. }
  112. if (line.startsWith('a=fmtp:') || line.startsWith('a=rtcp-fb:')) {
  113. return preferredPayloads.some(payload => line.startsWith(`a=${line.split(':')[0].split('a=')[1]}:${payload}`));
  114. }
  115. return true;
  116. });
  117. return [newMLine, ...filteredLines].join('\n');
  118. });
  119. return processedSections.join('\n');
  120. }
  121. /*
  122. * GetIceServers callback
  123. */
  124. WebRtcStreamer.prototype.onReceiveGetIceServers = function(iceServers, videourl, audiourl, options, stream, prefmime) {
  125. this.iceServers = iceServers;
  126. this.pcConfig = iceServers || {"iceServers": [] };
  127. try {
  128. this.createPeerConnection();
  129. let callurl = this.srvurl + "/api/call?peerid=" + this.pc.peerid + "&url=" + encodeURIComponent(videourl);
  130. if (audiourl) {
  131. callurl += "&audiourl="+encodeURIComponent(audiourl);
  132. }
  133. if (options) {
  134. callurl += "&options="+encodeURIComponent(options);
  135. }
  136. if (stream) {
  137. this.pc.addStream(stream);
  138. }
  139. // clear early candidates
  140. this.earlyCandidates.length = 0;
  141. // create Offer
  142. this.pc.createOffer(this.mediaConstraints).then((sessionDescription) => {
  143. console.log("Create offer:" + JSON.stringify(sessionDescription));
  144. console.log(`video codecs:${Array.from(new Set(RTCRtpReceiver.getCapabilities("video")?.codecs?.map(codec => codec.mimeType)))}`)
  145. console.log(`audio codecs:${Array.from(new Set(RTCRtpReceiver.getCapabilities("audio")?.codecs?.map(codec => codec.mimeType)))}`)
  146. if (prefmime != undefined) {
  147. //set prefered codec
  148. let [prefkind] = prefmime.split('/');
  149. if (prefkind != "video" && prefkind != "audio") {
  150. prefkind = "video";
  151. prefmime = prefkind + "/" + prefmime;
  152. }
  153. console.log("sdp:" + sessionDescription.sdp);
  154. sessionDescription.sdp = this.filterPreferredCodec(sessionDescription.sdp, prefmime);
  155. console.log("sdp:" + sessionDescription.sdp);
  156. }
  157. this.pc.setLocalDescription(sessionDescription)
  158. .then(() => {
  159. fetch(callurl, { method: "POST", body: JSON.stringify(sessionDescription) })
  160. .then(this._handleHttpErrors)
  161. .then( (response) => (response.json()) )
  162. .catch( (error) => this.onError("call " + error ))
  163. .then( (response) => this.onReceiveCall(response) )
  164. .catch( (error) => this.onError("call " + error ))
  165. }, (error) => {
  166. console.log ("setLocalDescription error:" + JSON.stringify(error));
  167. });
  168. }, (error) => {
  169. alert("Create offer error:" + JSON.stringify(error));
  170. });
  171. } catch (e) {
  172. this.disconnect();
  173. alert("connect error: " + e);
  174. }
  175. }
  176. WebRtcStreamer.prototype.getIceCandidate = function() {
  177. fetch(this.srvurl + "/api/getIceCandidate?peerid=" + this.pc.peerid)
  178. .then(this._handleHttpErrors)
  179. .then( (response) => (response.json()) )
  180. .then( (response) => this.onReceiveCandidate(response))
  181. .catch( (error) => this.onError("getIceCandidate " + error ))
  182. }
  183. /*
  184. * create RTCPeerConnection
  185. */
  186. WebRtcStreamer.prototype.createPeerConnection = function() {
  187. console.log("createPeerConnection config: " + JSON.stringify(this.pcConfig));
  188. this.pc = new RTCPeerConnection(this.pcConfig);
  189. let pc = this.pc;
  190. pc.peerid = Math.random();
  191. pc.onicecandidate = (evt) => this.onIceCandidate(evt);
  192. pc.onaddstream = (evt) => this.onAddStream(evt);
  193. pc.oniceconnectionstatechange = (evt) => {
  194. console.log("oniceconnectionstatechange state: " + pc.iceConnectionState);
  195. if (this.videoElement) {
  196. if (pc.iceConnectionState === "connected") {
  197. this.videoElement.style.opacity = "1.0";
  198. }
  199. else if (pc.iceConnectionState === "disconnected") {
  200. this.videoElement.style.opacity = "0.25";
  201. }
  202. else if ( (pc.iceConnectionState === "failed") || (pc.iceConnectionState === "closed") ) {
  203. this.videoElement.style.opacity = "0.5";
  204. } else if (pc.iceConnectionState === "new") {
  205. this.getIceCandidate();
  206. }
  207. }
  208. }
  209. pc.ondatachannel = function(evt) {
  210. console.log("remote datachannel created:"+JSON.stringify(evt));
  211. evt.channel.onopen = function () {
  212. console.log("remote datachannel open");
  213. this.send("remote channel openned");
  214. }
  215. evt.channel.onmessage = function (event) {
  216. console.log("remote datachannel recv:"+JSON.stringify(event.data));
  217. }
  218. }
  219. try {
  220. let dataChannel = pc.createDataChannel("ClientDataChannel");
  221. dataChannel.onopen = function() {
  222. console.log("local datachannel open");
  223. this.send("local channel openned");
  224. }
  225. dataChannel.onmessage = function(evt) {
  226. console.log("local datachannel recv:"+JSON.stringify(evt.data));
  227. }
  228. } catch (e) {
  229. console.log("Cannor create datachannel error: " + e);
  230. }
  231. console.log("Created RTCPeerConnnection with config: " + JSON.stringify(this.pcConfig) );
  232. return pc;
  233. }
  234. /*
  235. * RTCPeerConnection IceCandidate callback
  236. */
  237. WebRtcStreamer.prototype.onIceCandidate = function (event) {
  238. if (event.candidate) {
  239. if (this.pc.currentRemoteDescription) {
  240. this.addIceCandidate(this.pc.peerid, event.candidate);
  241. } else {
  242. this.earlyCandidates.push(event.candidate);
  243. }
  244. }
  245. else {
  246. console.log("End of candidates.");
  247. }
  248. }
  249. WebRtcStreamer.prototype.addIceCandidate = function(peerid, candidate) {
  250. fetch(this.srvurl + "/api/addIceCandidate?peerid="+peerid, { method: "POST", body: JSON.stringify(candidate) })
  251. .then(this._handleHttpErrors)
  252. .then( (response) => (response.json()) )
  253. .then( (response) => {console.log("addIceCandidate ok:" + response)})
  254. .catch( (error) => this.onError("addIceCandidate " + error ))
  255. }
  256. /*
  257. * RTCPeerConnection AddTrack callback
  258. */
  259. WebRtcStreamer.prototype.onAddStream = function(event) {
  260. console.log("Remote track added:" + JSON.stringify(event));
  261. this.videoElement.srcObject = event.stream;
  262. let promise = this.videoElement.play();
  263. if (promise !== undefined) {
  264. promise.catch((error) => {
  265. console.warn("error:"+error);
  266. this.videoElement.setAttribute("controls", true);
  267. });
  268. }
  269. }
  270. /*
  271. * AJAX /call callback
  272. */
  273. WebRtcStreamer.prototype.onReceiveCall = function(dataJson) {
  274. console.log("offer: " + JSON.stringify(dataJson));
  275. let descr = new RTCSessionDescription(dataJson);
  276. this.pc.setRemoteDescription(descr).then(() => {
  277. console.log ("setRemoteDescription ok");
  278. while (this.earlyCandidates.length) {
  279. let candidate = this.earlyCandidates.shift();
  280. this.addIceCandidate(this.pc.peerid, candidate);
  281. }
  282. this.getIceCandidate()
  283. }
  284. , (error) => {
  285. console.log ("setRemoteDescription error:" + JSON.stringify(error));
  286. });
  287. }
  288. /*
  289. * AJAX /getIceCandidate callback
  290. */
  291. WebRtcStreamer.prototype.onReceiveCandidate = function(dataJson) {
  292. console.log("candidate: " + JSON.stringify(dataJson));
  293. if (dataJson) {
  294. for (let i=0; i<dataJson.length; i++) {
  295. let candidate = new RTCIceCandidate(dataJson[i]);
  296. console.log("Adding ICE candidate :" + JSON.stringify(candidate) );
  297. this.pc.addIceCandidate(candidate).then( () => { console.log ("addIceCandidate OK"); }
  298. , (error) => { console.log ("addIceCandidate error:" + JSON.stringify(error)); } );
  299. }
  300. this.pc.addIceCandidate();
  301. }
  302. }
  303. /*
  304. * AJAX callback for Error
  305. */
  306. WebRtcStreamer.prototype.onError = function(status) {
  307. console.log("onError:" + status);
  308. }
  309. return WebRtcStreamer;
  310. })();
  311. if (typeof window !== 'undefined' && typeof window.document !== 'undefined') {
  312. window.WebRtcStreamer = WebRtcStreamer;
  313. }
  314. if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  315. module.exports = WebRtcStreamer;
  316. }