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

simulcast.js 35KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238
  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. if (desc && desc.sdp) {
  598. var sb = desc.sdp.split('\r\n');
  599. this._updateRemoteMaps(sb);
  600. this._cacheRemoteVideoSources(sb);
  601. // NOTE(gp) this needs to be called after updateRemoteMaps because we need the simulcast group in the _updateRemoteMaps() method.
  602. this.simulcastUtils._removeSimulcastGroup(sb);
  603. if (desc.sdp.indexOf('a=ssrc-group:SIM') !== -1) {
  604. // We don't need the goog conference flag if we're not doing
  605. // simulcast.
  606. this._ensureGoogConference(sb);
  607. }
  608. desc = new RTCSessionDescription({
  609. type: desc.type,
  610. sdp: sb.join('\r\n')
  611. });
  612. this.logger.fine(['Transformed remote description', desc.sdp].join(' '));
  613. }
  614. return desc;
  615. };
  616. NativeSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  617. // Nothing to do here, native simulcast does that auto-magically.
  618. };
  619. NativeSimulcastSender.prototype.constructor = NativeSimulcastSender;
  620. function SimpleSimulcastSender() {
  621. SimulcastSender.call(this);
  622. }
  623. SimpleSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  624. SimpleSimulcastSender.prototype._localMaps = {
  625. msids: [],
  626. msid2ssrc: {}
  627. };
  628. /**
  629. * Groups local video sources together in the ssrc-group:SIM group.
  630. *
  631. * @param lines
  632. * @private
  633. */
  634. SimpleSimulcastSender.prototype._groupLocalVideoSources = function (lines) {
  635. var sb, videoSources, ssrcs = [], ssrc;
  636. this.logger.info('Grouping local video sources...');
  637. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  638. for (ssrc in videoSources.sources) {
  639. // jitsi-meet destroys/creates streams at various places causing
  640. // the original local stream ids to change. The only thing that
  641. // remains unchanged is the trackid.
  642. this._localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  643. }
  644. var self = this;
  645. // TODO(gp) add only "free" sources.
  646. this._localMaps.msids.forEach(function (msid) {
  647. ssrcs.push(self._localMaps.msid2ssrc[msid]);
  648. });
  649. if (!videoSources.groups) {
  650. videoSources.groups = [];
  651. }
  652. videoSources.groups.push({
  653. 'semantics': 'SIM',
  654. 'ssrcs': ssrcs
  655. });
  656. sb = this.simulcastUtils._compileVideoSources(videoSources);
  657. this.simulcastUtils._replaceVideoSources(lines, sb);
  658. };
  659. /**
  660. * GUM for simulcast.
  661. *
  662. * @param constraints
  663. * @param success
  664. * @param err
  665. */
  666. SimpleSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  667. // TODO(gp) what if we request a resolution not supported by the hardware?
  668. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  669. var lqConstraints = {
  670. audio: false,
  671. video: {
  672. mandatory: {
  673. maxWidth: 320,
  674. maxHeight: 180,
  675. maxFrameRate: 15
  676. }
  677. }
  678. };
  679. this.logger.info('HQ constraints: ', constraints);
  680. this.logger.info('LQ constraints: ', lqConstraints);
  681. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  682. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  683. // reason appears to be that Chrome only acquires the cam once and
  684. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  685. var self = this;
  686. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  687. self.localStream = hqStream;
  688. // reset local maps.
  689. self._localMaps.msids = [];
  690. self._localMaps.msid2ssrc = {};
  691. // add hq trackid to local map
  692. self._localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  693. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  694. self.displayedLocalVideoStream = lqStream;
  695. // NOTE(gp) The specification says Array.forEach() will visit
  696. // the array elements in numeric order, and that it doesn't
  697. // visit elements that don't exist.
  698. // add lq trackid to local map
  699. self._localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  700. self.localStream.addTrack(lqStream.getVideoTracks()[0]);
  701. success(self.localStream);
  702. }, err);
  703. }, err);
  704. };
  705. /**
  706. * Prepares the local description for public usage (i.e. to be signaled
  707. * through Jingle to the focus).
  708. *
  709. * @param desc
  710. * @returns {RTCSessionDescription}
  711. */
  712. SimpleSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  713. var sb;
  714. if (!desc || desc == null) {
  715. return desc;
  716. }
  717. sb = desc.sdp.split('\r\n');
  718. this._groupLocalVideoSources(sb);
  719. desc = new RTCSessionDescription({
  720. type: desc.type,
  721. sdp: sb.join('\r\n')
  722. });
  723. this.logger.fine('Grouped local video sources');
  724. this.logger.fine(desc.sdp);
  725. return desc;
  726. };
  727. /**
  728. * Ensures that the simulcast group is present in the answer, _if_ native
  729. * simulcast is enabled,
  730. *
  731. * @param desc
  732. * @returns {*}
  733. */
  734. SimpleSimulcastSender.prototype.transformAnswer = function (desc) {
  735. return desc;
  736. };
  737. /**
  738. *
  739. *
  740. * @param desc
  741. * @returns {*}
  742. */
  743. SimpleSimulcastSender.prototype.transformLocalDescription = function (desc) {
  744. var sb = desc.sdp.split('\r\n');
  745. this.simulcastUtils._removeSimulcastGroup(sb);
  746. desc = new RTCSessionDescription({
  747. type: desc.type,
  748. sdp: sb.join('\r\n')
  749. });
  750. this.logger.fine('Transformed local description');
  751. this.logger.fine(desc.sdp);
  752. return desc;
  753. };
  754. SimpleSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  755. var trackid;
  756. var self = this;
  757. this.logger.log(['Requested to', enabled ? 'enable' : 'disable', ssrc].join(' '));
  758. if (Object.keys(this._localMaps.msid2ssrc).some(function (tid) {
  759. // Search for the track id that corresponds to the ssrc
  760. if (self._localMaps.msid2ssrc[tid] == ssrc) {
  761. trackid = tid;
  762. return true;
  763. }
  764. }) && self.localStream.getVideoTracks().some(function (track) {
  765. // Start/stop the track that corresponds to the track id
  766. if (track.id === trackid) {
  767. track.enabled = enabled;
  768. return true;
  769. }
  770. })) {
  771. this.logger.log([trackid, enabled ? 'enabled' : 'disabled'].join(' '));
  772. $(document).trigger(enabled
  773. ? 'simulcastlayerstarted'
  774. : 'simulcastlayerstopped');
  775. } else {
  776. this.logger.error("I don't have a local stream with SSRC " + ssrc);
  777. }
  778. };
  779. SimpleSimulcastSender.prototype.constructor = SimpleSimulcastSender;
  780. function NoSimulcastSender() {
  781. SimulcastSender.call(this);
  782. }
  783. NoSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  784. /**
  785. * GUM for simulcast.
  786. *
  787. * @param constraints
  788. * @param success
  789. * @param err
  790. */
  791. NoSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  792. var self = this;
  793. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  794. self.localStream = hqStream;
  795. success(self.localStream);
  796. }, err);
  797. };
  798. /**
  799. * Prepares the local description for public usage (i.e. to be signaled
  800. * through Jingle to the focus).
  801. *
  802. * @param desc
  803. * @returns {RTCSessionDescription}
  804. */
  805. NoSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  806. return desc;
  807. };
  808. /**
  809. * Ensures that the simulcast group is present in the answer, _if_ native
  810. * simulcast is enabled,
  811. *
  812. * @param desc
  813. * @returns {*}
  814. */
  815. NoSimulcastSender.prototype.transformAnswer = function (desc) {
  816. return desc;
  817. };
  818. /**
  819. *
  820. *
  821. * @param desc
  822. * @returns {*}
  823. */
  824. NoSimulcastSender.prototype.transformLocalDescription = function (desc) {
  825. return desc;
  826. };
  827. NoSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  828. };
  829. NoSimulcastSender.prototype.constructor = NoSimulcastSender;
  830. /**
  831. *
  832. * @constructor
  833. */
  834. function SimulcastManager() {
  835. // Create the simulcast utilities.
  836. this.simulcastUtils = new SimulcastUtils();
  837. // Create remote simulcast.
  838. this.simulcastReceiver = new SimulcastReceiver();
  839. // Initialize local simulcast.
  840. // TODO(gp) move into SimulcastManager.prototype.getUserMedia and take into
  841. // account constraints.
  842. if (!config.enableSimulcast) {
  843. this.simulcastSender = new NoSimulcastSender();
  844. } else {
  845. var isChromium = window.chrome,
  846. vendorName = window.navigator.vendor;
  847. if(isChromium !== null && isChromium !== undefined
  848. /* skip opera */
  849. && vendorName === "Google Inc."
  850. /* skip Chromium as suggested by fippo */
  851. && !window.navigator.appVersion.match(/Chromium\//) ) {
  852. var ver = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
  853. if (ver > 37) {
  854. this.simulcastSender = new NativeSimulcastSender();
  855. } else {
  856. this.simulcastSender = new NoSimulcastSender();
  857. }
  858. } else {
  859. this.simulcastSender = new NoSimulcastSender();
  860. }
  861. }
  862. }
  863. /**
  864. * Restores the simulcast groups of the remote description. In
  865. * transformRemoteDescription we remove those in order for the set remote
  866. * description to succeed. The focus needs the signal the groups to new
  867. * participants.
  868. *
  869. * @param desc
  870. * @returns {*}
  871. */
  872. SimulcastManager.prototype.reverseTransformRemoteDescription = function (desc) {
  873. return this.simulcastReceiver.reverseTransformRemoteDescription(desc);
  874. };
  875. /**
  876. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  877. * either gets confused and thinks this is an FID group or, if an FID group
  878. * is already present, it fails to set the remote description.
  879. *
  880. * @param desc
  881. * @returns {*}
  882. */
  883. SimulcastManager.prototype.transformRemoteDescription = function (desc) {
  884. return this.simulcastReceiver.transformRemoteDescription(desc);
  885. };
  886. /**
  887. * Gets the fully qualified msid (stream.id + track.id) associated to the
  888. * SSRC.
  889. *
  890. * @param ssrc
  891. * @returns {*}
  892. */
  893. SimulcastManager.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  894. return this.simulcastReceiver.getRemoteVideoStreamIdBySSRC(ssrc);
  895. };
  896. /**
  897. * Returns a stream with single video track, the one currently being
  898. * received by this endpoint.
  899. *
  900. * @param stream the remote simulcast stream.
  901. * @returns {webkitMediaStream}
  902. */
  903. SimulcastManager.prototype.getReceivingVideoStream = function (stream) {
  904. return this.simulcastReceiver.getReceivingVideoStream(stream);
  905. };
  906. /**
  907. *
  908. *
  909. * @param desc
  910. * @returns {*}
  911. */
  912. SimulcastManager.prototype.transformLocalDescription = function (desc) {
  913. return this.simulcastSender.transformLocalDescription(desc);
  914. };
  915. /**
  916. *
  917. * @returns {*}
  918. */
  919. SimulcastManager.prototype.getLocalVideoStream = function() {
  920. return this.simulcastSender.getLocalVideoStream();
  921. };
  922. /**
  923. * GUM for simulcast.
  924. *
  925. * @param constraints
  926. * @param success
  927. * @param err
  928. */
  929. SimulcastManager.prototype.getUserMedia = function (constraints, success, err) {
  930. this.simulcastSender.getUserMedia(constraints, success, err);
  931. };
  932. /**
  933. * Prepares the local description for public usage (i.e. to be signaled
  934. * through Jingle to the focus).
  935. *
  936. * @param desc
  937. * @returns {RTCSessionDescription}
  938. */
  939. SimulcastManager.prototype.reverseTransformLocalDescription = function (desc) {
  940. return this.simulcastSender.reverseTransformLocalDescription(desc);
  941. };
  942. /**
  943. * Ensures that the simulcast group is present in the answer, _if_ native
  944. * simulcast is enabled,
  945. *
  946. * @param desc
  947. * @returns {*}
  948. */
  949. SimulcastManager.prototype.transformAnswer = function (desc) {
  950. return this.simulcastSender.transformAnswer(desc);
  951. };
  952. SimulcastManager.prototype.getReceivingSSRC = function (jid) {
  953. return this.simulcastReceiver.getReceivingSSRC(jid);
  954. };
  955. SimulcastManager.prototype.getReceivingVideoStreamBySSRC = function (msid) {
  956. return this.simulcastReceiver.getReceivingVideoStreamBySSRC(msid);
  957. };
  958. /**
  959. *
  960. * @param lines
  961. * @param mediatypes
  962. * @returns {*}
  963. */
  964. SimulcastManager.prototype.parseMedia = function(lines, mediatypes) {
  965. var sb = lines.sdp.split('\r\n');
  966. return this.simulcastUtils.parseMedia(sb, mediatypes);
  967. };
  968. SimulcastManager.prototype._setReceivingVideoStream = function(resource, ssrc) {
  969. this.simulcastReceiver._setReceivingVideoStream(resource, ssrc);
  970. };
  971. SimulcastManager.prototype._setLocalVideoStreamEnabled = function(ssrc, enabled) {
  972. this.simulcastSender._setLocalVideoStreamEnabled(ssrc, enabled);
  973. };
  974. /**
  975. *
  976. * @constructor
  977. */
  978. function SimulcastLogger(name) {
  979. this.name = name;
  980. }
  981. SimulcastLogger.prototype.log = function (text) {
  982. console.log(text);
  983. };
  984. SimulcastLogger.prototype.info = function (text) {
  985. console.info(text);
  986. };
  987. SimulcastLogger.prototype.fine = function (text) {
  988. console.log(text);
  989. };
  990. SimulcastLogger.prototype.error = function (text) {
  991. console.error(text);
  992. };
  993. var simulcast = new SimulcastManager();
  994. $(document).bind('simulcastlayerschanged', function (event, endpointSimulcastLayers) {
  995. endpointSimulcastLayers.forEach(function (esl) {
  996. var ssrc = esl.simulcastLayer.primarySSRC;
  997. simulcast._setReceivingVideoStream(esl.endpoint, ssrc);
  998. });
  999. });
  1000. $(document).bind('startsimulcastlayer', function (event, simulcastLayer) {
  1001. var ssrc = simulcastLayer.primarySSRC;
  1002. simulcast._setLocalVideoStreamEnabled(ssrc, true);
  1003. });
  1004. $(document).bind('stopsimulcastlayer', function (event, simulcastLayer) {
  1005. var ssrc = simulcastLayer.primarySSRC;
  1006. simulcast._setLocalVideoStreamEnabled(ssrc, false);
  1007. });