webrtc.js 45 KB

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