webrtc.js 41 KB

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