webrtc.js 44 KB

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