webrtc.js 45 KB

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