Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

simulcast.bundle.js 37KB

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