webrtc.js 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  1. "use strict";
  2. /*
  3. The MIT License (MIT)
  4. Copyright (c) 2014-2018 Nikolai Suslov and the Krestianstvo.org project contributors. (https://github.com/NikolaySuslov/livecodingspace/blob/master/LICENSE.md)
  5. Virtual World Framework Apache 2.0 license (https://github.com/NikolaySuslov/livecodingspace/blob/master/licenses/LICENSE_VWF.md)
  6. */
  7. /// @module vwf/view/webrtc
  8. /// @requires vwf/view
  9. define( [ "module", "vwf/view", "vwf/utility", "vwf/utility/color"], function( module, view, utility, Color) {
  10. return view.load( module, {
  11. // == Module Definition ====================================================================
  12. initialize: function( options ) {
  13. if ( !this.state ) {
  14. this.state = {};
  15. }
  16. this.state.clients = {};
  17. this.state.instances = {};
  18. this.local = {
  19. "ID": undefined,
  20. "url": undefined,
  21. "stream": undefined,
  22. "sharing": { audio: true, video: true }
  23. };
  24. if ( options === undefined ) { options = {}; }
  25. this.stereo = options.stereo !== undefined ? options.stereo : false;
  26. this.videoElementsDiv = options.videoElementsDiv !== undefined ? options.videoElementsDiv : 'videoSurfaces';
  27. this.videoProperties = options.videoProperties !== undefined ? options.videoProperties : {};
  28. this.bandwidth = options.bandwidth;
  29. this.iceServers = options.iceServers !== undefined ? options.iceServers : [ { "url": "stun:stun.l.google.com:19302" } ];
  30. this.debug = options.debug !== undefined ? options.debug : false;
  31. this.videosAdded = 0;
  32. this.msgQueue = [];
  33. },
  34. createdNode: function( nodeID, childID, childExtendsID, childImplementsIDs,
  35. childSource, childType, childIndex, childName, callback /* ( ready ) */ ) {
  36. if ( childExtendsID === undefined )
  37. return;
  38. var self = this, node;
  39. var protos = getPrototypes.call( self, childExtendsID )
  40. if ( isClientInstanceDef.call( this, protos ) && childName ) {
  41. node = {
  42. "parentID": nodeID,
  43. "ID": childID,
  44. "extendsID": childExtendsID,
  45. "implementsIDs": childImplementsIDs,
  46. "source": childSource,
  47. "type": childType,
  48. "name": childName,
  49. "prototypes": protos,
  50. };
  51. this.state.instances[ childID ] = node;
  52. } else if ( isClientDefinition.call( this, protos ) && childName ) {
  53. // check if this instance of client and if this client is for this instance
  54. // create a login for this
  55. node = {
  56. "parentID": nodeID,
  57. "ID": childID,
  58. "moniker": undefined,
  59. "extendsID": childExtendsID,
  60. "implementsIDs": childImplementsIDs,
  61. "source": childSource,
  62. "type": childType,
  63. "name": childName,
  64. "prototypes": protos,
  65. "displayName": "",
  66. "connection": undefined,
  67. "localUrl": undefined,
  68. "remoteUrl": undefined,
  69. //"color": "rgb(0,0,0)",
  70. "createProperty": true,
  71. "sharing": { audio: true, video: true }
  72. };
  73. this.state.clients[ childID ] = node;
  74. // add the client specific locals
  75. node.moniker = appMoniker.call( this, childName );
  76. //console.info( "new client moniker: " + node.moniker );
  77. node.displayName = undefined;
  78. node.prototypes = protos;
  79. if ( this.kernel.moniker() == node.moniker ) {
  80. this.local.ID = childID;
  81. }
  82. }
  83. },
  84. deleteConnection: function(nodeID){
  85. // debugger;
  86. //if ( this.kernel.find( nodeID, "parent::element(*,'http://vwf.example.com/clients.vwf')" ).length > 0 ) {
  87. //if ( this.kernel.find( nodeID ).length > 0 ) {
  88. var moniker = nodeID.slice(-20);//this.kernel.name( nodeID );
  89. var client = undefined;
  90. if ( moniker == this.kernel.moniker() ) {
  91. // this is the client that has left the converstaion
  92. // go through the peerConnections and close the
  93. // all current connections
  94. var peer, peerMoniker;
  95. for ( var peerID in this.state.clients ) {
  96. peer = this.state.clients[ peerID ];
  97. peerMoniker = appMoniker.call( this, peer.name )
  98. if ( peerMoniker != this.kernel.moniker() ) {
  99. peer.connection && peer.connection.disconnect();
  100. let peername = 'avatar-' + peerMoniker;
  101. deletePeerConnection.call( this, peername);
  102. }
  103. }
  104. } else {
  105. // this is a client who has has a peer leave the converstaion
  106. // remove that client, and the
  107. client = findClientByMoniker.call( this, moniker );
  108. if ( client ) {
  109. client.connection && client.connection.disconnect();
  110. //removeClient.call( this, client );
  111. //delete this.state.clients[ client ]
  112. }
  113. }
  114. },
  115. stopWebRTC: function(nodeID){
  116. if( this.local.stream ){
  117. var tracks = this.local.stream.getTracks();
  118. tracks.forEach(function(track) {
  119. track.stop();
  120. });
  121. this.local.stream = undefined;
  122. let vidui = document.querySelector('#webrtcvideo');
  123. const viduicomp = new mdc.iconButton.MDCIconButtonToggle(vidui); //new mdc.select.MDCIconToggle
  124. if (vidui) viduicomp.on = false;
  125. let micui = document.querySelector('#webrtcaudio');
  126. const micuicomp = new mdc.iconButton.MDCIconButtonToggle(micui);
  127. if (micui) micuicomp.on = false;
  128. this.deleteConnection(nodeID);
  129. this.kernel.callMethod(nodeID, "removeSoundWebRTC");
  130. this.kernel.callMethod(nodeID, "removeVideoTexture");
  131. }
  132. },
  133. startWebRTC: function(childID) {
  134. var client = this.state.clients[ childID ];
  135. if ( client ) {
  136. if ( this.local.ID == childID ){
  137. // local client object
  138. // grab access to the webcam
  139. capture.call( this, this.local.sharing );
  140. var remoteClient = undefined;
  141. // existing clients
  142. for ( var clientID in this.state.clients ) {
  143. if ( clientID != this.local.ID ) {
  144. // create property for this client on each existing client
  145. remoteClient = this.state.clients[ clientID ];
  146. if ( remoteClient.createProperty ) {
  147. //console.info( "++ 1 ++ createProperty( "+clientID+", "+this.kernel.moniker()+" )" );
  148. remoteClient.createProperty = false;
  149. this.kernel.createProperty( clientID, this.kernel.moniker() );
  150. }
  151. }
  152. }
  153. } else {
  154. // not the local client, but if the local client has logged
  155. // in create the property for this on the new client
  156. if ( this.local.ID ) {
  157. if ( client.createProperty ) {
  158. client.createProperty = false;
  159. //console.info( "++ 2 ++ createProperty( "+childID+", "+this.kernel.moniker()+" )" );
  160. this.kernel.createProperty( childID, this.kernel.moniker() );
  161. }
  162. }
  163. }
  164. }
  165. },
  166. initializedNode: function( nodeID, childID, childExtendsID, childImplementsIDs,
  167. childSource, childType, childIndex, childName ) {
  168. if ( childExtendsID === undefined )
  169. return;
  170. },
  171. deletedNode: function( nodeID ) {
  172. // debugger;
  173. //if ( this.kernel.find( nodeID, "parent::element(*,'http://vwf.example.com/clients.vwf')" ).length > 0 ) {
  174. //if ( this.kernel.find( nodeID ).length > 0 ) {
  175. var moniker = nodeID.slice(-20);//this.kernel.name( nodeID );
  176. var client = undefined;
  177. if ( moniker == this.kernel.moniker() ) {
  178. // this is the client that has left the converstaion
  179. // go through the peerConnections and close the
  180. // all current connections
  181. var peer, peerMoniker;
  182. for ( var peerID in this.state.clients ) {
  183. peer = this.state.clients[ peerID ];
  184. peerMoniker = appMoniker.call( this, peer.name )
  185. if ( peerMoniker != this.kernel.moniker() ) {
  186. peer.connection && peer.connection.disconnect();
  187. let peername = 'avatar-' + peerMoniker;
  188. deletePeerConnection.call( this, peername);
  189. }
  190. }
  191. } else {
  192. // this is a client who has has a peer leave the converstaion
  193. // remove that client, and the
  194. client = findClientByMoniker.call( this, moniker );
  195. if ( client ) {
  196. client.connection && client.connection.disconnect();
  197. removeClient.call( this, client );
  198. delete this.state.clients[ client ]
  199. }
  200. }
  201. //}
  202. },
  203. createdProperty: function( nodeID, propertyName, propertyValue ) {
  204. this.satProperty( nodeID, propertyName, propertyValue );
  205. },
  206. initializedProperty: function( nodeID, propertyName, propertyValue ) {
  207. this.satProperty( nodeID, propertyName, propertyValue );
  208. },
  209. satProperty: function( nodeID, propertyName, propertyValue ) {
  210. var client = this.state.clients[ nodeID ];
  211. if ( client ) {
  212. switch( propertyName ) {
  213. case "sharing":
  214. if ( propertyValue ) {
  215. client.sharing = propertyValue;
  216. if ( nodeID == this.local.ID ) {
  217. updateSharing.call( this, nodeID, propertyValue );
  218. }
  219. }
  220. break;
  221. case "localUrl":
  222. if ( propertyValue ) {
  223. if ( nodeID != this.local.ID ) {
  224. client.localUrl = propertyValue;
  225. }
  226. }
  227. break;
  228. case "remoteUrl":
  229. if ( propertyValue ) {
  230. client.remoteUrl = propertyValue;
  231. }
  232. break;
  233. case "displayName":
  234. if ( propertyValue ) {
  235. client.displayName = propertyValue;
  236. }
  237. break;
  238. default:
  239. // propertyName is the moniker of the client that
  240. // this connection supports
  241. if ( nodeID == this.local.ID ) {
  242. if ( propertyValue ) {
  243. // propertyName - moniker of the client
  244. // propertyValue - peerConnection message
  245. handlePeerMessage.call( this, propertyName, propertyValue );
  246. }
  247. }
  248. break;
  249. }
  250. }
  251. },
  252. gotProperty: function( nodeID, propertyName, propertyValue ) {
  253. var value = undefined;
  254. return value;
  255. },
  256. calledMethod: function( nodeID, methodName, methodParameters, methodValue ) {
  257. switch ( methodName ) {
  258. case "setLocalMute":
  259. if ( this.kernel.moniker() == this.kernel.client() ) {
  260. methodValue = setMute.call( this, methodParameters );
  261. }
  262. break;
  263. case "webrtcTurnOnOff":
  264. if ( this.kernel.moniker() == this.kernel.client() ) {
  265. console.log("WEBRTC turn on/off")
  266. methodValue = turnOnOffTracks.call( this, methodParameters );
  267. }
  268. break;
  269. case "webrtcMuteAudio":
  270. if ( this.kernel.moniker() == this.kernel.client() ) {
  271. methodValue = muteAudio.call( this, methodParameters[0] );
  272. }
  273. break;
  274. case "webrtcMuteVideo":
  275. if ( this.kernel.moniker() == this.kernel.client() ) {
  276. methodValue = this.muteVideo.call( this, methodParameters[0] );
  277. }
  278. break;
  279. }
  280. },
  281. firedEvent: function( nodeID, eventName, eventParameters ) {
  282. },
  283. muteVideo: function ( mute ) {
  284. let str = this.local.stream;
  285. if ( str ) {
  286. var tracks = str.getVideoTracks();
  287. tracks.forEach(function(track) {
  288. track.enabled = mute;
  289. });
  290. }
  291. },
  292. muteAudio: function ( mute ) {
  293. let str = this.local.stream;
  294. if ( str ) {
  295. var tracks = str.getAudioTracks();
  296. tracks.forEach(function(track) {
  297. track.enabled = mute;
  298. });
  299. }
  300. }
  301. } );
  302. function createVideoElementAsAsset(id, local) {
  303. var video = document.querySelector('#' + id);
  304. if (!video) {
  305. video = document.createElement('video');
  306. }
  307. video.setAttribute('id', id);
  308. video.setAttribute('autoplay', true);
  309. //video.setAttribute('src', '');
  310. video.setAttribute("webkit-playsinline", true);
  311. video.setAttribute("controls", true);
  312. video.setAttribute("width", 640);
  313. video.setAttribute("height", 480);
  314. if (local) video.setAttribute("muted", true);
  315. // let audioID = '#audio-' + id;
  316. // var audio = document.querySelector(audioID);
  317. // if (!audio) {
  318. // audio = document.createElement('audio');
  319. // }
  320. // audio.setAttribute('id', audioID);
  321. var assets = document.querySelector('a-assets');
  322. // if (!assets) {
  323. // assets = document.createElement('a-assets');
  324. // document.querySelector('a-scene').appendChild(assets);
  325. // }
  326. if (!assets.contains(video)) {
  327. assets.appendChild(video);
  328. }
  329. // if (!assets.contains(audio)) {
  330. // assets.appendChild(audio);
  331. // }
  332. return video //{'video': video, 'audio': audio};
  333. }
  334. function getPrototypes( extendsID ) {
  335. var prototypes = [];
  336. var id = extendsID;
  337. while ( id !== undefined ) {
  338. prototypes.push( id );
  339. id = this.kernel.prototype( id );
  340. }
  341. return prototypes;
  342. }
  343. function getPeer( moniker ) {
  344. var clientNode;
  345. for ( var id in this.state.clients ) {
  346. if ( this.state.clients[id].moniker == moniker ) {
  347. clientNode = this.state.clients[id];
  348. break;
  349. }
  350. }
  351. return clientNode;
  352. }
  353. function displayLocal( stream, name) {
  354. var id = this.kernel.moniker();
  355. return displayVideo.call( this, id, stream, this.local.url, name, id, true);
  356. }
  357. function displayVideo( id, stream, url, name, destMoniker, local) {
  358. let va = createVideoElementAsAsset(name, local);
  359. //video.setAttribute('src', url);
  360. va.srcObject = stream;
  361. //var audioCtx = new AudioContext();
  362. //var source = audioCtx.createMediaStreamSource(stream);
  363. //va.audio.src = stream;
  364. this.kernel.callMethod( 'avatar-'+id, "setVideoTexture", [name]);
  365. return id;
  366. }
  367. function removeVideo( client ) {
  368. // if ( client.videoDivID ) {
  369. // var $videoWin = $( "#" + client.videoDivID );
  370. // if ( $videoWin ) {
  371. // $videoWin.remove();
  372. // }
  373. // client.videoDivID = undefined;
  374. // }
  375. // this.kernel.callMethod( this.kernel.application(), "removeVideo", [ client.moniker ] );
  376. }
  377. function displayRemote( id, stream, url, name, destMoniker, color ) {
  378. let audioID = 'audio-' + name;
  379. this.kernel.callMethod( 'avatar-'+id, "setSoundWebRTC", [audioID]);
  380. return displayVideo.call( this, id, stream, url, name, destMoniker, true );
  381. }
  382. function capture( media ) {
  383. if ( this.local.stream === undefined && ( media.video || media.audio ) ) {
  384. var self = this;
  385. var constraints = {
  386. audio: true,
  387. video: true
  388. };
  389. navigator.mediaDevices.getUserMedia(constraints).then(handleSuccess).catch(handleError);
  390. function handleError(error) {
  391. console.log('navigator.getUserMedia error: ', error);
  392. }
  393. function handleSuccess(stream) {
  394. // var videoTracks = stream.getVideoTracks();
  395. // console.log('Got stream with constraints:', constraints);
  396. // if (videoTracks.length) {
  397. // videoTracks[0].enabled = true;
  398. // }
  399. self.local.url = "url" //URL.createObjectURL( stream );
  400. self.local.stream = stream;
  401. self.kernel.setProperty( self.local.ID, "localUrl", self.local.url );
  402. var localNode = self.state.clients[ self.local.ID ];
  403. self.muteAudio(false);
  404. self.muteVideo(false);
  405. let webRTCGUI = document.querySelector('#webrtcswitch');
  406. if (webRTCGUI) webRTCGUI.setAttribute("aria-pressed", true);
  407. let videoTracks = stream.getVideoTracks();
  408. let vstatus = videoTracks[0].enabled;
  409. let vidui = document.querySelector('#webrtcvideo');
  410. const viduicomp = new mdc.iconButton.MDCIconButtonToggle(vidui); //new mdc.select.MDCIconToggle
  411. if (vidui) viduicomp.on = vstatus;
  412. let audioTracks = stream.getAudioTracks();
  413. let astatus = audioTracks[0].enabled;
  414. let micui = document.querySelector('#webrtcaudio');
  415. const micuicomp = new mdc.iconButton.MDCIconButtonToggle(micui);
  416. if (micui) micuicomp.on = astatus;
  417. displayLocal.call( self, stream, localNode.displayName);
  418. sendOffers.call( self );
  419. }
  420. }
  421. }
  422. function appMoniker( name ) {
  423. return name.substr( 7, name.length-1 );
  424. }
  425. function findClientByMoniker( moniker ) {
  426. var client = undefined;
  427. for ( var id in this.state.clients ) {
  428. if ( client === undefined && moniker == this.state.clients[ id ].moniker ) {
  429. client = this.state.clients[ id ];
  430. }
  431. }
  432. return client;
  433. }
  434. function removeClient( client ) {
  435. if ( client ) {
  436. removeVideo.call( this, client );
  437. }
  438. }
  439. function sendOffers() {
  440. var peerNode;
  441. for ( var id in this.state.clients ) {
  442. if ( id != this.local.ID ) {
  443. peerNode = this.state.clients[ id ];
  444. // if there's a url then connect
  445. if ( peerNode.localUrl && peerNode.localUrl != "" && peerNode.connection === undefined ) {
  446. createPeerConnection.call( this, peerNode, true );
  447. }
  448. }
  449. }
  450. }
  451. function updateSharing( nodeID, sharing ) {
  452. setMute.call( this, !sharing.audio );
  453. setPause.call( this, !sharing.video );
  454. }
  455. function turnOnOffTracks( mute ) {
  456. let str = this.local.stream;
  457. if ( str ) {
  458. var audioTracks = str.getAudioTracks();
  459. var videoTracks = str.getVideoTracks();
  460. audioTracks.forEach(function(track) {
  461. track.enabled = mute[0];
  462. });
  463. videoTracks.forEach(function(track) {
  464. track.enabled = mute[0];
  465. });
  466. }
  467. };
  468. function muteAudio( mute ) {
  469. let str = this.local.stream;
  470. if ( str ) {
  471. var audioTracks = str.getAudioTracks();
  472. audioTracks.forEach(function(track) {
  473. track.enabled = mute;
  474. });
  475. }
  476. };
  477. function setMute( mute ) {
  478. if ( this.local.stream && this.local.stream.audioTracks && this.local.stream.audioTracks.length > 0 ) {
  479. if ( mute !== undefined ) {
  480. this.local.stream.audioTracks[0].enabled = !mute;
  481. }
  482. }
  483. };
  484. function setPause( pause ) {
  485. if ( this.local.stream && this.local.stream.videoTracks && this.local.stream.videoTracks.length > 0 ) {
  486. if ( pause !== undefined ) {
  487. this.local.stream.videoTracks[0].enabled = !pause;
  488. }
  489. }
  490. }
  491. function release() {
  492. for ( id in this.connections ) {
  493. this.connections[id].disconnect();
  494. }
  495. this.connections = {};
  496. }
  497. function hasStream() {
  498. return ( this.stream !== undefined );
  499. }
  500. function createPeerConnection( peerNode, sendOffer ) {
  501. if ( peerNode ) {
  502. if ( peerNode.connection === undefined ) {
  503. peerNode.connection = new mediaConnection( this, peerNode );
  504. peerNode.connection.connect( this.local.stream, sendOffer );
  505. //if ( this.bandwidth !== undefined ) {
  506. // debugger;
  507. //}
  508. }
  509. }
  510. }
  511. function handlePeerMessage( propertyName, msg ) {
  512. var peerNode = getPeer.call( this, propertyName )
  513. if ( peerNode ) {
  514. if ( peerNode.connection !== undefined ) {
  515. peerNode.connection.processMessage( msg );
  516. } else {
  517. if ( msg.type === 'offer' ) {
  518. this.msgQueue.unshift( msg );
  519. peerNode.connection = new mediaConnection( this, peerNode );
  520. peerNode.connection.connect( this.local.stream, false );
  521. while ( this.msgQueue.length > 0 ) {
  522. peerNode.connection.processMessage( this.msgQueue.shift() );
  523. }
  524. this.msgQueue = [];
  525. } else {
  526. this.msgQueue.push( msg );
  527. }
  528. }
  529. }
  530. }
  531. function deletePeerConnection( peerID ) {
  532. var peerNode = this.state.clients[ peerID ];
  533. if ( peerNode ) {
  534. peerNode.connection.disconnect();
  535. peerNode.connection = undefined;
  536. }
  537. }
  538. function getConnectionStats() {
  539. var peerNode = undefined;
  540. for ( var id in this.state.clients ) {
  541. peerNode = this.state.clients[ id ];
  542. if ( peerNode && peerNode.connection ) {
  543. peerNode.connection.getStats();
  544. }
  545. }
  546. }
  547. function isClientDefinition( prototypes ) {
  548. var foundClient = false;
  549. if ( prototypes ) {
  550. var len = prototypes.length;
  551. for ( var i = 0; i < len && !foundClient; i++ ) {
  552. foundClient = ( prototypes[i] == "http://vwf.example.com/aframe/avatar.vwf" );
  553. }
  554. }
  555. return foundClient;
  556. }
  557. function isClientInstanceDef( nodeID ) {
  558. return ( nodeID == "http://vwf.example.com/clients.vwf" );
  559. }
  560. function mediaConnection( view, peerNode ) {
  561. this.view = view;
  562. this.peerNode = peerNode;
  563. //
  564. this.stream = undefined;
  565. this.url = undefined;
  566. this.pc = undefined;
  567. this.connected = false;
  568. this.streamAdded = false;
  569. this.state = "created";
  570. // webrtc peerConnection parameters
  571. this.pc_config = {'iceServers': [
  572. {'url': 'stun:stun.l.google.com:19302'},
  573. {'url': 'stun:stun1.l.google.com:19302'}
  574. ]};//{ "iceServers": this.view.iceServers };
  575. this.pc_constraints = { "optional": [ { "DtlsSrtpKeyAgreement": true } ] };
  576. // Set up audio and video regardless of what devices are present.
  577. this.sdpConstraints = {
  578. 'offerToReceiveAudio':1,
  579. 'offerToReceiveVideo':1 };
  580. this.connect = function( stream, sendOffer ) {
  581. var self = this;
  582. if ( this.pc === undefined ) {
  583. if ( this.view.debug ) console.log("Creating PeerConnection.");
  584. var iceCallback = function( event ) {
  585. //console.log( "------------------------ iceCallback ------------------------" );
  586. if ( event.candidate ) {
  587. var sMsg = {
  588. "type": 'candidate',
  589. "label": event.candidate.sdpMLineIndex,
  590. "id": event.candidate.sdpMid,
  591. "candidate": event.candidate.candidate
  592. };
  593. // each client creates a property for each other
  594. // the message value is broadcast via the property
  595. self.view.kernel.setProperty( self.peerNode.ID, self.view.kernel.moniker(), sMsg );
  596. } else {
  597. if ( self.view.debug ) console.log("End of candidates.");
  598. }
  599. };
  600. // if ( webrtcDetectedBrowser == "firefox" ) {
  601. // this.pc_config = {"iceServers":[{"url":"stun:23.21.150.121"}]};
  602. // }
  603. try {
  604. this.pc = new RTCPeerConnection( this.pc_config, this.pc_constraints);
  605. this.pc.onicecandidate = iceCallback;
  606. if ( self.view.debug ) console.log("Created RTCPeerConnnection with config \"" + JSON.stringify( this.pc_config ) + "\".");
  607. } catch (e) {
  608. console.log("Failed to create PeerConnection, exception: " + e.message);
  609. alert("Cannot create RTCPeerConnection object; WebRTC is not supported by this browser.");
  610. return;
  611. }
  612. this.pc.onnegotiationeeded = function( event ) {
  613. //debugger;
  614. //console.info( "onnegotiationeeded." );
  615. }
  616. this.pc.ontrack = function( event ) {
  617. if ( self.view.debug ) console.log("Remote stream added.");
  618. self.stream = event.streams[0];
  619. self.url = "url" //URL.createObjectURL( event.streams[0] );
  620. if ( self.view.debug ) console.log("Remote stream added. url: " + self.url );
  621. var divID = displayRemote.call( self.view, self.peerNode.moniker, self.stream, self.url, self.peerNode.displayName, view.kernel.moniker(), self.peerNode.color );
  622. if ( divID !== undefined ) {
  623. self.peerNode.videoDivID = divID;
  624. }
  625. };
  626. this.pc.onremovestream = function( event ) {
  627. if ( self.view.debug ) console.log("Remote stream removed.");
  628. };
  629. this.pc.onsignalingstatechange = function() {
  630. //console.info( "onsignalingstatechange state change." );
  631. }
  632. this.pc.oniceconnectionstatechange = function( ) {
  633. if ( self && self.pc ) {
  634. var state = self.pc.signalingState || self.pc.readyState;
  635. //console.info( "peerConnection state change: " + state );
  636. }
  637. }
  638. if ( stream ) {
  639. // stream.getVideoTracks();
  640. // stream.getAudioTracks();
  641. stream.getTracks().forEach(
  642. function(track) {
  643. self.pc.addTrack(
  644. track,
  645. stream
  646. );
  647. }
  648. );
  649. //this.pc.addStream( stream );
  650. this.streamAdded = true;
  651. }
  652. if ( sendOffer ){
  653. this.call();
  654. }
  655. }
  656. this.connected = ( this.pc !== undefined );
  657. };
  658. this.setMute = function( mute ) {
  659. if ( this.stream && this.stream.audioTracks && this.stream.audioTracks.length > 0 ) {
  660. if ( mute !== undefined ) {
  661. this.stream.audioTracks[0].enabled = !mute;
  662. }
  663. }
  664. }
  665. this.setPause = function( pause ) {
  666. if ( this.stream && this.stream.videoTracks && this.stream.videoTracks.length > 0 ) {
  667. if ( pause !== undefined ) {
  668. this.stream.videoTracks[0].enabled = !pause;
  669. }
  670. }
  671. }
  672. this.disconnect = function() {
  673. if ( this.view.debug ) console.log( "PC.disconnect " + this.peerID );
  674. if ( this.pc ) {
  675. this.pc.close();
  676. this.pc = undefined;
  677. }
  678. };
  679. this.processMessage = function( msg ) {
  680. //var msg = JSON.parse(message);
  681. if ( this.view.debug ) console.log('S->C: ' + JSON.stringify(msg) );
  682. if ( this.pc ) {
  683. if ( msg.type === 'offer') {
  684. // if ( this.view.stereo ) {
  685. // msg.sdp = addStereo( msg.sdp );
  686. // }
  687. this.pc.setRemoteDescription( new RTCSessionDescription( msg ) ); //msg.sdp
  688. this.answer();
  689. } else if ( msg.type === 'answer' && this.streamAdded ) {
  690. // if ( this.view.stereo ) {
  691. // msg.sdp = addStereo( msg.sdp );
  692. // }
  693. this.pc.setRemoteDescription( new RTCSessionDescription( msg ) ); //msg.sdp
  694. } else if ( msg.type === 'candidate' && this.streamAdded ) {
  695. var candidate = new RTCIceCandidate( {
  696. "sdpMLineIndex": msg.label,
  697. "candidate": msg.candidate
  698. } );
  699. this.pc.addIceCandidate( candidate );
  700. } else if ( msg.type === 'bye' && this.streamAdded ) {
  701. this.hangup();
  702. }
  703. }
  704. };
  705. this.answer = function() {
  706. if ( this.view.debug ) console.log( "Send answer to peer" );
  707. var self = this;
  708. var answerer = function( sessionDescription ) {
  709. // // Set Opus as the preferred codec in SDP if Opus is present.
  710. // sessionDescription.sdp = self.preferOpus( sessionDescription.sdp );
  711. // sessionDescription.sdp = self.setBandwidth( sessionDescription.sdp );
  712. self.pc.setLocalDescription( sessionDescription );
  713. self.view.kernel.setProperty( self.peerNode.ID, self.view.kernel.moniker(), sessionDescription );
  714. };
  715. function onCreateSessionDescriptionError(error) {
  716. console.log('Failed to create session description: ' + error.toString());
  717. }
  718. this.pc.createAnswer(
  719. self.sdpConstraints
  720. ).then(
  721. answerer,
  722. onCreateSessionDescriptionError
  723. );
  724. //this.pc.createAnswer( answerer, null, this.sdpConstraints);
  725. };
  726. this.call = function() {
  727. var self = this;
  728. var constraints = {
  729. offerToReceiveAudio: 1,
  730. offerToReceiveVideo: 1
  731. };
  732. var offerer = function( sessionDescription ) {
  733. self.pc.setLocalDescription(sessionDescription).then(
  734. function() {
  735. onSetLocalSuccess(self.pc);
  736. },
  737. onSetSessionDescriptionError
  738. );
  739. function onSetLocalSuccess(pc) {
  740. console.log(self.pc + ' setLocalDescription complete');
  741. }
  742. function onSetSessionDescriptionError(error) {
  743. console.log('Failed to set session description: ' + error.toString());
  744. }
  745. // Set Opus as the preferred codec in SDP if Opus is present.
  746. // sessionDescription.sdp = self.preferOpus( sessionDescription.sdp );
  747. // sessionDescription.sdp = self.setBandwidth( sessionDescription.sdp );
  748. // self.pc.setLocalDescription( sessionDescription );
  749. //sendSignalMessage.call( sessionDescription, self.peerID );
  750. self.view.kernel.setProperty( self.peerNode.ID, self.view.kernel.moniker(), sessionDescription );
  751. };
  752. var onFailure = function(e) {
  753. console.log(e)
  754. }
  755. self.pc.createOffer(
  756. constraints
  757. ).then(
  758. offerer,
  759. onFailure
  760. );
  761. //this.pc.createOffer( offerer, onFailure, constraints );
  762. };
  763. this.setBandwidth = function( sdp ) {
  764. // apparently this only works in chrome
  765. if ( this.bandwidth === undefined || moz ) {
  766. return sdp;
  767. }
  768. // remove existing bandwidth lines
  769. sdp = sdp.replace(/b=AS([^\r\n]+\r\n)/g, '');
  770. if ( this.bandwidth.audio ) {
  771. sdp = sdp.replace(/a=mid:audio\r\n/g, 'a=mid:audio\r\nb=AS:' + this.bandwidth.audio + '\r\n');
  772. }
  773. if ( this.bandwidth.video ) {
  774. sdp = sdp.replace(/a=mid:video\r\n/g, 'a=mid:video\r\nb=AS:' + this.bandwidth.video + '\r\n');
  775. }
  776. if ( this.bandwidth.data /*&& !options.preferSCTP */ ) {
  777. sdp = sdp.replace(/a=mid:data\r\n/g, 'a=mid:data\r\nb=AS:' + this.bandwidth.data + '\r\n');
  778. }
  779. return sdp;
  780. }
  781. this.getStats = function(){
  782. if ( this.pc && this.pc.getStats ) {
  783. console.info( "pc.iceConnectionState = " + this.pc.iceConnectionState );
  784. console.info( " pc.iceGatheringState = " + this.pc.iceGatheringState );
  785. console.info( " pc.readyState = " + this.pc.readyState );
  786. console.info( " pc.signalingState = " + this.pc.signalingState );
  787. var consoleStats = function( obj ) {
  788. console.info( ' Timestamp:' + obj.timestamp );
  789. if ( obj.id ) {
  790. console.info( ' id: ' + obj.id );
  791. }
  792. if ( obj.type ) {
  793. console.info( ' type: ' + obj.type );
  794. }
  795. if ( obj.names ) {
  796. var names = obj.names();
  797. for ( var i = 0; i < names.length; ++i ) {
  798. console.info( " "+names[ i ]+": " + obj.stat( names[ i ] ) );
  799. }
  800. } else {
  801. if ( obj.stat && obj.stat( 'audioOutputLevel' ) ) {
  802. console.info( " audioOutputLevel: " + obj.stat( 'audioOutputLevel' ) );
  803. }
  804. }
  805. };
  806. // local function
  807. var readStats = function( stats ) {
  808. var results = stats.result();
  809. var bitrateText = 'No bitrate stats';
  810. for ( var i = 0; i < results.length; ++i ) {
  811. var res = results[ i ];
  812. console.info( 'Report ' + i );
  813. if ( !res.local || res.local === res ) {
  814. consoleStats( res );
  815. // The bandwidth info for video is in a type ssrc stats record
  816. // with googFrameHeightReceived defined.
  817. // Should check for mediatype = video, but this is not
  818. // implemented yet.
  819. if ( res.type == 'ssrc' && res.stat( 'googFrameHeightReceived' ) ) {
  820. var bytesNow = res.stat( 'bytesReceived' );
  821. if ( timestampPrev > 0) {
  822. var bitRate = Math.round( ( bytesNow - bytesPrev ) * 8 / ( res.timestamp - timestampPrev ) );
  823. bitrateText = bitRate + ' kbits/sec';
  824. }
  825. timestampPrev = res.timestamp;
  826. bytesPrev = bytesNow;
  827. }
  828. } else {
  829. // Pre-227.0.1445 (188719) browser
  830. if ( res.local ) {
  831. console.info( " Local: " );
  832. consoleStats( res.local );
  833. }
  834. if ( res.remote ) {
  835. console.info( " Remote: " );
  836. consoleStats( res.remote );
  837. }
  838. }
  839. }
  840. console.info( " bitrate: " + bitrateText )
  841. }
  842. this.pc.getStats( readStats );
  843. }
  844. }
  845. this.hangup = function() {
  846. if ( this.view.debug ) console.log( "PC.hangup " + this.id );
  847. if ( this.pc ) {
  848. this.pc.close();
  849. this.pc = undefined;
  850. }
  851. };
  852. this.mergeConstraints = function( cons1, cons2 ) {
  853. var merged = cons1;
  854. for (var name in cons2.mandatory) {
  855. merged.mandatory[ name ] = cons2.mandatory[ name ];
  856. }
  857. merged.optional.concat( cons2.optional );
  858. return merged;
  859. }
  860. // Set Opus as the default audio codec if it's present.
  861. this.preferOpus = function( sdp ) {
  862. var sdpLines = sdp.split( '\r\n' );
  863. // Search for m line.
  864. for ( var i = 0; i < sdpLines.length; i++ ) {
  865. if ( sdpLines[i].search( 'm=audio' ) !== -1 ) {
  866. var mLineIndex = i;
  867. break;
  868. }
  869. }
  870. if ( mLineIndex === null ) {
  871. return sdp;
  872. }
  873. // for ( var i = 0; i < sdpLines.length; i++ ) {
  874. // if ( i == 0 ) console.info( "=============================================" );
  875. // console.info( "sdpLines["+i+"] = " + sdpLines[i] );
  876. // }
  877. // If Opus is available, set it as the default in m line.
  878. for ( var i = 0; i < sdpLines.length; i++ ) {
  879. if ( sdpLines[i].search( 'opus/48000' ) !== -1 ) {
  880. var opusPayload = this.extractSdp( sdpLines[i], /:(\d+) opus\/48000/i );
  881. if ( opusPayload) {
  882. sdpLines[ mLineIndex ] = this.setDefaultCodec( sdpLines[ mLineIndex ], opusPayload );
  883. }
  884. break;
  885. }
  886. }
  887. // Remove CN in m line and sdp.
  888. sdpLines = this.removeCN( sdpLines, mLineIndex );
  889. sdp = sdpLines.join('\r\n');
  890. return sdp;
  891. }
  892. // Set Opus in stereo if stereo is enabled.
  893. function addStereo( sdp ) {
  894. var sdpLines = sdp.split('\r\n');
  895. // Find opus payload.
  896. for (var i = 0; i < sdpLines.length; i++) {
  897. if (sdpLines[i].search('opus/48000') !== -1) {
  898. var opusPayload = extractSdp(sdpLines[i], /:(\d+) opus\/48000/i);
  899. break;
  900. }
  901. }
  902. // Find the payload in fmtp line.
  903. for (var i = 0; i < sdpLines.length; i++) {
  904. if (sdpLines[i].search('a=fmtp') !== -1) {
  905. var payload = extractSdp(sdpLines[i], /a=fmtp:(\d+)/ );
  906. if (payload === opusPayload) {
  907. var fmtpLineIndex = i;
  908. break;
  909. }
  910. }
  911. }
  912. // No fmtp line found.
  913. if (fmtpLineIndex === null)
  914. return sdp;
  915. // Append stereo=1 to fmtp line.
  916. sdpLines[fmtpLineIndex] = sdpLines[fmtpLineIndex].concat(' stereo=1');
  917. sdp = sdpLines.join('\r\n');
  918. return sdp;
  919. }
  920. // Strip CN from sdp before CN constraints is ready.
  921. this.removeCN = function( sdpLines, mLineIndex ) {
  922. var mLineElements = sdpLines[mLineIndex].split( ' ' );
  923. // Scan from end for the convenience of removing an item.
  924. for ( var i = sdpLines.length-1; i >= 0; i-- ) {
  925. var payload = this.extractSdp( sdpLines[i], /a=rtpmap:(\d+) CN\/\d+/i );
  926. if ( payload ) {
  927. var cnPos = mLineElements.indexOf( payload );
  928. if ( cnPos !== -1 ) {
  929. // Remove CN payload from m line.
  930. mLineElements.splice( cnPos, 1 );
  931. }
  932. // Remove CN line in sdp
  933. sdpLines.splice( i, 1 );
  934. }
  935. }
  936. sdpLines[ mLineIndex ] = mLineElements.join( ' ' );
  937. return sdpLines;
  938. }
  939. this.extractSdp = function( sdpLine, pattern ) {
  940. var result = sdpLine.match( pattern );
  941. return ( result && result.length == 2 ) ? result[ 1 ] : null;
  942. }
  943. // Set the selected codec to the first in m line.
  944. this.setDefaultCodec = function( mLine, payload ) {
  945. var elements = mLine.split( ' ' );
  946. var newLine = new Array();
  947. var index = 0;
  948. for ( var i = 0; i < elements.length; i++ ) {
  949. if ( index === 3 ) // Format of media starts from the fourth.
  950. newLine[ index++ ] = payload; // Put target payload to the first.
  951. if ( elements[ i ] !== payload )
  952. newLine[ index++ ] = elements[ i ];
  953. }
  954. return newLine.join( ' ' );
  955. }
  956. }
  957. } );