webrtc.js 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  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) {
  315. video.setAttribute("muted", false);
  316. video.volume = 0;
  317. }
  318. // let audioID = '#audio-' + id;
  319. // var audio = document.querySelector(audioID);
  320. // if (!audio) {
  321. // audio = document.createElement('audio');
  322. // }
  323. // audio.setAttribute('id', audioID);
  324. var assets = document.querySelector('a-assets');
  325. // if (!assets) {
  326. // assets = document.createElement('a-assets');
  327. // document.querySelector('a-scene').appendChild(assets);
  328. // }
  329. if (!assets.contains(video)) {
  330. assets.appendChild(video);
  331. }
  332. // if (!assets.contains(audio)) {
  333. // assets.appendChild(audio);
  334. // }
  335. return video //{'video': video, 'audio': audio};
  336. }
  337. function getPrototypes( extendsID ) {
  338. var prototypes = [];
  339. var id = extendsID;
  340. while ( id !== undefined ) {
  341. prototypes.push( id );
  342. id = this.kernel.prototype( id );
  343. }
  344. return prototypes;
  345. }
  346. function getPeer( moniker ) {
  347. var clientNode;
  348. for ( var id in this.state.clients ) {
  349. if ( this.state.clients[id].moniker == moniker ) {
  350. clientNode = this.state.clients[id];
  351. break;
  352. }
  353. }
  354. return clientNode;
  355. }
  356. function displayLocal( stream, name) {
  357. var id = this.kernel.moniker();
  358. return displayVideo.call( this, id, stream, this.local.url, name, id, true);
  359. }
  360. function displayVideo( id, stream, url, name, destMoniker, local) {
  361. let va = createVideoElementAsAsset(name, local);
  362. //video.setAttribute('src', url);
  363. va.srcObject = stream;
  364. //var audioCtx = new AudioContext();
  365. //var source = audioCtx.createMediaStreamSource(stream);
  366. //va.audio.src = stream;
  367. this.kernel.callMethod( 'avatar-'+id, "setVideoTexture", [name]);
  368. return id;
  369. }
  370. function removeVideo( client ) {
  371. // if ( client.videoDivID ) {
  372. // var $videoWin = $( "#" + client.videoDivID );
  373. // if ( $videoWin ) {
  374. // $videoWin.remove();
  375. // }
  376. // client.videoDivID = undefined;
  377. // }
  378. // this.kernel.callMethod( this.kernel.application(), "removeVideo", [ client.moniker ] );
  379. }
  380. function displayRemote( id, stream, url, name, destMoniker, color ) {
  381. let audioID = 'audio-' + name;
  382. this.kernel.callMethod( 'avatar-'+id, "setSoundWebRTC", [audioID]);
  383. return displayVideo.call( this, id, stream, url, name, destMoniker, true );
  384. }
  385. function capture( media ) {
  386. if ( this.local.stream === undefined && ( media.video || media.audio ) ) {
  387. var self = this;
  388. var constraints = {
  389. //audio: true,
  390. audio: {
  391. "sampleSize": 16,
  392. "channelCount": 2,
  393. "echoCancellation": true
  394. },
  395. video: true
  396. };
  397. navigator.mediaDevices.getUserMedia(constraints).then(handleSuccess).catch(handleError);
  398. function handleError(error) {
  399. console.log('navigator.getUserMedia error: ', error);
  400. }
  401. function handleSuccess(stream) {
  402. // var videoTracks = stream.getVideoTracks();
  403. // console.log('Got stream with constraints:', constraints);
  404. // if (videoTracks.length) {
  405. // videoTracks[0].enabled = true;
  406. // }
  407. self.local.url = "url" //URL.createObjectURL( stream );
  408. self.local.stream = stream;
  409. self.kernel.setProperty( self.local.ID, "localUrl", self.local.url );
  410. var localNode = self.state.clients[ self.local.ID ];
  411. self.muteAudio(false);
  412. self.muteVideo(false);
  413. let webRTCGUI = document.querySelector('#webrtcswitch');
  414. if (webRTCGUI) webRTCGUI.setAttribute("aria-pressed", true);
  415. let videoTracks = stream.getVideoTracks();
  416. let vstatus = videoTracks[0].enabled;
  417. let vidui = document.querySelector('#webrtcvideo');
  418. const viduicomp = new mdc.iconButton.MDCIconButtonToggle(vidui); //new mdc.select.MDCIconToggle
  419. if (vidui) viduicomp.on = vstatus;
  420. let audioTracks = stream.getAudioTracks();
  421. let astatus = audioTracks[0].enabled;
  422. let micui = document.querySelector('#webrtcaudio');
  423. const micuicomp = new mdc.iconButton.MDCIconButtonToggle(micui);
  424. if (micui) micuicomp.on = astatus;
  425. displayLocal.call( self, stream, localNode.displayName);
  426. sendOffers.call( self );
  427. }
  428. }
  429. }
  430. function appMoniker( name ) {
  431. return name.substr( 7, name.length-1 );
  432. }
  433. function findClientByMoniker( moniker ) {
  434. var client = undefined;
  435. for ( var id in this.state.clients ) {
  436. if ( client === undefined && moniker == this.state.clients[ id ].moniker ) {
  437. client = this.state.clients[ id ];
  438. }
  439. }
  440. return client;
  441. }
  442. function removeClient( client ) {
  443. if ( client ) {
  444. removeVideo.call( this, client );
  445. }
  446. }
  447. function sendOffers() {
  448. var peerNode;
  449. for ( var id in this.state.clients ) {
  450. if ( id != this.local.ID ) {
  451. peerNode = this.state.clients[ id ];
  452. // if there's a url then connect
  453. if ( peerNode.localUrl && peerNode.localUrl != "" && peerNode.connection === undefined ) {
  454. createPeerConnection.call( this, peerNode, true );
  455. }
  456. }
  457. }
  458. }
  459. function updateSharing( nodeID, sharing ) {
  460. setMute.call( this, !sharing.audio );
  461. setPause.call( this, !sharing.video );
  462. }
  463. function turnOnOffTracks( mute ) {
  464. let str = this.local.stream;
  465. if ( str ) {
  466. var audioTracks = str.getAudioTracks();
  467. var videoTracks = str.getVideoTracks();
  468. audioTracks.forEach(function(track) {
  469. track.enabled = mute[0];
  470. });
  471. videoTracks.forEach(function(track) {
  472. track.enabled = mute[0];
  473. });
  474. }
  475. };
  476. function muteAudio( mute ) {
  477. let str = this.local.stream;
  478. if ( str ) {
  479. var audioTracks = str.getAudioTracks();
  480. audioTracks.forEach(function(track) {
  481. track.enabled = mute;
  482. });
  483. }
  484. };
  485. function setMute( mute ) {
  486. if ( this.local.stream && this.local.stream.audioTracks && this.local.stream.audioTracks.length > 0 ) {
  487. if ( mute !== undefined ) {
  488. this.local.stream.audioTracks[0].enabled = !mute;
  489. }
  490. }
  491. };
  492. function setPause( pause ) {
  493. if ( this.local.stream && this.local.stream.videoTracks && this.local.stream.videoTracks.length > 0 ) {
  494. if ( pause !== undefined ) {
  495. this.local.stream.videoTracks[0].enabled = !pause;
  496. }
  497. }
  498. }
  499. function release() {
  500. for ( id in this.connections ) {
  501. this.connections[id].disconnect();
  502. }
  503. this.connections = {};
  504. }
  505. function hasStream() {
  506. return ( this.stream !== undefined );
  507. }
  508. function createPeerConnection( peerNode, sendOffer ) {
  509. if ( peerNode ) {
  510. if ( peerNode.connection === undefined ) {
  511. peerNode.connection = new mediaConnection( this, peerNode );
  512. peerNode.connection.connect( this.local.stream, sendOffer );
  513. //if ( this.bandwidth !== undefined ) {
  514. // debugger;
  515. //}
  516. }
  517. }
  518. }
  519. function handlePeerMessage( propertyName, msg ) {
  520. var peerNode = getPeer.call( this, propertyName )
  521. if ( peerNode ) {
  522. if ( peerNode.connection !== undefined ) {
  523. peerNode.connection.processMessage( msg );
  524. } else {
  525. if ( msg.type === 'offer' ) {
  526. this.msgQueue.unshift( msg );
  527. peerNode.connection = new mediaConnection( this, peerNode );
  528. peerNode.connection.connect( this.local.stream, false );
  529. while ( this.msgQueue.length > 0 ) {
  530. peerNode.connection.processMessage( this.msgQueue.shift() );
  531. }
  532. this.msgQueue = [];
  533. } else {
  534. this.msgQueue.push( msg );
  535. }
  536. }
  537. }
  538. }
  539. function deletePeerConnection( peerID ) {
  540. var peerNode = this.state.clients[ peerID ];
  541. if ( peerNode ) {
  542. peerNode.connection.disconnect();
  543. peerNode.connection = undefined;
  544. }
  545. }
  546. function getConnectionStats() {
  547. var peerNode = undefined;
  548. for ( var id in this.state.clients ) {
  549. peerNode = this.state.clients[ id ];
  550. if ( peerNode && peerNode.connection ) {
  551. peerNode.connection.getStats();
  552. }
  553. }
  554. }
  555. function isClientDefinition( prototypes ) {
  556. var foundClient = false;
  557. if ( prototypes ) {
  558. var len = prototypes.length;
  559. for ( var i = 0; i < len && !foundClient; i++ ) {
  560. foundClient = ( prototypes[i] == "http://vwf.example.com/aframe/avatar.vwf" );
  561. }
  562. }
  563. return foundClient;
  564. }
  565. function isClientInstanceDef( nodeID ) {
  566. return ( nodeID == "http://vwf.example.com/clients.vwf" );
  567. }
  568. function mediaConnection( view, peerNode ) {
  569. this.view = view;
  570. this.peerNode = peerNode;
  571. //
  572. this.stream = undefined;
  573. this.url = undefined;
  574. this.pc = undefined;
  575. this.connected = false;
  576. this.streamAdded = false;
  577. this.state = "created";
  578. // webrtc peerConnection parameters
  579. this.pc_config = {'iceServers': [
  580. {'url': 'stun:stun.l.google.com:19302'},
  581. {'url': 'stun:stun1.l.google.com:19302'}
  582. ]};//{ "iceServers": this.view.iceServers };
  583. this.pc_constraints = { "optional": [ { "DtlsSrtpKeyAgreement": true } ] };
  584. // Set up audio and video regardless of what devices are present.
  585. this.sdpConstraints = {
  586. 'offerToReceiveAudio':1,
  587. 'offerToReceiveVideo':1 };
  588. this.connect = function( stream, sendOffer ) {
  589. var self = this;
  590. if ( this.pc === undefined ) {
  591. if ( this.view.debug ) console.log("Creating PeerConnection.");
  592. var iceCallback = function( event ) {
  593. //console.log( "------------------------ iceCallback ------------------------" );
  594. if ( event.candidate ) {
  595. var sMsg = {
  596. "type": 'candidate',
  597. "label": event.candidate.sdpMLineIndex,
  598. "id": event.candidate.sdpMid,
  599. "candidate": event.candidate.candidate
  600. };
  601. // each client creates a property for each other
  602. // the message value is broadcast via the property
  603. self.view.kernel.setProperty( self.peerNode.ID, self.view.kernel.moniker(), sMsg );
  604. } else {
  605. if ( self.view.debug ) console.log("End of candidates.");
  606. }
  607. };
  608. // if ( webrtcDetectedBrowser == "firefox" ) {
  609. // this.pc_config = {"iceServers":[{"url":"stun:23.21.150.121"}]};
  610. // }
  611. try {
  612. this.pc = new RTCPeerConnection( this.pc_config, this.pc_constraints);
  613. this.pc.onicecandidate = iceCallback;
  614. if ( self.view.debug ) console.log("Created RTCPeerConnnection with config \"" + JSON.stringify( this.pc_config ) + "\".");
  615. } catch (e) {
  616. console.log("Failed to create PeerConnection, exception: " + e.message);
  617. alert("Cannot create RTCPeerConnection object; WebRTC is not supported by this browser.");
  618. return;
  619. }
  620. this.pc.onnegotiationeeded = function( event ) {
  621. //debugger;
  622. //console.info( "onnegotiationeeded." );
  623. }
  624. this.pc.ontrack = function( event ) {
  625. if ( self.view.debug ) console.log("Remote stream added.");
  626. self.stream = event.streams[0];
  627. self.url = "url" //URL.createObjectURL( event.streams[0] );
  628. if ( self.view.debug ) console.log("Remote stream added. url: " + self.url );
  629. var divID = displayRemote.call( self.view, self.peerNode.moniker, self.stream, self.url, self.peerNode.displayName, view.kernel.moniker(), self.peerNode.color );
  630. if ( divID !== undefined ) {
  631. self.peerNode.videoDivID = divID;
  632. }
  633. };
  634. this.pc.onremovestream = function( event ) {
  635. if ( self.view.debug ) console.log("Remote stream removed.");
  636. };
  637. this.pc.onsignalingstatechange = function() {
  638. //console.info( "onsignalingstatechange state change." );
  639. }
  640. this.pc.oniceconnectionstatechange = function( ) {
  641. if ( self && self.pc ) {
  642. var state = self.pc.signalingState || self.pc.readyState;
  643. //console.info( "peerConnection state change: " + state );
  644. }
  645. }
  646. if ( stream ) {
  647. // stream.getVideoTracks();
  648. // stream.getAudioTracks();
  649. stream.getTracks().forEach(
  650. function(track) {
  651. self.pc.addTrack(
  652. track,
  653. stream
  654. );
  655. }
  656. );
  657. //this.pc.addStream( stream );
  658. this.streamAdded = true;
  659. }
  660. if ( sendOffer ){
  661. this.call();
  662. }
  663. }
  664. this.connected = ( this.pc !== undefined );
  665. };
  666. this.setMute = function( mute ) {
  667. if ( this.stream && this.stream.audioTracks && this.stream.audioTracks.length > 0 ) {
  668. if ( mute !== undefined ) {
  669. this.stream.audioTracks[0].enabled = !mute;
  670. }
  671. }
  672. }
  673. this.setPause = function( pause ) {
  674. if ( this.stream && this.stream.videoTracks && this.stream.videoTracks.length > 0 ) {
  675. if ( pause !== undefined ) {
  676. this.stream.videoTracks[0].enabled = !pause;
  677. }
  678. }
  679. }
  680. this.disconnect = function() {
  681. if ( this.view.debug ) console.log( "PC.disconnect " + this.peerID );
  682. if ( this.pc ) {
  683. this.pc.close();
  684. this.pc = undefined;
  685. }
  686. };
  687. this.processMessage = function( msg ) {
  688. //var msg = JSON.parse(message);
  689. if ( this.view.debug ) console.log('S->C: ' + JSON.stringify(msg) );
  690. if ( this.pc ) {
  691. if ( msg.type === 'offer') {
  692. // if ( this.view.stereo ) {
  693. // msg.sdp = addStereo( msg.sdp );
  694. // }
  695. this.pc.setRemoteDescription( new RTCSessionDescription( msg ) ); //msg.sdp
  696. this.answer();
  697. } else if ( msg.type === 'answer' && this.streamAdded ) {
  698. // if ( this.view.stereo ) {
  699. // msg.sdp = addStereo( msg.sdp );
  700. // }
  701. this.pc.setRemoteDescription( new RTCSessionDescription( msg ) ); //msg.sdp
  702. } else if ( msg.type === 'candidate' && this.streamAdded ) {
  703. var candidate = new RTCIceCandidate( {
  704. "sdpMLineIndex": msg.label,
  705. "candidate": msg.candidate
  706. } );
  707. this.pc.addIceCandidate( candidate );
  708. } else if ( msg.type === 'bye' && this.streamAdded ) {
  709. this.hangup();
  710. }
  711. }
  712. };
  713. this.answer = function() {
  714. if ( this.view.debug ) console.log( "Send answer to peer" );
  715. var self = this;
  716. var answerer = function( sessionDescription ) {
  717. // // Set Opus as the preferred codec in SDP if Opus is present.
  718. // sessionDescription.sdp = self.preferOpus( sessionDescription.sdp );
  719. // sessionDescription.sdp = self.setBandwidth( sessionDescription.sdp );
  720. self.pc.setLocalDescription( sessionDescription );
  721. self.view.kernel.setProperty( self.peerNode.ID, self.view.kernel.moniker(), sessionDescription );
  722. };
  723. function onCreateSessionDescriptionError(error) {
  724. console.log('Failed to create session description: ' + error.toString());
  725. }
  726. this.pc.createAnswer(
  727. self.sdpConstraints
  728. ).then(
  729. answerer,
  730. onCreateSessionDescriptionError
  731. );
  732. //this.pc.createAnswer( answerer, null, this.sdpConstraints);
  733. };
  734. this.call = function() {
  735. var self = this;
  736. var constraints = {
  737. offerToReceiveAudio: 1,
  738. offerToReceiveVideo: 1
  739. };
  740. var offerer = function( sessionDescription ) {
  741. self.pc.setLocalDescription(sessionDescription).then(
  742. function() {
  743. onSetLocalSuccess(self.pc);
  744. },
  745. onSetSessionDescriptionError
  746. );
  747. function onSetLocalSuccess(pc) {
  748. console.log(self.pc + ' setLocalDescription complete');
  749. }
  750. function onSetSessionDescriptionError(error) {
  751. console.log('Failed to set session description: ' + error.toString());
  752. }
  753. // Set Opus as the preferred codec in SDP if Opus is present.
  754. // sessionDescription.sdp = self.preferOpus( sessionDescription.sdp );
  755. // sessionDescription.sdp = self.setBandwidth( sessionDescription.sdp );
  756. // self.pc.setLocalDescription( sessionDescription );
  757. //sendSignalMessage.call( sessionDescription, self.peerID );
  758. self.view.kernel.setProperty( self.peerNode.ID, self.view.kernel.moniker(), sessionDescription );
  759. };
  760. var onFailure = function(e) {
  761. console.log(e)
  762. }
  763. self.pc.createOffer(
  764. constraints
  765. ).then(
  766. offerer,
  767. onFailure
  768. );
  769. //this.pc.createOffer( offerer, onFailure, constraints );
  770. };
  771. this.setBandwidth = function( sdp ) {
  772. // apparently this only works in chrome
  773. if ( this.bandwidth === undefined || moz ) {
  774. return sdp;
  775. }
  776. // remove existing bandwidth lines
  777. sdp = sdp.replace(/b=AS([^\r\n]+\r\n)/g, '');
  778. if ( this.bandwidth.audio ) {
  779. sdp = sdp.replace(/a=mid:audio\r\n/g, 'a=mid:audio\r\nb=AS:' + this.bandwidth.audio + '\r\n');
  780. }
  781. if ( this.bandwidth.video ) {
  782. sdp = sdp.replace(/a=mid:video\r\n/g, 'a=mid:video\r\nb=AS:' + this.bandwidth.video + '\r\n');
  783. }
  784. if ( this.bandwidth.data /*&& !options.preferSCTP */ ) {
  785. sdp = sdp.replace(/a=mid:data\r\n/g, 'a=mid:data\r\nb=AS:' + this.bandwidth.data + '\r\n');
  786. }
  787. return sdp;
  788. }
  789. this.getStats = function(){
  790. if ( this.pc && this.pc.getStats ) {
  791. console.info( "pc.iceConnectionState = " + this.pc.iceConnectionState );
  792. console.info( " pc.iceGatheringState = " + this.pc.iceGatheringState );
  793. console.info( " pc.readyState = " + this.pc.readyState );
  794. console.info( " pc.signalingState = " + this.pc.signalingState );
  795. var consoleStats = function( obj ) {
  796. console.info( ' Timestamp:' + obj.timestamp );
  797. if ( obj.id ) {
  798. console.info( ' id: ' + obj.id );
  799. }
  800. if ( obj.type ) {
  801. console.info( ' type: ' + obj.type );
  802. }
  803. if ( obj.names ) {
  804. var names = obj.names();
  805. for ( var i = 0; i < names.length; ++i ) {
  806. console.info( " "+names[ i ]+": " + obj.stat( names[ i ] ) );
  807. }
  808. } else {
  809. if ( obj.stat && obj.stat( 'audioOutputLevel' ) ) {
  810. console.info( " audioOutputLevel: " + obj.stat( 'audioOutputLevel' ) );
  811. }
  812. }
  813. };
  814. // local function
  815. var readStats = function( stats ) {
  816. var results = stats.result();
  817. var bitrateText = 'No bitrate stats';
  818. for ( var i = 0; i < results.length; ++i ) {
  819. var res = results[ i ];
  820. console.info( 'Report ' + i );
  821. if ( !res.local || res.local === res ) {
  822. consoleStats( res );
  823. // The bandwidth info for video is in a type ssrc stats record
  824. // with googFrameHeightReceived defined.
  825. // Should check for mediatype = video, but this is not
  826. // implemented yet.
  827. if ( res.type == 'ssrc' && res.stat( 'googFrameHeightReceived' ) ) {
  828. var bytesNow = res.stat( 'bytesReceived' );
  829. if ( timestampPrev > 0) {
  830. var bitRate = Math.round( ( bytesNow - bytesPrev ) * 8 / ( res.timestamp - timestampPrev ) );
  831. bitrateText = bitRate + ' kbits/sec';
  832. }
  833. timestampPrev = res.timestamp;
  834. bytesPrev = bytesNow;
  835. }
  836. } else {
  837. // Pre-227.0.1445 (188719) browser
  838. if ( res.local ) {
  839. console.info( " Local: " );
  840. consoleStats( res.local );
  841. }
  842. if ( res.remote ) {
  843. console.info( " Remote: " );
  844. consoleStats( res.remote );
  845. }
  846. }
  847. }
  848. console.info( " bitrate: " + bitrateText )
  849. }
  850. this.pc.getStats( readStats );
  851. }
  852. }
  853. this.hangup = function() {
  854. if ( this.view.debug ) console.log( "PC.hangup " + this.id );
  855. if ( this.pc ) {
  856. this.pc.close();
  857. this.pc = undefined;
  858. }
  859. };
  860. this.mergeConstraints = function( cons1, cons2 ) {
  861. var merged = cons1;
  862. for (var name in cons2.mandatory) {
  863. merged.mandatory[ name ] = cons2.mandatory[ name ];
  864. }
  865. merged.optional.concat( cons2.optional );
  866. return merged;
  867. }
  868. // Set Opus as the default audio codec if it's present.
  869. this.preferOpus = function( sdp ) {
  870. var sdpLines = sdp.split( '\r\n' );
  871. // Search for m line.
  872. for ( var i = 0; i < sdpLines.length; i++ ) {
  873. if ( sdpLines[i].search( 'm=audio' ) !== -1 ) {
  874. var mLineIndex = i;
  875. break;
  876. }
  877. }
  878. if ( mLineIndex === null ) {
  879. return sdp;
  880. }
  881. // for ( var i = 0; i < sdpLines.length; i++ ) {
  882. // if ( i == 0 ) console.info( "=============================================" );
  883. // console.info( "sdpLines["+i+"] = " + sdpLines[i] );
  884. // }
  885. // If Opus is available, set it as the default in m line.
  886. for ( var i = 0; i < sdpLines.length; i++ ) {
  887. if ( sdpLines[i].search( 'opus/48000' ) !== -1 ) {
  888. var opusPayload = this.extractSdp( sdpLines[i], /:(\d+) opus\/48000/i );
  889. if ( opusPayload) {
  890. sdpLines[ mLineIndex ] = this.setDefaultCodec( sdpLines[ mLineIndex ], opusPayload );
  891. }
  892. break;
  893. }
  894. }
  895. // Remove CN in m line and sdp.
  896. sdpLines = this.removeCN( sdpLines, mLineIndex );
  897. sdp = sdpLines.join('\r\n');
  898. return sdp;
  899. }
  900. // Set Opus in stereo if stereo is enabled.
  901. function addStereo( sdp ) {
  902. var sdpLines = sdp.split('\r\n');
  903. // Find opus payload.
  904. for (var i = 0; i < sdpLines.length; i++) {
  905. if (sdpLines[i].search('opus/48000') !== -1) {
  906. var opusPayload = extractSdp(sdpLines[i], /:(\d+) opus\/48000/i);
  907. break;
  908. }
  909. }
  910. // Find the payload in fmtp line.
  911. for (var i = 0; i < sdpLines.length; i++) {
  912. if (sdpLines[i].search('a=fmtp') !== -1) {
  913. var payload = extractSdp(sdpLines[i], /a=fmtp:(\d+)/ );
  914. if (payload === opusPayload) {
  915. var fmtpLineIndex = i;
  916. break;
  917. }
  918. }
  919. }
  920. // No fmtp line found.
  921. if (fmtpLineIndex === null)
  922. return sdp;
  923. // Append stereo=1 to fmtp line.
  924. sdpLines[fmtpLineIndex] = sdpLines[fmtpLineIndex].concat(' stereo=1');
  925. sdp = sdpLines.join('\r\n');
  926. return sdp;
  927. }
  928. // Strip CN from sdp before CN constraints is ready.
  929. this.removeCN = function( sdpLines, mLineIndex ) {
  930. var mLineElements = sdpLines[mLineIndex].split( ' ' );
  931. // Scan from end for the convenience of removing an item.
  932. for ( var i = sdpLines.length-1; i >= 0; i-- ) {
  933. var payload = this.extractSdp( sdpLines[i], /a=rtpmap:(\d+) CN\/\d+/i );
  934. if ( payload ) {
  935. var cnPos = mLineElements.indexOf( payload );
  936. if ( cnPos !== -1 ) {
  937. // Remove CN payload from m line.
  938. mLineElements.splice( cnPos, 1 );
  939. }
  940. // Remove CN line in sdp
  941. sdpLines.splice( i, 1 );
  942. }
  943. }
  944. sdpLines[ mLineIndex ] = mLineElements.join( ' ' );
  945. return sdpLines;
  946. }
  947. this.extractSdp = function( sdpLine, pattern ) {
  948. var result = sdpLine.match( pattern );
  949. return ( result && result.length == 2 ) ? result[ 1 ] : null;
  950. }
  951. // Set the selected codec to the first in m line.
  952. this.setDefaultCodec = function( mLine, payload ) {
  953. var elements = mLine.split( ' ' );
  954. var newLine = new Array();
  955. var index = 0;
  956. for ( var i = 0; i < elements.length; i++ ) {
  957. if ( index === 3 ) // Format of media starts from the fourth.
  958. newLine[ index++ ] = payload; // Put target payload to the first.
  959. if ( elements[ i ] !== payload )
  960. newLine[ index++ ] = elements[ i ];
  961. }
  962. return newLine.join( ' ' );
  963. }
  964. }
  965. } );