您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

simulcast.js 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  1. /*jslint plusplus: true */
  2. /*jslint nomen: true*/
  3. /**
  4. * Created by gp on 11/08/14.
  5. */
  6. function Simulcast() {
  7. "use strict";
  8. // TODO(gp) split the Simulcast class in two classes : NativeSimulcast and ClassicSimulcast.
  9. this.debugLvl = 1;
  10. }
  11. (function () {
  12. "use strict";
  13. // global state for all transformers.
  14. var localExplosionMap = {}, localVideoSourceCache, emptyCompoundIndex,
  15. remoteVideoSourceCache, remoteMaps = {
  16. msid2Quality: {},
  17. ssrc2Msid: {},
  18. receivingVideoStreams: {}
  19. }, localMaps = {
  20. msids: [],
  21. msid2ssrc: {}
  22. };
  23. Simulcast.prototype._generateGuid = (function () {
  24. function s4() {
  25. return Math.floor((1 + Math.random()) * 0x10000)
  26. .toString(16)
  27. .substring(1);
  28. }
  29. return function () {
  30. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  31. s4() + '-' + s4() + s4() + s4();
  32. };
  33. }());
  34. Simulcast.prototype._cacheVideoSources = function (lines) {
  35. localVideoSourceCache = this._getVideoSources(lines);
  36. };
  37. Simulcast.prototype._restoreVideoSources = function (lines) {
  38. this._replaceVideoSources(lines, localVideoSourceCache);
  39. };
  40. Simulcast.prototype._cacheRemoteVideoSources = function (lines) {
  41. remoteVideoSourceCache = this._getVideoSources(lines);
  42. };
  43. Simulcast.prototype._restoreRemoteVideoSources = function (lines) {
  44. this._replaceVideoSources(lines, remoteVideoSourceCache);
  45. };
  46. Simulcast.prototype._replaceVideoSources = function (lines, videoSources) {
  47. var i, inVideo = false, index = -1, howMany = 0;
  48. if (this.debugLvl) {
  49. console.info('Replacing video sources...');
  50. }
  51. for (i = 0; i < lines.length; i++) {
  52. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  53. // Out of video.
  54. break;
  55. }
  56. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  57. // In video.
  58. inVideo = true;
  59. }
  60. if (inVideo && (lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:'
  61. || lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:')) {
  62. if (index === -1) {
  63. index = i;
  64. }
  65. howMany++;
  66. }
  67. }
  68. // efficiency baby ;)
  69. lines.splice.apply(lines,
  70. [index, howMany].concat(videoSources));
  71. };
  72. Simulcast.prototype._getVideoSources = function (lines) {
  73. var i, inVideo = false, sb = [];
  74. if (this.debugLvl) {
  75. console.info('Getting video sources...');
  76. }
  77. for (i = 0; i < lines.length; i++) {
  78. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  79. // Out of video.
  80. break;
  81. }
  82. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  83. // In video.
  84. inVideo = true;
  85. }
  86. if (inVideo && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  87. // In SSRC.
  88. sb.push(lines[i]);
  89. }
  90. if (inVideo && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  91. sb.push(lines[i]);
  92. }
  93. }
  94. return sb;
  95. };
  96. Simulcast.prototype._parseMedia = function (lines, mediatypes) {
  97. var i, res = [], type, cur_media, idx, ssrcs, cur_ssrc, ssrc,
  98. ssrc_attribute, group, semantics, skip;
  99. if (this.debugLvl) {
  100. console.info('Parsing media sources...');
  101. }
  102. for (i = 0; i < lines.length; i++) {
  103. if (lines[i].substring(0, 'm='.length) === 'm=') {
  104. type = lines[i]
  105. .substr('m='.length, lines[i].indexOf(' ') - 'm='.length);
  106. skip = mediatypes !== undefined && mediatypes.indexOf(type) === -1;
  107. if (!skip) {
  108. cur_media = {
  109. 'type': type,
  110. 'sources': {},
  111. 'groups': []
  112. };
  113. res.push(cur_media);
  114. }
  115. } else if (!skip && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  116. idx = lines[i].indexOf(' ');
  117. ssrc = lines[i].substring('a=ssrc:'.length, idx);
  118. if (cur_media.sources[ssrc] === undefined) {
  119. cur_ssrc = {'ssrc': ssrc};
  120. cur_media.sources[ssrc] = cur_ssrc;
  121. }
  122. ssrc_attribute = lines[i].substr(idx + 1).split(':', 2)[0];
  123. cur_ssrc[ssrc_attribute] = lines[i].substr(idx + 1).split(':', 2)[1];
  124. if (cur_media.base === undefined) {
  125. cur_media.base = cur_ssrc;
  126. }
  127. } else if (!skip && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  128. idx = lines[i].indexOf(' ');
  129. semantics = lines[i].substr(0, idx).substr('a=ssrc-group:'.length);
  130. ssrcs = lines[i].substr(idx).trim().split(' ');
  131. group = {
  132. 'semantics': semantics,
  133. 'ssrcs': ssrcs
  134. };
  135. cur_media.groups.push(group);
  136. } else if (!skip && (lines[i].substring(0, 'a=sendrecv'.length) === 'a=sendrecv' ||
  137. lines[i].substring(0, 'a=recvonly'.length) === 'a=recvonly' ||
  138. lines[i].substring(0, 'a=sendonly'.length) === 'a=sendonly' ||
  139. lines[i].substring(0, 'a=inactive'.length) === 'a=inactive')) {
  140. cur_media.direction = lines[i].substring('a='.length, 8);
  141. }
  142. }
  143. return res;
  144. };
  145. // Returns a random integer between min (included) and max (excluded)
  146. // Using Math.round() will give you a non-uniform distribution!
  147. Simulcast.prototype._generateRandomSSRC = function () {
  148. var min = 0, max = 0xffffffff;
  149. return Math.floor(Math.random() * (max - min)) + min;
  150. };
  151. function CompoundIndex(obj) {
  152. if (obj !== undefined) {
  153. this.row = obj.row;
  154. this.column = obj.column;
  155. }
  156. }
  157. emptyCompoundIndex = new CompoundIndex();
  158. Simulcast.prototype._indexOfArray = function (needle, haystack, start) {
  159. var length = haystack.length, idx, i;
  160. if (!start) {
  161. start = 0;
  162. }
  163. for (i = start; i < length; i++) {
  164. idx = haystack[i].indexOf(needle);
  165. if (idx !== -1) {
  166. return new CompoundIndex({row: i, column: idx});
  167. }
  168. }
  169. return emptyCompoundIndex;
  170. };
  171. Simulcast.prototype._removeSimulcastGroup = function (lines) {
  172. var i;
  173. for (i = lines.length - 1; i >= 0; i--) {
  174. if (lines[i].indexOf('a=ssrc-group:SIM') !== -1) {
  175. lines.splice(i, 1);
  176. }
  177. }
  178. };
  179. /**
  180. * Produces a single stream with multiple tracks for local video sources.
  181. *
  182. * @param lines
  183. * @private
  184. */
  185. Simulcast.prototype._explodeLocalSimulcastSources = function (lines) {
  186. var sb, msid, sid, tid, videoSources, self;
  187. if (this.debugLvl) {
  188. console.info('Exploding local video sources...');
  189. }
  190. videoSources = this._parseMedia(lines, ['video'])[0];
  191. self = this;
  192. if (videoSources.groups && videoSources.groups.length !== 0) {
  193. videoSources.groups.forEach(function (group) {
  194. if (group.semantics === 'SIM') {
  195. group.ssrcs.forEach(function (ssrc) {
  196. // Get the msid for this ssrc..
  197. if (localExplosionMap[ssrc]) {
  198. // .. either from the explosion map..
  199. msid = localExplosionMap[ssrc];
  200. } else {
  201. // .. or generate a new one (msid).
  202. sid = videoSources.sources[ssrc].msid
  203. .substring(0, videoSources.sources[ssrc].msid.indexOf(' '));
  204. tid = self._generateGuid();
  205. msid = [sid, tid].join(' ');
  206. localExplosionMap[ssrc] = msid;
  207. }
  208. // Assign it to the source object.
  209. videoSources.sources[ssrc].msid = msid;
  210. // TODO(gp) Change the msid of associated sources.
  211. });
  212. }
  213. });
  214. }
  215. sb = this._compileVideoSources(videoSources);
  216. this._replaceVideoSources(lines, sb);
  217. };
  218. /**
  219. * Groups local video sources together in the ssrc-group:SIM group.
  220. *
  221. * @param lines
  222. * @private
  223. */
  224. Simulcast.prototype._groupLocalVideoSources = function (lines) {
  225. var sb, videoSources, ssrcs = [], ssrc;
  226. if (this.debugLvl) {
  227. console.info('Grouping local video sources...');
  228. }
  229. videoSources = this._parseMedia(lines, ['video'])[0];
  230. for (ssrc in videoSources.sources) {
  231. // jitsi-meet destroys/creates streams at various places causing
  232. // the original local stream ids to change. The only thing that
  233. // remains unchanged is the trackid.
  234. localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  235. }
  236. // TODO(gp) add only "free" sources.
  237. localMaps.msids.forEach(function (msid) {
  238. ssrcs.push(localMaps.msid2ssrc[msid]);
  239. });
  240. if (!videoSources.groups) {
  241. videoSources.groups = [];
  242. }
  243. videoSources.groups.push({
  244. 'semantics': 'SIM',
  245. 'ssrcs': ssrcs
  246. });
  247. sb = this._compileVideoSources(videoSources);
  248. this._replaceVideoSources(lines, sb);
  249. };
  250. Simulcast.prototype._appendSimulcastGroup = function (lines) {
  251. var videoSources, ssrcGroup, simSSRC, numOfSubs = 3, i, sb, msid;
  252. if (this.debugLvl) {
  253. console.info('Appending simulcast group...');
  254. }
  255. // Get the primary SSRC information.
  256. videoSources = this._parseMedia(lines, ['video'])[0];
  257. // Start building the SIM SSRC group.
  258. ssrcGroup = ['a=ssrc-group:SIM'];
  259. // The video source buffer.
  260. sb = [];
  261. // Create the simulcast sub-streams.
  262. for (i = 0; i < numOfSubs; i++) {
  263. // TODO(gp) prevent SSRC collision.
  264. simSSRC = this._generateRandomSSRC();
  265. ssrcGroup.push(simSSRC);
  266. sb.splice.apply(sb, [sb.length, 0].concat(
  267. [["a=ssrc:", simSSRC, " cname:", videoSources.base.cname].join(''),
  268. ["a=ssrc:", simSSRC, " msid:", videoSources.base.msid].join('')]
  269. ));
  270. if (this.debugLvl) {
  271. console.info(['Generated substream ', i, ' with SSRC ', simSSRC, '.'].join(''));
  272. }
  273. }
  274. // Add the group sim layers.
  275. sb.splice(0, 0, ssrcGroup.join(' '))
  276. this._replaceVideoSources(lines, sb);
  277. };
  278. // Does the actual patching.
  279. Simulcast.prototype._ensureSimulcastGroup = function (lines) {
  280. if (this.debugLvl) {
  281. console.info('Ensuring simulcast group...');
  282. }
  283. if (this._indexOfArray('a=ssrc-group:SIM', lines) === emptyCompoundIndex) {
  284. this._appendSimulcastGroup(lines);
  285. this._cacheVideoSources(lines);
  286. } else {
  287. // verify that the ssrcs participating in the SIM group are present
  288. // in the SDP (needed for presence).
  289. this._restoreVideoSources(lines);
  290. }
  291. };
  292. Simulcast.prototype._ensureGoogConference = function (lines) {
  293. var sb;
  294. if (this.debugLvl) {
  295. console.info('Ensuring x-google-conference flag...')
  296. }
  297. if (this._indexOfArray('a=x-google-flag:conference', lines) === emptyCompoundIndex) {
  298. // Add the google conference flag
  299. sb = this._getVideoSources(lines);
  300. sb = ['a=x-google-flag:conference'].concat(sb);
  301. this._replaceVideoSources(lines, sb);
  302. }
  303. };
  304. Simulcast.prototype._compileVideoSources = function (videoSources) {
  305. var sb = [], ssrc, addedSSRCs = [];
  306. if (this.debugLvl) {
  307. console.info('Compiling video sources...');
  308. }
  309. // Add the groups
  310. if (videoSources.groups && videoSources.groups.length !== 0) {
  311. videoSources.groups.forEach(function (group) {
  312. if (group.ssrcs && group.ssrcs.length !== 0) {
  313. sb.push([['a=ssrc-group:', group.semantics].join(''), group.ssrcs.join(' ')].join(' '));
  314. // if (group.semantics !== 'SIM') {
  315. group.ssrcs.forEach(function (ssrc) {
  316. addedSSRCs.push(ssrc);
  317. sb.splice.apply(sb, [sb.length, 0].concat([
  318. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  319. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  320. });
  321. //}
  322. }
  323. });
  324. }
  325. // Then add any free sources.
  326. if (videoSources.sources) {
  327. for (ssrc in videoSources.sources) {
  328. if (addedSSRCs.indexOf(ssrc) === -1) {
  329. sb.splice.apply(sb, [sb.length, 0].concat([
  330. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  331. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  332. }
  333. }
  334. }
  335. return sb;
  336. };
  337. /**
  338. * Ensures that the simulcast group is present in the answer, _if_ native
  339. * simulcast is enabled,
  340. *
  341. * @param desc
  342. * @returns {*}
  343. */
  344. Simulcast.prototype.transformAnswer = function (desc) {
  345. if (config.enableSimulcast && config.useNativeSimulcast) {
  346. var sb = desc.sdp.split('\r\n');
  347. // Even if we have enabled native simulcasting previously
  348. // (with a call to SLD with an appropriate SDP, for example),
  349. // createAnswer seems to consistently generate incomplete SDP
  350. // with missing SSRCS.
  351. //
  352. // So, subsequent calls to SLD will have missing SSRCS and presence
  353. // won't have the complete list of SRCs.
  354. this._ensureSimulcastGroup(sb);
  355. desc = new RTCSessionDescription({
  356. type: desc.type,
  357. sdp: sb.join('\r\n')
  358. });
  359. if (this.debugLvl && this.debugLvl > 1) {
  360. console.info('Transformed answer');
  361. console.info(desc.sdp);
  362. }
  363. }
  364. return desc;
  365. };
  366. Simulcast.prototype._restoreSimulcastGroups = function (sb) {
  367. this._restoreRemoteVideoSources(sb);
  368. };
  369. /**
  370. * Restores the simulcast groups of the remote description. In
  371. * transformRemoteDescription we remove those in order for the set remote
  372. * description to succeed. The focus needs the signal the groups to new
  373. * participants.
  374. *
  375. * @param desc
  376. * @returns {*}
  377. */
  378. Simulcast.prototype.reverseTransformRemoteDescription = function (desc) {
  379. var sb;
  380. if (!desc || desc == null) {
  381. return desc;
  382. }
  383. if (config.enableSimulcast) {
  384. sb = desc.sdp.split('\r\n');
  385. this._restoreSimulcastGroups(sb);
  386. desc = new RTCSessionDescription({
  387. type: desc.type,
  388. sdp: sb.join('\r\n')
  389. });
  390. }
  391. return desc;
  392. };
  393. /**
  394. * Prepares the local description for public usage (i.e. to be signaled
  395. * through Jingle to the focus).
  396. *
  397. * @param desc
  398. * @returns {RTCSessionDescription}
  399. */
  400. Simulcast.prototype.reverseTransformLocalDescription = function (desc) {
  401. var sb;
  402. if (!desc || desc == null) {
  403. return desc;
  404. }
  405. if (config.enableSimulcast) {
  406. if (config.useNativeSimulcast) {
  407. sb = desc.sdp.split('\r\n');
  408. this._explodeLocalSimulcastSources(sb);
  409. desc = new RTCSessionDescription({
  410. type: desc.type,
  411. sdp: sb.join('\r\n')
  412. });
  413. if (this.debugLvl && this.debugLvl > 1) {
  414. console.info('Exploded local video sources');
  415. console.info(desc.sdp);
  416. }
  417. } else {
  418. sb = desc.sdp.split('\r\n');
  419. this._groupLocalVideoSources(sb);
  420. desc = new RTCSessionDescription({
  421. type: desc.type,
  422. sdp: sb.join('\r\n')
  423. });
  424. if (this.debugLvl && this.debugLvl > 1) {
  425. console.info('Grouped local video sources');
  426. console.info(desc.sdp);
  427. }
  428. }
  429. }
  430. return desc;
  431. };
  432. Simulcast.prototype._ensureOrder = function (lines) {
  433. var videoSources, sb;
  434. videoSources = this._parseMedia(lines, ['video'])[0];
  435. sb = this._compileVideoSources(videoSources);
  436. this._replaceVideoSources(lines, sb);
  437. };
  438. Simulcast.prototype._updateRemoteMaps = function (lines) {
  439. var remoteVideoSources = this._parseMedia(lines, ['video'])[0], videoSource, quality;
  440. // (re) initialize the remote maps.
  441. remoteMaps = {
  442. msid2Quality: {},
  443. ssrc2Msid: {},
  444. receivingVideoStreams: {}
  445. };
  446. if (remoteVideoSources.groups && remoteVideoSources.groups.length !== 0) {
  447. remoteVideoSources.groups.forEach(function (group) {
  448. if (group.semantics === 'SIM' && group.ssrcs && group.ssrcs.length !== 0) {
  449. quality = 0;
  450. group.ssrcs.forEach(function (ssrc) {
  451. videoSource = remoteVideoSources.sources[ssrc];
  452. remoteMaps.msid2Quality[videoSource.msid] = quality++;
  453. remoteMaps.ssrc2Msid[videoSource.ssrc] = videoSource.msid;
  454. });
  455. }
  456. });
  457. }
  458. };
  459. /**
  460. *
  461. *
  462. * @param desc
  463. * @returns {*}
  464. */
  465. Simulcast.prototype.transformLocalDescription = function (desc) {
  466. if (config.enableSimulcast && !config.useNativeSimulcast) {
  467. var sb = desc.sdp.split('\r\n');
  468. this._removeSimulcastGroup(sb);
  469. desc = new RTCSessionDescription({
  470. type: desc.type,
  471. sdp: sb.join('\r\n')
  472. });
  473. if (this.debugLvl && this.debugLvl > 1) {
  474. console.info('Transformed local description');
  475. console.info(desc.sdp);
  476. }
  477. }
  478. return desc;
  479. };
  480. /**
  481. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  482. * either gets confused and thinks this is an FID group or, if an FID group
  483. * is already present, it fails to set the remote description.
  484. *
  485. * @param desc
  486. * @returns {*}
  487. */
  488. Simulcast.prototype.transformRemoteDescription = function (desc) {
  489. if (config.enableSimulcast) {
  490. var sb = desc.sdp.split('\r\n');
  491. this._updateRemoteMaps(sb);
  492. this._cacheRemoteVideoSources(sb);
  493. this._removeSimulcastGroup(sb); // NOTE(gp) this needs to be called after updateRemoteMaps because we need the simulcast group in the _updateRemoteMaps() method.
  494. if (config.useNativeSimulcast) {
  495. // We don't need the goog conference flag if we're not doing
  496. // native simulcast.
  497. this._ensureGoogConference(sb);
  498. }
  499. desc = new RTCSessionDescription({
  500. type: desc.type,
  501. sdp: sb.join('\r\n')
  502. });
  503. if (this.debugLvl && this.debugLvl > 1) {
  504. console.info('Transformed remote description');
  505. console.info(desc.sdp);
  506. }
  507. }
  508. return desc;
  509. };
  510. Simulcast.prototype._setReceivingVideoStream = function (ssrc) {
  511. var receivingTrack = remoteMaps.ssrc2Msid[ssrc],
  512. msidParts = receivingTrack.split(' ');
  513. remoteMaps.receivingVideoStreams[msidParts[0]] = msidParts[1];
  514. };
  515. /**
  516. * Returns a stream with single video track, the one currently being
  517. * received by this endpoint.
  518. *
  519. * @param stream the remote simulcast stream.
  520. * @returns {webkitMediaStream}
  521. */
  522. Simulcast.prototype.getReceivingVideoStream = function (stream) {
  523. var tracks, i, electedTrack, msid, quality = 1, receivingTrackId;
  524. if (config.enableSimulcast) {
  525. if (remoteMaps.receivingVideoStreams[stream.id])
  526. {
  527. // the bridge has signaled us to receive a specific track.
  528. receivingTrackId = remoteMaps.receivingVideoStreams[stream.id];
  529. tracks = stream.getVideoTracks();
  530. for (i = 0; i < tracks.length; i++) {
  531. if (receivingTrackId === tracks[i].id) {
  532. electedTrack = tracks[i];
  533. break;
  534. }
  535. }
  536. }
  537. if (!electedTrack) {
  538. // we don't have an elected track, choose by initial quality.
  539. tracks = stream.getVideoTracks();
  540. for (i = 0; i < tracks.length; i++) {
  541. msid = [stream.id, tracks[i].id].join(' ');
  542. if (remoteMaps.msid2Quality[msid] === quality) {
  543. electedTrack = tracks[i];
  544. break;
  545. }
  546. }
  547. // TODO(gp) if the initialQuality could not be satisfied, lower
  548. // the requirement and try again.
  549. }
  550. }
  551. return (electedTrack)
  552. ? new webkitMediaStream([electedTrack])
  553. : stream;
  554. };
  555. var stream;
  556. /**
  557. * GUM for simulcast.
  558. *
  559. * @param constraints
  560. * @param success
  561. * @param err
  562. */
  563. Simulcast.prototype.getUserMedia = function (constraints, success, err) {
  564. // TODO(gp) what if we request a resolution not supported by the hardware?
  565. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  566. var lqConstraints = {
  567. audio: false,
  568. video: {
  569. mandatory: {
  570. maxWidth: 320,
  571. maxHeight: 180
  572. }
  573. }
  574. };
  575. if (config.enableSimulcast && !config.useNativeSimulcast) {
  576. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  577. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  578. // reason appears to be that Chrome only acquires the cam once and
  579. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  580. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  581. // reset local maps.
  582. localMaps.msids = [];
  583. localMaps.msid2ssrc = {};
  584. // add hq trackid to local map
  585. localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  586. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  587. // NOTE(gp) The specification says Array.forEach() will visit
  588. // the array elements in numeric order, and that it doesn't
  589. // visit elements that don't exist.
  590. // add lq trackid to local map
  591. localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  592. hqStream.addTrack(lqStream.getVideoTracks()[0]);
  593. stream = hqStream;
  594. success(hqStream);
  595. }, err);
  596. }, err);
  597. } else {
  598. // There's nothing special to do for native simulcast, so just do a normal GUM.
  599. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  600. // reset local maps.
  601. localMaps.msids = [];
  602. localMaps.msid2ssrc = {};
  603. // add hq stream to local map
  604. localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  605. stream = hqStream;
  606. success(hqStream);
  607. }, err);
  608. }
  609. };
  610. /**
  611. * Gets the fully qualified msid (stream.id + track.id) associated to the
  612. * SSRC.
  613. *
  614. * @param ssrc
  615. * @returns {*}
  616. */
  617. Simulcast.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  618. return remoteMaps.ssrc2Msid[ssrc];
  619. };
  620. Simulcast.prototype.parseMedia = function (desc, mediatypes) {
  621. var lines = desc.sdp.split('\r\n');
  622. return this._parseMedia(lines, mediatypes);
  623. };
  624. Simulcast.prototype._startLocalVideoStream = function (ssrc) {
  625. var trackid;
  626. Object.keys(localMaps.msid2ssrc).some(function (tid) {
  627. if (localMaps.msid2ssrc[tid] == ssrc)
  628. {
  629. trackid = tid;
  630. return true;
  631. }
  632. });
  633. stream.getVideoTracks().some(function(track) {
  634. if (track.id === trackid) {
  635. track.enabled = true;
  636. return true;
  637. }
  638. });
  639. };
  640. Simulcast.prototype._stopLocalVideoStream = function (ssrc) {
  641. var trackid;
  642. Object.keys(localMaps.msid2ssrc).some(function (tid) {
  643. if (localMaps.msid2ssrc[tid] == ssrc)
  644. {
  645. trackid = tid;
  646. return true;
  647. }
  648. });
  649. stream.getVideoTracks().some(function(track) {
  650. if (track.id === trackid) {
  651. track.enabled = false;
  652. return true;
  653. }
  654. });
  655. };
  656. Simulcast.prototype.getLocalVideoStream = function() {
  657. var track;
  658. stream.getVideoTracks().some(function(t) {
  659. if ((track = t).enabled) {
  660. return true;
  661. }
  662. });
  663. return new webkitMediaStream([track]);
  664. };
  665. $(document).bind('simulcastlayerschanged', function (event, endpointSimulcastLayers) {
  666. endpointSimulcastLayers.forEach(function (esl) {
  667. var ssrc = esl.simulcastLayer.primarySSRC;
  668. var simulcast = new Simulcast();
  669. simulcast._setReceivingVideoStream(ssrc);
  670. });
  671. });
  672. $(document).bind('startsimulcastlayer', function(event, simulcastLayer) {
  673. var ssrc = simulcastLayer.primarySSRC;
  674. var simulcast = new Simulcast();
  675. simulcast._startLocalVideoStream(ssrc);
  676. });
  677. $(document).bind('stopsimulcastlayer', function(event, simulcastLayer) {
  678. var ssrc = simulcastLayer.primarySSRC;
  679. var simulcast = new Simulcast();
  680. simulcast._stopLocalVideoStream(ssrc);
  681. });
  682. }());