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.js 35KB

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