webrtc.js 43 KB

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