webrtc.js 38 KB

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