webrtc.1.js 41 KB

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