webrtc.js 44 KB

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