You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

simulcast.bundle.js 37KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  1. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.simulcast=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. /**
  3. *
  4. * @constructor
  5. */
  6. function SimulcastLogger(name, lvl) {
  7. this.name = name;
  8. this.lvl = lvl;
  9. }
  10. SimulcastLogger.prototype.log = function (text) {
  11. if (this.lvl) {
  12. console.log(text);
  13. }
  14. };
  15. SimulcastLogger.prototype.info = function (text) {
  16. if (this.lvl > 1) {
  17. console.info(text);
  18. }
  19. };
  20. SimulcastLogger.prototype.fine = function (text) {
  21. if (this.lvl > 2) {
  22. console.log(text);
  23. }
  24. };
  25. SimulcastLogger.prototype.error = function (text) {
  26. console.error(text);
  27. };
  28. module.exports = SimulcastLogger;
  29. },{}],2:[function(require,module,exports){
  30. var SimulcastLogger = require("./SimulcastLogger");
  31. var SimulcastUtils = require("./SimulcastUtils");
  32. function SimulcastReceiver() {
  33. this.simulcastUtils = new SimulcastUtils();
  34. this.logger = new SimulcastLogger('SimulcastReceiver', 1);
  35. }
  36. SimulcastReceiver.prototype._remoteVideoSourceCache = '';
  37. SimulcastReceiver.prototype._remoteMaps = {
  38. msid2Quality: {},
  39. ssrc2Msid: {},
  40. msid2ssrc: {},
  41. receivingVideoStreams: {}
  42. };
  43. SimulcastReceiver.prototype._cacheRemoteVideoSources = function (lines) {
  44. this._remoteVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  45. };
  46. SimulcastReceiver.prototype._restoreRemoteVideoSources = function (lines) {
  47. this.simulcastUtils._replaceVideoSources(lines, this._remoteVideoSourceCache);
  48. };
  49. SimulcastReceiver.prototype._ensureGoogConference = function (lines) {
  50. var sb;
  51. this.logger.info('Ensuring x-google-conference flag...')
  52. if (this.simulcastUtils._indexOfArray('a=x-google-flag:conference', lines) === this.simulcastUtils._emptyCompoundIndex) {
  53. // TODO(gp) do that for the audio as well as suggested by fippo.
  54. // Add the google conference flag
  55. sb = this.simulcastUtils._getVideoSources(lines);
  56. sb = ['a=x-google-flag:conference'].concat(sb);
  57. this.simulcastUtils._replaceVideoSources(lines, sb);
  58. }
  59. };
  60. SimulcastReceiver.prototype._restoreSimulcastGroups = function (sb) {
  61. this._restoreRemoteVideoSources(sb);
  62. };
  63. /**
  64. * Restores the simulcast groups of the remote description. In
  65. * transformRemoteDescription we remove those in order for the set remote
  66. * description to succeed. The focus needs the signal the groups to new
  67. * participants.
  68. *
  69. * @param desc
  70. * @returns {*}
  71. */
  72. SimulcastReceiver.prototype.reverseTransformRemoteDescription = function (desc) {
  73. var sb;
  74. if (!this.simulcastUtils.isValidDescription(desc)) {
  75. return desc;
  76. }
  77. if (config.enableSimulcast) {
  78. sb = desc.sdp.split('\r\n');
  79. this._restoreSimulcastGroups(sb);
  80. desc = new RTCSessionDescription({
  81. type: desc.type,
  82. sdp: sb.join('\r\n')
  83. });
  84. }
  85. return desc;
  86. };
  87. SimulcastUtils.prototype._ensureOrder = function (lines) {
  88. var videoSources, sb;
  89. videoSources = this.parseMedia(lines, ['video'])[0];
  90. sb = this._compileVideoSources(videoSources);
  91. this._replaceVideoSources(lines, sb);
  92. };
  93. SimulcastReceiver.prototype._updateRemoteMaps = function (lines) {
  94. var remoteVideoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0],
  95. videoSource, quality;
  96. // (re) initialize the remote maps.
  97. this._remoteMaps.msid2Quality = {};
  98. this._remoteMaps.ssrc2Msid = {};
  99. this._remoteMaps.msid2ssrc = {};
  100. var self = this;
  101. if (remoteVideoSources.groups && remoteVideoSources.groups.length !== 0) {
  102. remoteVideoSources.groups.forEach(function (group) {
  103. if (group.semantics === 'SIM' && group.ssrcs && group.ssrcs.length !== 0) {
  104. quality = 0;
  105. group.ssrcs.forEach(function (ssrc) {
  106. videoSource = remoteVideoSources.sources[ssrc];
  107. self._remoteMaps.msid2Quality[videoSource.msid] = quality++;
  108. self._remoteMaps.ssrc2Msid[videoSource.ssrc] = videoSource.msid;
  109. self._remoteMaps.msid2ssrc[videoSource.msid] = videoSource.ssrc;
  110. });
  111. }
  112. });
  113. }
  114. };
  115. SimulcastReceiver.prototype._setReceivingVideoStream = function (resource, ssrc) {
  116. this._remoteMaps.receivingVideoStreams[resource] = ssrc;
  117. };
  118. /**
  119. * Returns a stream with single video track, the one currently being
  120. * received by this endpoint.
  121. *
  122. * @param stream the remote simulcast stream.
  123. * @returns {webkitMediaStream}
  124. */
  125. SimulcastReceiver.prototype.getReceivingVideoStream = function (stream) {
  126. var tracks, i, electedTrack, msid, quality = 0, receivingTrackId;
  127. var self = this;
  128. if (config.enableSimulcast) {
  129. stream.getVideoTracks().some(function (track) {
  130. return Object.keys(self._remoteMaps.receivingVideoStreams).some(function (resource) {
  131. var ssrc = self._remoteMaps.receivingVideoStreams[resource];
  132. var msid = self._remoteMaps.ssrc2Msid[ssrc];
  133. if (msid == [stream.id, track.id].join(' ')) {
  134. electedTrack = track;
  135. return true;
  136. }
  137. });
  138. });
  139. if (!electedTrack) {
  140. // we don't have an elected track, choose by initial quality.
  141. tracks = stream.getVideoTracks();
  142. for (i = 0; i < tracks.length; i++) {
  143. msid = [stream.id, tracks[i].id].join(' ');
  144. if (this._remoteMaps.msid2Quality[msid] === quality) {
  145. electedTrack = tracks[i];
  146. break;
  147. }
  148. }
  149. // TODO(gp) if the initialQuality could not be satisfied, lower
  150. // the requirement and try again.
  151. }
  152. }
  153. return (electedTrack)
  154. ? new webkitMediaStream([electedTrack])
  155. : stream;
  156. };
  157. SimulcastReceiver.prototype.getReceivingSSRC = function (jid) {
  158. var resource = Strophe.getResourceFromJid(jid);
  159. var ssrc = this._remoteMaps.receivingVideoStreams[resource];
  160. // If we haven't receiving a "changed" event yet, then we must be receiving
  161. // low quality (that the sender always streams).
  162. if(!ssrc)
  163. {
  164. var remoteStreamObject = RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  165. var remoteStream = remoteStreamObject.getOriginalStream();
  166. var tracks = remoteStream.getVideoTracks();
  167. if (tracks) {
  168. for (var k = 0; k < tracks.length; k++) {
  169. var track = tracks[k];
  170. var msid = [remoteStream.id, track.id].join(' ');
  171. var _ssrc = this._remoteMaps.msid2ssrc[msid];
  172. var quality = this._remoteMaps.msid2Quality[msid];
  173. if (quality == 0) {
  174. ssrc = _ssrc;
  175. }
  176. }
  177. }
  178. }
  179. return ssrc;
  180. };
  181. SimulcastReceiver.prototype.getReceivingVideoStreamBySSRC = function (ssrc)
  182. {
  183. var sid, electedStream;
  184. var i, j, k;
  185. var jid = xmpp.getJidFromSSRC(ssrc);
  186. if(jid && RTC.remoteStreams[jid])
  187. {
  188. var remoteStreamObject = RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  189. var remoteStream = remoteStreamObject.getOriginalStream();
  190. var tracks = remoteStream.getVideoTracks();
  191. if (tracks) {
  192. for (k = 0; k < tracks.length; k++) {
  193. var track = tracks[k];
  194. var msid = [remoteStream.id, track.id].join(' ');
  195. var tmp = this._remoteMaps.msid2ssrc[msid];
  196. if (tmp == ssrc) {
  197. electedStream = new webkitMediaStream([track]);
  198. sid = remoteStreamObject.sid;
  199. // stream found, stop.
  200. break;
  201. }
  202. }
  203. }
  204. }
  205. else
  206. {
  207. console.debug(RTC.remoteStreams, jid, ssrc);
  208. }
  209. return {
  210. sid: sid,
  211. stream: electedStream
  212. };
  213. };
  214. /**
  215. * Gets the fully qualified msid (stream.id + track.id) associated to the
  216. * SSRC.
  217. *
  218. * @param ssrc
  219. * @returns {*}
  220. */
  221. SimulcastReceiver.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  222. return this._remoteMaps.ssrc2Msid[ssrc];
  223. };
  224. /**
  225. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  226. * either gets confused and thinks this is an FID group or, if an FID group
  227. * is already present, it fails to set the remote description.
  228. *
  229. * @param desc
  230. * @returns {*}
  231. */
  232. SimulcastReceiver.prototype.transformRemoteDescription = function (desc) {
  233. if (desc && desc.sdp) {
  234. var sb = desc.sdp.split('\r\n');
  235. this._updateRemoteMaps(sb);
  236. this._cacheRemoteVideoSources(sb);
  237. // NOTE(gp) this needs to be called after updateRemoteMaps because we
  238. // need the simulcast group in the _updateRemoteMaps() method.
  239. this.simulcastUtils._removeSimulcastGroup(sb);
  240. if (desc.sdp.indexOf('a=ssrc-group:SIM') !== -1) {
  241. // We don't need the goog conference flag if we're not doing
  242. // simulcast.
  243. this._ensureGoogConference(sb);
  244. }
  245. desc = new RTCSessionDescription({
  246. type: desc.type,
  247. sdp: sb.join('\r\n')
  248. });
  249. this.logger.fine(['Transformed remote description', desc.sdp].join(' '));
  250. }
  251. return desc;
  252. };
  253. module.exports = SimulcastReceiver;
  254. },{"./SimulcastLogger":1,"./SimulcastUtils":4}],3:[function(require,module,exports){
  255. var SimulcastLogger = require("./SimulcastLogger");
  256. var SimulcastUtils = require("./SimulcastUtils");
  257. function SimulcastSender() {
  258. this.simulcastUtils = new SimulcastUtils();
  259. this.logger = new SimulcastLogger('SimulcastSender', 1);
  260. }
  261. SimulcastSender.prototype.displayedLocalVideoStream = null;
  262. SimulcastSender.prototype._generateGuid = (function () {
  263. function s4() {
  264. return Math.floor((1 + Math.random()) * 0x10000)
  265. .toString(16)
  266. .substring(1);
  267. }
  268. return function () {
  269. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  270. s4() + '-' + s4() + s4() + s4();
  271. };
  272. }());
  273. // Returns a random integer between min (included) and max (excluded)
  274. // Using Math.round() gives a non-uniform distribution!
  275. SimulcastSender.prototype._generateRandomSSRC = function () {
  276. var min = 0, max = 0xffffffff;
  277. return Math.floor(Math.random() * (max - min)) + min;
  278. };
  279. SimulcastSender.prototype.getLocalVideoStream = function () {
  280. return (this.displayedLocalVideoStream != null)
  281. ? this.displayedLocalVideoStream
  282. // in case we have no simulcast at all, i.e. we didn't perform the GUM
  283. : RTC.localVideo.getOriginalStream();
  284. };
  285. function NativeSimulcastSender() {
  286. SimulcastSender.call(this); // call the super constructor.
  287. }
  288. NativeSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  289. NativeSimulcastSender.prototype._localExplosionMap = {};
  290. NativeSimulcastSender.prototype._isUsingScreenStream = false;
  291. NativeSimulcastSender.prototype._localVideoSourceCache = '';
  292. NativeSimulcastSender.prototype.reset = function () {
  293. this._localExplosionMap = {};
  294. this._isUsingScreenStream = desktopsharing.isUsingScreenStream();
  295. };
  296. NativeSimulcastSender.prototype._cacheLocalVideoSources = function (lines) {
  297. this._localVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  298. };
  299. NativeSimulcastSender.prototype._restoreLocalVideoSources = function (lines) {
  300. this.simulcastUtils._replaceVideoSources(lines, this._localVideoSourceCache);
  301. };
  302. NativeSimulcastSender.prototype._appendSimulcastGroup = function (lines) {
  303. var videoSources, ssrcGroup, simSSRC, numOfSubs = 2, i, sb, msid;
  304. this.logger.info('Appending simulcast group...');
  305. // Get the primary SSRC information.
  306. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  307. // Start building the SIM SSRC group.
  308. ssrcGroup = ['a=ssrc-group:SIM'];
  309. // The video source buffer.
  310. sb = [];
  311. // Create the simulcast sub-streams.
  312. for (i = 0; i < numOfSubs; i++) {
  313. // TODO(gp) prevent SSRC collision.
  314. simSSRC = this._generateRandomSSRC();
  315. ssrcGroup.push(simSSRC);
  316. if (videoSources.base) {
  317. sb.splice.apply(sb, [sb.length, 0].concat(
  318. [["a=ssrc:", simSSRC, " cname:", videoSources.base.cname].join(''),
  319. ["a=ssrc:", simSSRC, " msid:", videoSources.base.msid].join('')]
  320. ));
  321. }
  322. this.logger.info(['Generated substream ', i, ' with SSRC ', simSSRC, '.'].join(''));
  323. }
  324. // Add the group sim layers.
  325. sb.splice(0, 0, ssrcGroup.join(' '))
  326. this.simulcastUtils._replaceVideoSources(lines, sb);
  327. };
  328. // Does the actual patching.
  329. NativeSimulcastSender.prototype._ensureSimulcastGroup = function (lines) {
  330. this.logger.info('Ensuring simulcast group...');
  331. if (this.simulcastUtils._indexOfArray('a=ssrc-group:SIM', lines) === this.simulcastUtils._emptyCompoundIndex) {
  332. this._appendSimulcastGroup(lines);
  333. this._cacheLocalVideoSources(lines);
  334. } else {
  335. // verify that the ssrcs participating in the SIM group are present
  336. // in the SDP (needed for presence).
  337. this._restoreLocalVideoSources(lines);
  338. }
  339. };
  340. /**
  341. * Produces a single stream with multiple tracks for local video sources.
  342. *
  343. * @param lines
  344. * @private
  345. */
  346. NativeSimulcastSender.prototype._explodeSimulcastSenderSources = function (lines) {
  347. var sb, msid, sid, tid, videoSources, self;
  348. this.logger.info('Exploding local video sources...');
  349. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  350. self = this;
  351. if (videoSources.groups && videoSources.groups.length !== 0) {
  352. videoSources.groups.forEach(function (group) {
  353. if (group.semantics === 'SIM') {
  354. group.ssrcs.forEach(function (ssrc) {
  355. // Get the msid for this ssrc..
  356. if (self._localExplosionMap[ssrc]) {
  357. // .. either from the explosion map..
  358. msid = self._localExplosionMap[ssrc];
  359. } else {
  360. // .. or generate a new one (msid).
  361. sid = videoSources.sources[ssrc].msid
  362. .substring(0, videoSources.sources[ssrc].msid.indexOf(' '));
  363. tid = self._generateGuid();
  364. msid = [sid, tid].join(' ');
  365. self._localExplosionMap[ssrc] = msid;
  366. }
  367. // Assign it to the source object.
  368. videoSources.sources[ssrc].msid = msid;
  369. // TODO(gp) Change the msid of associated sources.
  370. });
  371. }
  372. });
  373. }
  374. sb = this.simulcastUtils._compileVideoSources(videoSources);
  375. this.simulcastUtils._replaceVideoSources(lines, sb);
  376. };
  377. /**
  378. * GUM for simulcast.
  379. *
  380. * @param constraints
  381. * @param success
  382. * @param err
  383. */
  384. NativeSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  385. // There's nothing special to do for native simulcast, so just do a normal GUM.
  386. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  387. success(hqStream);
  388. }, err);
  389. };
  390. /**
  391. * Prepares the local description for public usage (i.e. to be signaled
  392. * through Jingle to the focus).
  393. *
  394. * @param desc
  395. * @returns {RTCSessionDescription}
  396. */
  397. NativeSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  398. var sb;
  399. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  400. return desc;
  401. }
  402. sb = desc.sdp.split('\r\n');
  403. this._explodeSimulcastSenderSources(sb);
  404. desc = new RTCSessionDescription({
  405. type: desc.type,
  406. sdp: sb.join('\r\n')
  407. });
  408. this.logger.fine(['Exploded local video sources', desc.sdp].join(' '));
  409. return desc;
  410. };
  411. /**
  412. * Ensures that the simulcast group is present in the answer, _if_ native
  413. * simulcast is enabled,
  414. *
  415. * @param desc
  416. * @returns {*}
  417. */
  418. NativeSimulcastSender.prototype.transformAnswer = function (desc) {
  419. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  420. return desc;
  421. }
  422. var sb = desc.sdp.split('\r\n');
  423. // Even if we have enabled native simulcasting previously
  424. // (with a call to SLD with an appropriate SDP, for example),
  425. // createAnswer seems to consistently generate incomplete SDP
  426. // with missing SSRCS.
  427. //
  428. // So, subsequent calls to SLD will have missing SSRCS and presence
  429. // won't have the complete list of SRCs.
  430. this._ensureSimulcastGroup(sb);
  431. desc = new RTCSessionDescription({
  432. type: desc.type,
  433. sdp: sb.join('\r\n')
  434. });
  435. this.logger.fine(['Transformed answer', desc.sdp].join(' '));
  436. return desc;
  437. };
  438. /**
  439. *
  440. *
  441. * @param desc
  442. * @returns {*}
  443. */
  444. NativeSimulcastSender.prototype.transformLocalDescription = function (desc) {
  445. return desc;
  446. };
  447. NativeSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  448. // Nothing to do here, native simulcast does that auto-magically.
  449. };
  450. NativeSimulcastSender.prototype.constructor = NativeSimulcastSender;
  451. function SimpleSimulcastSender() {
  452. SimulcastSender.call(this);
  453. }
  454. SimpleSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  455. SimpleSimulcastSender.prototype.localStream = null;
  456. SimpleSimulcastSender.prototype._localMaps = {
  457. msids: [],
  458. msid2ssrc: {}
  459. };
  460. /**
  461. * Groups local video sources together in the ssrc-group:SIM group.
  462. *
  463. * @param lines
  464. * @private
  465. */
  466. SimpleSimulcastSender.prototype._groupLocalVideoSources = function (lines) {
  467. var sb, videoSources, ssrcs = [], ssrc;
  468. this.logger.info('Grouping local video sources...');
  469. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  470. for (ssrc in videoSources.sources) {
  471. // jitsi-meet destroys/creates streams at various places causing
  472. // the original local stream ids to change. The only thing that
  473. // remains unchanged is the trackid.
  474. this._localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  475. }
  476. var self = this;
  477. // TODO(gp) add only "free" sources.
  478. this._localMaps.msids.forEach(function (msid) {
  479. ssrcs.push(self._localMaps.msid2ssrc[msid]);
  480. });
  481. if (!videoSources.groups) {
  482. videoSources.groups = [];
  483. }
  484. videoSources.groups.push({
  485. 'semantics': 'SIM',
  486. 'ssrcs': ssrcs
  487. });
  488. sb = this.simulcastUtils._compileVideoSources(videoSources);
  489. this.simulcastUtils._replaceVideoSources(lines, sb);
  490. };
  491. /**
  492. * GUM for simulcast.
  493. *
  494. * @param constraints
  495. * @param success
  496. * @param err
  497. */
  498. SimpleSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  499. // TODO(gp) what if we request a resolution not supported by the hardware?
  500. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  501. var lqConstraints = {
  502. audio: false,
  503. video: {
  504. mandatory: {
  505. maxWidth: 320,
  506. maxHeight: 180,
  507. maxFrameRate: 15
  508. }
  509. }
  510. };
  511. this.logger.info('HQ constraints: ', constraints);
  512. this.logger.info('LQ constraints: ', lqConstraints);
  513. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  514. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  515. // reason appears to be that Chrome only acquires the cam once and
  516. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  517. var self = this;
  518. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  519. self.localStream = hqStream;
  520. // reset local maps.
  521. self._localMaps.msids = [];
  522. self._localMaps.msid2ssrc = {};
  523. // add hq trackid to local map
  524. self._localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  525. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  526. self.displayedLocalVideoStream = lqStream;
  527. // NOTE(gp) The specification says Array.forEach() will visit
  528. // the array elements in numeric order, and that it doesn't
  529. // visit elements that don't exist.
  530. // add lq trackid to local map
  531. self._localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  532. self.localStream.addTrack(lqStream.getVideoTracks()[0]);
  533. success(self.localStream);
  534. }, err);
  535. }, err);
  536. };
  537. /**
  538. * Prepares the local description for public usage (i.e. to be signaled
  539. * through Jingle to the focus).
  540. *
  541. * @param desc
  542. * @returns {RTCSessionDescription}
  543. */
  544. SimpleSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  545. var sb;
  546. if (!this.simulcastUtils.isValidDescription(desc)) {
  547. return desc;
  548. }
  549. sb = desc.sdp.split('\r\n');
  550. this._groupLocalVideoSources(sb);
  551. desc = new RTCSessionDescription({
  552. type: desc.type,
  553. sdp: sb.join('\r\n')
  554. });
  555. this.logger.fine('Grouped local video sources');
  556. this.logger.fine(desc.sdp);
  557. return desc;
  558. };
  559. /**
  560. * Ensures that the simulcast group is present in the answer, _if_ native
  561. * simulcast is enabled,
  562. *
  563. * @param desc
  564. * @returns {*}
  565. */
  566. SimpleSimulcastSender.prototype.transformAnswer = function (desc) {
  567. return desc;
  568. };
  569. /**
  570. *
  571. *
  572. * @param desc
  573. * @returns {*}
  574. */
  575. SimpleSimulcastSender.prototype.transformLocalDescription = function (desc) {
  576. var sb = desc.sdp.split('\r\n');
  577. this.simulcastUtils._removeSimulcastGroup(sb);
  578. desc = new RTCSessionDescription({
  579. type: desc.type,
  580. sdp: sb.join('\r\n')
  581. });
  582. this.logger.fine('Transformed local description');
  583. this.logger.fine(desc.sdp);
  584. return desc;
  585. };
  586. SimpleSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  587. var trackid;
  588. var self = this;
  589. this.logger.log(['Requested to', enabled ? 'enable' : 'disable', ssrc].join(' '));
  590. if (Object.keys(this._localMaps.msid2ssrc).some(function (tid) {
  591. // Search for the track id that corresponds to the ssrc
  592. if (self._localMaps.msid2ssrc[tid] == ssrc) {
  593. trackid = tid;
  594. return true;
  595. }
  596. }) && self.localStream.getVideoTracks().some(function (track) {
  597. // Start/stop the track that corresponds to the track id
  598. if (track.id === trackid) {
  599. track.enabled = enabled;
  600. return true;
  601. }
  602. })) {
  603. this.logger.log([trackid, enabled ? 'enabled' : 'disabled'].join(' '));
  604. $(document).trigger(enabled
  605. ? 'simulcastlayerstarted'
  606. : 'simulcastlayerstopped');
  607. } else {
  608. this.logger.error("I don't have a local stream with SSRC " + ssrc);
  609. }
  610. };
  611. SimpleSimulcastSender.prototype.constructor = SimpleSimulcastSender;
  612. function NoSimulcastSender() {
  613. SimulcastSender.call(this);
  614. }
  615. NoSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  616. /**
  617. * GUM for simulcast.
  618. *
  619. * @param constraints
  620. * @param success
  621. * @param err
  622. */
  623. NoSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  624. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  625. success(hqStream);
  626. }, err);
  627. };
  628. /**
  629. * Prepares the local description for public usage (i.e. to be signaled
  630. * through Jingle to the focus).
  631. *
  632. * @param desc
  633. * @returns {RTCSessionDescription}
  634. */
  635. NoSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  636. return desc;
  637. };
  638. /**
  639. * Ensures that the simulcast group is present in the answer, _if_ native
  640. * simulcast is enabled,
  641. *
  642. * @param desc
  643. * @returns {*}
  644. */
  645. NoSimulcastSender.prototype.transformAnswer = function (desc) {
  646. return desc;
  647. };
  648. /**
  649. *
  650. *
  651. * @param desc
  652. * @returns {*}
  653. */
  654. NoSimulcastSender.prototype.transformLocalDescription = function (desc) {
  655. return desc;
  656. };
  657. NoSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  658. };
  659. NoSimulcastSender.prototype.constructor = NoSimulcastSender;
  660. module.exports = {
  661. "native": NativeSimulcastSender,
  662. "no": NoSimulcastSender
  663. }
  664. },{"./SimulcastLogger":1,"./SimulcastUtils":4}],4:[function(require,module,exports){
  665. var SimulcastLogger = require("./SimulcastLogger");
  666. /**
  667. *
  668. * @constructor
  669. */
  670. function SimulcastUtils() {
  671. this.logger = new SimulcastLogger("SimulcastUtils", 1);
  672. }
  673. /**
  674. *
  675. * @type {{}}
  676. * @private
  677. */
  678. SimulcastUtils.prototype._emptyCompoundIndex = {};
  679. /**
  680. *
  681. * @param lines
  682. * @param videoSources
  683. * @private
  684. */
  685. SimulcastUtils.prototype._replaceVideoSources = function (lines, videoSources) {
  686. var i, inVideo = false, index = -1, howMany = 0;
  687. this.logger.info('Replacing video sources...');
  688. for (i = 0; i < lines.length; i++) {
  689. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  690. // Out of video.
  691. break;
  692. }
  693. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  694. // In video.
  695. inVideo = true;
  696. }
  697. if (inVideo && (lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:'
  698. || lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:')) {
  699. if (index === -1) {
  700. index = i;
  701. }
  702. howMany++;
  703. }
  704. }
  705. // efficiency baby ;)
  706. lines.splice.apply(lines,
  707. [index, howMany].concat(videoSources));
  708. };
  709. SimulcastUtils.prototype.isValidDescription = function (desc)
  710. {
  711. return desc && desc != null
  712. && desc.type && desc.type != ''
  713. && desc.sdp && desc.sdp != '';
  714. };
  715. SimulcastUtils.prototype._getVideoSources = function (lines) {
  716. var i, inVideo = false, sb = [];
  717. this.logger.info('Getting video sources...');
  718. for (i = 0; i < lines.length; i++) {
  719. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  720. // Out of video.
  721. break;
  722. }
  723. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  724. // In video.
  725. inVideo = true;
  726. }
  727. if (inVideo && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  728. // In SSRC.
  729. sb.push(lines[i]);
  730. }
  731. if (inVideo && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  732. sb.push(lines[i]);
  733. }
  734. }
  735. return sb;
  736. };
  737. SimulcastUtils.prototype.parseMedia = function (lines, mediatypes) {
  738. var i, res = [], type, cur_media, idx, ssrcs, cur_ssrc, ssrc,
  739. ssrc_attribute, group, semantics, skip = true;
  740. this.logger.info('Parsing media sources...');
  741. for (i = 0; i < lines.length; i++) {
  742. if (lines[i].substring(0, 'm='.length) === 'm=') {
  743. type = lines[i]
  744. .substr('m='.length, lines[i].indexOf(' ') - 'm='.length);
  745. skip = mediatypes !== undefined && mediatypes.indexOf(type) === -1;
  746. if (!skip) {
  747. cur_media = {
  748. 'type': type,
  749. 'sources': {},
  750. 'groups': []
  751. };
  752. res.push(cur_media);
  753. }
  754. } else if (!skip && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  755. idx = lines[i].indexOf(' ');
  756. ssrc = lines[i].substring('a=ssrc:'.length, idx);
  757. if (cur_media.sources[ssrc] === undefined) {
  758. cur_ssrc = {'ssrc': ssrc};
  759. cur_media.sources[ssrc] = cur_ssrc;
  760. }
  761. ssrc_attribute = lines[i].substr(idx + 1).split(':', 2)[0];
  762. cur_ssrc[ssrc_attribute] = lines[i].substr(idx + 1).split(':', 2)[1];
  763. if (cur_media.base === undefined) {
  764. cur_media.base = cur_ssrc;
  765. }
  766. } else if (!skip && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  767. idx = lines[i].indexOf(' ');
  768. semantics = lines[i].substr(0, idx).substr('a=ssrc-group:'.length);
  769. ssrcs = lines[i].substr(idx).trim().split(' ');
  770. group = {
  771. 'semantics': semantics,
  772. 'ssrcs': ssrcs
  773. };
  774. cur_media.groups.push(group);
  775. } else if (!skip && (lines[i].substring(0, 'a=sendrecv'.length) === 'a=sendrecv' ||
  776. lines[i].substring(0, 'a=recvonly'.length) === 'a=recvonly' ||
  777. lines[i].substring(0, 'a=sendonly'.length) === 'a=sendonly' ||
  778. lines[i].substring(0, 'a=inactive'.length) === 'a=inactive')) {
  779. cur_media.direction = lines[i].substring('a='.length);
  780. }
  781. }
  782. return res;
  783. };
  784. /**
  785. * The _indexOfArray() method returns the first a CompoundIndex at which a
  786. * given element can be found in the array, or _emptyCompoundIndex if it is
  787. * not present.
  788. *
  789. * Example:
  790. *
  791. * _indexOfArray('3', [ 'this is line 1', 'this is line 2', 'this is line 3' ])
  792. *
  793. * returns {row: 2, column: 14}
  794. *
  795. * @param needle
  796. * @param haystack
  797. * @param start
  798. * @returns {}
  799. * @private
  800. */
  801. SimulcastUtils.prototype._indexOfArray = function (needle, haystack, start) {
  802. var length = haystack.length, idx, i;
  803. if (!start) {
  804. start = 0;
  805. }
  806. for (i = start; i < length; i++) {
  807. idx = haystack[i].indexOf(needle);
  808. if (idx !== -1) {
  809. return {row: i, column: idx};
  810. }
  811. }
  812. return this._emptyCompoundIndex;
  813. };
  814. SimulcastUtils.prototype._removeSimulcastGroup = function (lines) {
  815. var i;
  816. for (i = lines.length - 1; i >= 0; i--) {
  817. if (lines[i].indexOf('a=ssrc-group:SIM') !== -1) {
  818. lines.splice(i, 1);
  819. }
  820. }
  821. };
  822. SimulcastUtils.prototype._compileVideoSources = function (videoSources) {
  823. var sb = [], ssrc, addedSSRCs = [];
  824. this.logger.info('Compiling video sources...');
  825. // Add the groups
  826. if (videoSources.groups && videoSources.groups.length !== 0) {
  827. videoSources.groups.forEach(function (group) {
  828. if (group.ssrcs && group.ssrcs.length !== 0) {
  829. sb.push([['a=ssrc-group:', group.semantics].join(''), group.ssrcs.join(' ')].join(' '));
  830. // if (group.semantics !== 'SIM') {
  831. group.ssrcs.forEach(function (ssrc) {
  832. addedSSRCs.push(ssrc);
  833. sb.splice.apply(sb, [sb.length, 0].concat([
  834. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  835. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  836. });
  837. //}
  838. }
  839. });
  840. }
  841. // Then add any free sources.
  842. if (videoSources.sources) {
  843. for (ssrc in videoSources.sources) {
  844. if (addedSSRCs.indexOf(ssrc) === -1) {
  845. sb.splice.apply(sb, [sb.length, 0].concat([
  846. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  847. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  848. }
  849. }
  850. }
  851. return sb;
  852. };
  853. module.exports = SimulcastUtils;
  854. },{"./SimulcastLogger":1}],5:[function(require,module,exports){
  855. /*jslint plusplus: true */
  856. /*jslint nomen: true*/
  857. var SimulcastSender = require("./SimulcastSender");
  858. var NoSimulcastSender = SimulcastSender["no"];
  859. var NativeSimulcastSender = SimulcastSender["native"];
  860. var SimulcastReceiver = require("./SimulcastReceiver");
  861. var SimulcastUtils = require("./SimulcastUtils");
  862. /**
  863. *
  864. * @constructor
  865. */
  866. function SimulcastManager() {
  867. // Create the simulcast utilities.
  868. this.simulcastUtils = new SimulcastUtils();
  869. // Create remote simulcast.
  870. this.simulcastReceiver = new SimulcastReceiver();
  871. // Initialize local simulcast.
  872. // TODO(gp) move into SimulcastManager.prototype.getUserMedia and take into
  873. // account constraints.
  874. if (!config.enableSimulcast) {
  875. this.simulcastSender = new NoSimulcastSender();
  876. } else {
  877. var isChromium = window.chrome,
  878. vendorName = window.navigator.vendor;
  879. if(isChromium !== null && isChromium !== undefined
  880. /* skip opera */
  881. && vendorName === "Google Inc."
  882. /* skip Chromium as suggested by fippo */
  883. && !window.navigator.appVersion.match(/Chromium\//) ) {
  884. var ver = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
  885. if (ver > 37) {
  886. this.simulcastSender = new NativeSimulcastSender();
  887. } else {
  888. this.simulcastSender = new NoSimulcastSender();
  889. }
  890. } else {
  891. this.simulcastSender = new NoSimulcastSender();
  892. }
  893. }
  894. }
  895. /**
  896. * Restores the simulcast groups of the remote description. In
  897. * transformRemoteDescription we remove those in order for the set remote
  898. * description to succeed. The focus needs the signal the groups to new
  899. * participants.
  900. *
  901. * @param desc
  902. * @returns {*}
  903. */
  904. SimulcastManager.prototype.reverseTransformRemoteDescription = function (desc) {
  905. return this.simulcastReceiver.reverseTransformRemoteDescription(desc);
  906. };
  907. /**
  908. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  909. * either gets confused and thinks this is an FID group or, if an FID group
  910. * is already present, it fails to set the remote description.
  911. *
  912. * @param desc
  913. * @returns {*}
  914. */
  915. SimulcastManager.prototype.transformRemoteDescription = function (desc) {
  916. return this.simulcastReceiver.transformRemoteDescription(desc);
  917. };
  918. /**
  919. * Gets the fully qualified msid (stream.id + track.id) associated to the
  920. * SSRC.
  921. *
  922. * @param ssrc
  923. * @returns {*}
  924. */
  925. SimulcastManager.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  926. return this.simulcastReceiver.getRemoteVideoStreamIdBySSRC(ssrc);
  927. };
  928. /**
  929. * Returns a stream with single video track, the one currently being
  930. * received by this endpoint.
  931. *
  932. * @param stream the remote simulcast stream.
  933. * @returns {webkitMediaStream}
  934. */
  935. SimulcastManager.prototype.getReceivingVideoStream = function (stream) {
  936. return this.simulcastReceiver.getReceivingVideoStream(stream);
  937. };
  938. /**
  939. *
  940. *
  941. * @param desc
  942. * @returns {*}
  943. */
  944. SimulcastManager.prototype.transformLocalDescription = function (desc) {
  945. return this.simulcastSender.transformLocalDescription(desc);
  946. };
  947. /**
  948. *
  949. * @returns {*}
  950. */
  951. SimulcastManager.prototype.getLocalVideoStream = function() {
  952. return this.simulcastSender.getLocalVideoStream();
  953. };
  954. /**
  955. * GUM for simulcast.
  956. *
  957. * @param constraints
  958. * @param success
  959. * @param err
  960. */
  961. SimulcastManager.prototype.getUserMedia = function (constraints, success, err) {
  962. this.simulcastSender.getUserMedia(constraints, success, err);
  963. };
  964. /**
  965. * Prepares the local description for public usage (i.e. to be signaled
  966. * through Jingle to the focus).
  967. *
  968. * @param desc
  969. * @returns {RTCSessionDescription}
  970. */
  971. SimulcastManager.prototype.reverseTransformLocalDescription = function (desc) {
  972. return this.simulcastSender.reverseTransformLocalDescription(desc);
  973. };
  974. /**
  975. * Ensures that the simulcast group is present in the answer, _if_ native
  976. * simulcast is enabled,
  977. *
  978. * @param desc
  979. * @returns {*}
  980. */
  981. SimulcastManager.prototype.transformAnswer = function (desc) {
  982. return this.simulcastSender.transformAnswer(desc);
  983. };
  984. SimulcastManager.prototype.getReceivingSSRC = function (jid) {
  985. return this.simulcastReceiver.getReceivingSSRC(jid);
  986. };
  987. SimulcastManager.prototype.getReceivingVideoStreamBySSRC = function (msid) {
  988. return this.simulcastReceiver.getReceivingVideoStreamBySSRC(msid);
  989. };
  990. /**
  991. *
  992. * @param lines
  993. * @param mediatypes
  994. * @returns {*}
  995. */
  996. SimulcastManager.prototype.parseMedia = function(lines, mediatypes) {
  997. var sb = lines.sdp.split('\r\n');
  998. return this.simulcastUtils.parseMedia(sb, mediatypes);
  999. };
  1000. SimulcastManager.prototype._setReceivingVideoStream = function(resource, ssrc) {
  1001. this.simulcastReceiver._setReceivingVideoStream(resource, ssrc);
  1002. };
  1003. SimulcastManager.prototype._setLocalVideoStreamEnabled = function(ssrc, enabled) {
  1004. this.simulcastSender._setLocalVideoStreamEnabled(ssrc, enabled);
  1005. };
  1006. SimulcastManager.prototype.resetSender = function() {
  1007. if (typeof this.simulcastSender.reset === 'function'){
  1008. this.simulcastSender.reset();
  1009. }
  1010. };
  1011. $(document).bind('simulcastlayerschanged', function (event, endpointSimulcastLayers) {
  1012. endpointSimulcastLayers.forEach(function (esl) {
  1013. var ssrc = esl.simulcastLayer.primarySSRC;
  1014. simulcast._setReceivingVideoStream(esl.endpoint, ssrc);
  1015. });
  1016. });
  1017. $(document).bind('startsimulcastlayer', function (event, simulcastLayer) {
  1018. var ssrc = simulcastLayer.primarySSRC;
  1019. simulcast._setLocalVideoStreamEnabled(ssrc, true);
  1020. });
  1021. $(document).bind('stopsimulcastlayer', function (event, simulcastLayer) {
  1022. var ssrc = simulcastLayer.primarySSRC;
  1023. simulcast._setLocalVideoStreamEnabled(ssrc, false);
  1024. });
  1025. var simulcast = new SimulcastManager();
  1026. module.exports = simulcast;
  1027. },{"./SimulcastReceiver":2,"./SimulcastSender":3,"./SimulcastUtils":4}]},{},[5])(5)
  1028. });