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.

strophe.jingle.sdp.js 41KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  1. /* jshint -W117 */
  2. // SDP STUFF
  3. function SDP(sdp) {
  4. this.media = sdp.split('\r\nm=');
  5. for (var i = 1; i < this.media.length; i++) {
  6. this.media[i] = 'm=' + this.media[i];
  7. if (i != this.media.length - 1) {
  8. this.media[i] += '\r\n';
  9. }
  10. }
  11. this.session = this.media.shift() + '\r\n';
  12. this.raw = this.session + this.media.join('');
  13. }
  14. /**
  15. * Returns map of MediaChannel mapped per channel idx.
  16. */
  17. SDP.prototype.getMediaSsrcMap = function() {
  18. var self = this;
  19. var media_ssrcs = {};
  20. var tmp;
  21. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  22. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  23. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  24. var media = {
  25. mediaindex: mediaindex,
  26. mid: mid,
  27. ssrcs: {},
  28. ssrcGroups: []
  29. };
  30. media_ssrcs[mediaindex] = media;
  31. tmp.forEach(function (line) {
  32. var linessrc = line.substring(7).split(' ')[0];
  33. // allocate new ChannelSsrc
  34. if(!media.ssrcs[linessrc]) {
  35. media.ssrcs[linessrc] = {
  36. ssrc: linessrc,
  37. lines: []
  38. };
  39. }
  40. media.ssrcs[linessrc].lines.push(line);
  41. });
  42. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  43. tmp.forEach(function(line){
  44. var semantics = line.substr(0, idx).substr(13);
  45. var ssrcs = line.substr(14 + semantics.length).split(' ');
  46. if (ssrcs.length != 0) {
  47. media.ssrcGroups.push({
  48. semantics: semantics,
  49. ssrcs: ssrcs
  50. });
  51. }
  52. });
  53. }
  54. return media_ssrcs;
  55. };
  56. /**
  57. * Returns <tt>true</tt> if this SDP contains given SSRC.
  58. * @param ssrc the ssrc to check.
  59. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  60. */
  61. SDP.prototype.containsSSRC = function(ssrc) {
  62. var medias = this.getMediaSsrcMap();
  63. var contains = false;
  64. Object.keys(medias).forEach(function(mediaindex){
  65. var media = medias[mediaindex];
  66. //console.log("Check", channel, ssrc);
  67. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  68. contains = true;
  69. }
  70. });
  71. return contains;
  72. };
  73. function SDPDiffer(mySDP, otherSDP) {
  74. this.mySDP = mySDP;
  75. this.otherSDP = otherSDP;
  76. }
  77. /**
  78. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  79. * @param otherSdp the other SDP to check ssrc with.
  80. */
  81. SDPDiffer.prototype.getNewMedia = function() {
  82. // this could be useful in Array.prototype.
  83. function arrayEquals(array) {
  84. // if the other array is a falsy value, return
  85. if (!array)
  86. return false;
  87. // compare lengths - can save a lot of time
  88. if (this.length != array.length)
  89. return false;
  90. for (var i = 0, l=this.length; i < l; i++) {
  91. // Check if we have nested arrays
  92. if (this[i] instanceof Array && array[i] instanceof Array) {
  93. // recurse into the nested arrays
  94. if (!this[i].equals(array[i]))
  95. return false;
  96. }
  97. else if (this[i] != array[i]) {
  98. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  99. return false;
  100. }
  101. }
  102. return true;
  103. }
  104. var myMedias = this.mySDP.getMediaSsrcMap();
  105. var othersMedias = this.otherSDP.getMediaSsrcMap();
  106. var newMedia = {};
  107. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  108. var myMedia = myMedias[othersMediaIdx];
  109. var othersMedia = othersMedias[othersMediaIdx];
  110. if(!myMedia && othersMedia) {
  111. // Add whole channel
  112. newMedia[othersMediaIdx] = othersMedia;
  113. return;
  114. }
  115. // Look for new ssrcs accross the channel
  116. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  117. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  118. // Allocate channel if we've found ssrc that doesn't exist in our channel
  119. if(!newMedia[othersMediaIdx]){
  120. newMedia[othersMediaIdx] = {
  121. mediaindex: othersMedia.mediaindex,
  122. mid: othersMedia.mid,
  123. ssrcs: {},
  124. ssrcGroups: []
  125. };
  126. }
  127. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  128. }
  129. });
  130. // Look for new ssrc groups across the channels
  131. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  132. // try to match the other ssrc-group with an ssrc-group of ours
  133. var matched = false;
  134. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  135. var mySsrcGroup = myMedia.ssrcGroups[i];
  136. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  137. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  138. matched = true;
  139. break;
  140. }
  141. }
  142. if (!matched) {
  143. // Allocate channel if we've found an ssrc-group that doesn't
  144. // exist in our channel
  145. if(!newMedia[othersMediaIdx]){
  146. newMedia[othersMediaIdx] = {
  147. mediaindex: othersMedia.mediaindex,
  148. mid: othersMedia.mid,
  149. ssrcs: {},
  150. ssrcGroups: []
  151. };
  152. }
  153. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  154. }
  155. });
  156. });
  157. return newMedia;
  158. };
  159. /**
  160. * Sends SSRC update IQ.
  161. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  162. * @param sid session identifier that will be put into the IQ.
  163. * @param initiator initiator identifier.
  164. * @param toJid destination Jid
  165. * @param isAdd indicates if this is remove or add operation.
  166. */
  167. SDPDiffer.prototype.toJingle = function(modify) {
  168. var sdpMediaSsrcs = this.getNewMedia();
  169. var self = this;
  170. // FIXME: only announce video ssrcs since we mix audio and dont need
  171. // the audio ssrcs therefore
  172. var modified = false;
  173. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  174. modified = true;
  175. var media = sdpMediaSsrcs[mediaindex];
  176. modify.c('content', {name: media.mid});
  177. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  178. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  179. // generate sources from lines
  180. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  181. var mediaSsrc = media.ssrcs[ssrcNum];
  182. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  183. modify.attrs({ssrc: mediaSsrc.ssrc});
  184. // iterate over ssrc lines
  185. mediaSsrc.lines.forEach(function (line) {
  186. var idx = line.indexOf(' ');
  187. var kv = line.substr(idx + 1);
  188. modify.c('parameter');
  189. if (kv.indexOf(':') == -1) {
  190. modify.attrs({ name: kv });
  191. } else {
  192. modify.attrs({ name: kv.split(':', 2)[0] });
  193. modify.attrs({ value: kv.split(':', 2)[1] });
  194. }
  195. modify.up(); // end of parameter
  196. });
  197. modify.up(); // end of source
  198. });
  199. // generate source groups from lines
  200. media.ssrcGroups.forEach(function(ssrcGroup) {
  201. if (ssrcGroup.ssrcs.length != 0) {
  202. modify.c('ssrc-group', {
  203. semantics: ssrcGroup.semantics,
  204. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  205. });
  206. ssrcGroup.ssrcs.forEach(function (ssrc) {
  207. modify.c('source', { ssrc: ssrc })
  208. .up(); // end of source
  209. });
  210. modify.up(); // end of ssrc-group
  211. }
  212. });
  213. modify.up(); // end of description
  214. modify.up(); // end of content
  215. });
  216. return modified;
  217. };
  218. // remove iSAC and CN from SDP
  219. SDP.prototype.mangle = function () {
  220. var i, j, mline, lines, rtpmap, newdesc;
  221. for (i = 0; i < this.media.length; i++) {
  222. lines = this.media[i].split('\r\n');
  223. lines.pop(); // remove empty last element
  224. mline = SDPUtil.parse_mline(lines.shift());
  225. if (mline.media != 'audio')
  226. continue;
  227. newdesc = '';
  228. mline.fmt.length = 0;
  229. for (j = 0; j < lines.length; j++) {
  230. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  231. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  232. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  233. continue;
  234. mline.fmt.push(rtpmap.id);
  235. newdesc += lines[j] + '\r\n';
  236. } else {
  237. newdesc += lines[j] + '\r\n';
  238. }
  239. }
  240. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  241. this.media[i] += newdesc;
  242. }
  243. this.raw = this.session + this.media.join('');
  244. };
  245. // remove lines matching prefix from session section
  246. SDP.prototype.removeSessionLines = function(prefix) {
  247. var self = this;
  248. var lines = SDPUtil.find_lines(this.session, prefix);
  249. lines.forEach(function(line) {
  250. self.session = self.session.replace(line + '\r\n', '');
  251. });
  252. this.raw = this.session + this.media.join('');
  253. return lines;
  254. }
  255. // remove lines matching prefix from a media section specified by mediaindex
  256. // TODO: non-numeric mediaindex could match mid
  257. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  258. var self = this;
  259. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  260. lines.forEach(function(line) {
  261. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  262. });
  263. this.raw = this.session + this.media.join('');
  264. return lines;
  265. }
  266. // add content's to a jingle element
  267. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  268. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  269. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  270. var self = this;
  271. // new bundle plan
  272. if (SDPUtil.find_line(this.session, 'a=group:')) {
  273. lines = SDPUtil.find_lines(this.session, 'a=group:');
  274. for (i = 0; i < lines.length; i++) {
  275. tmp = lines[i].split(' ');
  276. var semantics = tmp.shift().substr(8);
  277. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  278. for (j = 0; j < tmp.length; j++) {
  279. elem.c('content', {name: tmp[j]}).up();
  280. }
  281. elem.up();
  282. }
  283. }
  284. for (i = 0; i < this.media.length; i++) {
  285. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  286. if (!(mline.media === 'audio' ||
  287. mline.media === 'video' ||
  288. mline.media === 'application'))
  289. {
  290. continue;
  291. }
  292. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  293. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  294. } else {
  295. if(ssrcs && ssrcs[mline.media])
  296. {
  297. ssrc = ssrcs[mline.media];
  298. }
  299. else
  300. ssrc = false;
  301. }
  302. elem.c('content', {creator: thecreator, name: mline.media});
  303. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  304. // prefer identifier from a=mid if present
  305. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  306. elem.attrs({ name: mid });
  307. }
  308. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  309. {
  310. elem.c('description',
  311. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  312. media: mline.media });
  313. if (ssrc) {
  314. elem.attrs({ssrc: ssrc});
  315. }
  316. for (j = 0; j < mline.fmt.length; j++) {
  317. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  318. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  319. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  320. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  321. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  322. for (k = 0; k < tmp.length; k++) {
  323. elem.c('parameter', tmp[k]).up();
  324. }
  325. }
  326. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  327. elem.up();
  328. }
  329. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  330. elem.c('encryption', {required: 1});
  331. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  332. crypto.forEach(function(line) {
  333. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  334. });
  335. elem.up(); // end of encryption
  336. }
  337. if (ssrc) {
  338. // new style mapping
  339. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  340. // FIXME: group by ssrc and support multiple different ssrcs
  341. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  342. if(ssrclines.length > 0) {
  343. ssrclines.forEach(function (line) {
  344. idx = line.indexOf(' ');
  345. var linessrc = line.substr(0, idx).substr(7);
  346. if (linessrc != ssrc) {
  347. elem.up();
  348. ssrc = linessrc;
  349. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  350. }
  351. var kv = line.substr(idx + 1);
  352. elem.c('parameter');
  353. if (kv.indexOf(':') == -1) {
  354. elem.attrs({ name: kv });
  355. } else {
  356. elem.attrs({ name: kv.split(':', 2)[0] });
  357. elem.attrs({ value: kv.split(':', 2)[1] });
  358. }
  359. elem.up();
  360. });
  361. elem.up();
  362. }
  363. else
  364. {
  365. elem.up();
  366. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  367. elem.c('parameter');
  368. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  369. elem.up();
  370. var msid = null;
  371. if(mline.media == "audio")
  372. {
  373. msid = RTC.localAudio.getId();
  374. }
  375. else
  376. {
  377. msid = RTC.localVideo.getId();
  378. }
  379. if(msid != null)
  380. {
  381. msid = msid.replace(/[\{,\}]/g,"");
  382. elem.c('parameter');
  383. elem.attrs({name: "msid", value:msid});
  384. elem.up();
  385. elem.c('parameter');
  386. elem.attrs({name: "mslabel", value:msid});
  387. elem.up();
  388. elem.c('parameter');
  389. elem.attrs({name: "label", value:msid});
  390. elem.up();
  391. elem.up();
  392. }
  393. }
  394. // XEP-0339 handle ssrc-group attributes
  395. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  396. ssrc_group_lines.forEach(function(line) {
  397. idx = line.indexOf(' ');
  398. var semantics = line.substr(0, idx).substr(13);
  399. var ssrcs = line.substr(14 + semantics.length).split(' ');
  400. if (ssrcs.length != 0) {
  401. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  402. ssrcs.forEach(function(ssrc) {
  403. elem.c('source', { ssrc: ssrc })
  404. .up();
  405. });
  406. elem.up();
  407. }
  408. });
  409. }
  410. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  411. elem.c('rtcp-mux').up();
  412. }
  413. // XEP-0293 -- map a=rtcp-fb:*
  414. this.RtcpFbToJingle(i, elem, '*');
  415. // XEP-0294
  416. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  417. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  418. for (j = 0; j < lines.length; j++) {
  419. tmp = SDPUtil.parse_extmap(lines[j]);
  420. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  421. uri: tmp.uri,
  422. id: tmp.value });
  423. if (tmp.hasOwnProperty('direction')) {
  424. switch (tmp.direction) {
  425. case 'sendonly':
  426. elem.attrs({senders: 'responder'});
  427. break;
  428. case 'recvonly':
  429. elem.attrs({senders: 'initiator'});
  430. break;
  431. case 'sendrecv':
  432. elem.attrs({senders: 'both'});
  433. break;
  434. case 'inactive':
  435. elem.attrs({senders: 'none'});
  436. break;
  437. }
  438. }
  439. // TODO: handle params
  440. elem.up();
  441. }
  442. }
  443. elem.up(); // end of description
  444. }
  445. // map ice-ufrag/pwd, dtls fingerprint, candidates
  446. this.TransportToJingle(i, elem);
  447. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  448. elem.attrs({senders: 'both'});
  449. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  450. elem.attrs({senders: 'initiator'});
  451. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  452. elem.attrs({senders: 'responder'});
  453. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  454. elem.attrs({senders: 'none'});
  455. }
  456. if (mline.port == '0') {
  457. // estos hack to reject an m-line
  458. elem.attrs({senders: 'rejected'});
  459. }
  460. elem.up(); // end of content
  461. }
  462. elem.up();
  463. return elem;
  464. };
  465. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  466. var i = mediaindex;
  467. var tmp;
  468. var self = this;
  469. elem.c('transport');
  470. // XEP-0343 DTLS/SCTP
  471. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  472. {
  473. var sctpmap = SDPUtil.find_line(
  474. this.media[i], 'a=sctpmap:', self.session);
  475. if (sctpmap)
  476. {
  477. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  478. elem.c('sctpmap',
  479. {
  480. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  481. number: sctpAttrs[0], /* SCTP port */
  482. protocol: sctpAttrs[1], /* protocol */
  483. });
  484. // Optional stream count attribute
  485. if (sctpAttrs.length > 2)
  486. elem.attrs({ streams: sctpAttrs[2]});
  487. elem.up();
  488. }
  489. }
  490. // XEP-0320
  491. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  492. fingerprints.forEach(function(line) {
  493. tmp = SDPUtil.parse_fingerprint(line);
  494. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  495. elem.c('fingerprint').t(tmp.fingerprint);
  496. delete tmp.fingerprint;
  497. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  498. if (line) {
  499. tmp.setup = line.substr(8);
  500. }
  501. elem.attrs(tmp);
  502. elem.up(); // end of fingerprint
  503. });
  504. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  505. if (tmp) {
  506. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  507. elem.attrs(tmp);
  508. // XEP-0176
  509. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  510. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  511. lines.forEach(function (line) {
  512. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  513. });
  514. }
  515. }
  516. elem.up(); // end of transport
  517. }
  518. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  519. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  520. lines.forEach(function (line) {
  521. var tmp = SDPUtil.parse_rtcpfb(line);
  522. if (tmp.type == 'trr-int') {
  523. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  524. elem.up();
  525. } else {
  526. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  527. if (tmp.params.length > 0) {
  528. elem.attrs({'subtype': tmp.params[0]});
  529. }
  530. elem.up();
  531. }
  532. });
  533. };
  534. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  535. var media = '';
  536. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  537. if (tmp.length) {
  538. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  539. if (tmp.attr('value')) {
  540. media += tmp.attr('value');
  541. } else {
  542. media += '0';
  543. }
  544. media += '\r\n';
  545. }
  546. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  547. tmp.each(function () {
  548. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  549. if ($(this).attr('subtype')) {
  550. media += ' ' + $(this).attr('subtype');
  551. }
  552. media += '\r\n';
  553. });
  554. return media;
  555. };
  556. // construct an SDP from a jingle stanza
  557. SDP.prototype.fromJingle = function (jingle) {
  558. var self = this;
  559. this.raw = 'v=0\r\n' +
  560. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  561. 's=-\r\n' +
  562. 't=0 0\r\n';
  563. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  564. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  565. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  566. var contents = $(group).find('>content').map(function (idx, content) {
  567. return content.getAttribute('name');
  568. }).get();
  569. if (contents.length > 0) {
  570. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  571. }
  572. });
  573. }
  574. this.session = this.raw;
  575. jingle.find('>content').each(function () {
  576. var m = self.jingle2media($(this));
  577. self.media.push(m);
  578. });
  579. // reconstruct msid-semantic -- apparently not necessary
  580. /*
  581. var msid = SDPUtil.parse_ssrc(this.raw);
  582. if (msid.hasOwnProperty('mslabel')) {
  583. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  584. }
  585. */
  586. this.raw = this.session + this.media.join('');
  587. };
  588. // translate a jingle content element into an an SDP media part
  589. SDP.prototype.jingle2media = function (content) {
  590. var media = '',
  591. desc = content.find('description'),
  592. ssrc = desc.attr('ssrc'),
  593. self = this,
  594. tmp;
  595. var sctp = content.find(
  596. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  597. tmp = { media: desc.attr('media') };
  598. tmp.port = '1';
  599. if (content.attr('senders') == 'rejected') {
  600. // estos hack to reject an m-line.
  601. tmp.port = '0';
  602. }
  603. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  604. if (sctp.length)
  605. tmp.proto = 'DTLS/SCTP';
  606. else
  607. tmp.proto = 'RTP/SAVPF';
  608. } else {
  609. tmp.proto = 'RTP/AVPF';
  610. }
  611. if (!sctp.length)
  612. {
  613. tmp.fmt = desc.find('payload-type').map(
  614. function () { return this.getAttribute('id'); }).get();
  615. media += SDPUtil.build_mline(tmp) + '\r\n';
  616. }
  617. else
  618. {
  619. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  620. media += 'a=sctpmap:' + sctp.attr('number') +
  621. ' ' + sctp.attr('protocol');
  622. var streamCount = sctp.attr('streams');
  623. if (streamCount)
  624. media += ' ' + streamCount + '\r\n';
  625. else
  626. media += '\r\n';
  627. }
  628. media += 'c=IN IP4 0.0.0.0\r\n';
  629. if (!sctp.length)
  630. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  631. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  632. if (tmp.length) {
  633. if (tmp.attr('ufrag')) {
  634. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  635. }
  636. if (tmp.attr('pwd')) {
  637. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  638. }
  639. tmp.find('>fingerprint').each(function () {
  640. // FIXME: check namespace at some point
  641. media += 'a=fingerprint:' + this.getAttribute('hash');
  642. media += ' ' + $(this).text();
  643. media += '\r\n';
  644. if (this.getAttribute('setup')) {
  645. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  646. }
  647. });
  648. }
  649. switch (content.attr('senders')) {
  650. case 'initiator':
  651. media += 'a=sendonly\r\n';
  652. break;
  653. case 'responder':
  654. media += 'a=recvonly\r\n';
  655. break;
  656. case 'none':
  657. media += 'a=inactive\r\n';
  658. break;
  659. case 'both':
  660. media += 'a=sendrecv\r\n';
  661. break;
  662. }
  663. media += 'a=mid:' + content.attr('name') + '\r\n';
  664. // <description><rtcp-mux/></description>
  665. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  666. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  667. if (desc.find('rtcp-mux').length) {
  668. media += 'a=rtcp-mux\r\n';
  669. }
  670. if (desc.find('encryption').length) {
  671. desc.find('encryption>crypto').each(function () {
  672. media += 'a=crypto:' + this.getAttribute('tag');
  673. media += ' ' + this.getAttribute('crypto-suite');
  674. media += ' ' + this.getAttribute('key-params');
  675. if (this.getAttribute('session-params')) {
  676. media += ' ' + this.getAttribute('session-params');
  677. }
  678. media += '\r\n';
  679. });
  680. }
  681. desc.find('payload-type').each(function () {
  682. media += SDPUtil.build_rtpmap(this) + '\r\n';
  683. if ($(this).find('>parameter').length) {
  684. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  685. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  686. media += '\r\n';
  687. }
  688. // xep-0293
  689. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  690. });
  691. // xep-0293
  692. media += self.RtcpFbFromJingle(desc, '*');
  693. // xep-0294
  694. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  695. tmp.each(function () {
  696. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  697. });
  698. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  699. media += SDPUtil.candidateFromJingle(this);
  700. });
  701. // XEP-0339 handle ssrc-group attributes
  702. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  703. var semantics = this.getAttribute('semantics');
  704. var ssrcs = $(this).find('>source').map(function() {
  705. return this.getAttribute('ssrc');
  706. }).get();
  707. if (ssrcs.length != 0) {
  708. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  709. }
  710. });
  711. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  712. tmp.each(function () {
  713. var ssrc = this.getAttribute('ssrc');
  714. $(this).find('>parameter').each(function () {
  715. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  716. if (this.getAttribute('value') && this.getAttribute('value').length)
  717. media += ':' + this.getAttribute('value');
  718. media += '\r\n';
  719. });
  720. });
  721. return media;
  722. };
  723. SDPUtil = {
  724. iceparams: function (mediadesc, sessiondesc) {
  725. var data = null;
  726. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  727. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  728. data = {
  729. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  730. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  731. };
  732. }
  733. return data;
  734. },
  735. parse_iceufrag: function (line) {
  736. return line.substring(12);
  737. },
  738. build_iceufrag: function (frag) {
  739. return 'a=ice-ufrag:' + frag;
  740. },
  741. parse_icepwd: function (line) {
  742. return line.substring(10);
  743. },
  744. build_icepwd: function (pwd) {
  745. return 'a=ice-pwd:' + pwd;
  746. },
  747. parse_mid: function (line) {
  748. return line.substring(6);
  749. },
  750. parse_mline: function (line) {
  751. var parts = line.substring(2).split(' '),
  752. data = {};
  753. data.media = parts.shift();
  754. data.port = parts.shift();
  755. data.proto = parts.shift();
  756. if (parts[parts.length - 1] === '') { // trailing whitespace
  757. parts.pop();
  758. }
  759. data.fmt = parts;
  760. return data;
  761. },
  762. build_mline: function (mline) {
  763. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  764. },
  765. parse_rtpmap: function (line) {
  766. var parts = line.substring(9).split(' '),
  767. data = {};
  768. data.id = parts.shift();
  769. parts = parts[0].split('/');
  770. data.name = parts.shift();
  771. data.clockrate = parts.shift();
  772. data.channels = parts.length ? parts.shift() : '1';
  773. return data;
  774. },
  775. /**
  776. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  777. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  778. * @returns [SCTP port number, protocol, streams]
  779. */
  780. parse_sctpmap: function (line)
  781. {
  782. var parts = line.substring(10).split(' ');
  783. var sctpPort = parts[0];
  784. var protocol = parts[1];
  785. // Stream count is optional
  786. var streamCount = parts.length > 2 ? parts[2] : null;
  787. return [sctpPort, protocol, streamCount];// SCTP port
  788. },
  789. build_rtpmap: function (el) {
  790. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  791. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  792. line += '/' + el.getAttribute('channels');
  793. }
  794. return line;
  795. },
  796. parse_crypto: function (line) {
  797. var parts = line.substring(9).split(' '),
  798. data = {};
  799. data.tag = parts.shift();
  800. data['crypto-suite'] = parts.shift();
  801. data['key-params'] = parts.shift();
  802. if (parts.length) {
  803. data['session-params'] = parts.join(' ');
  804. }
  805. return data;
  806. },
  807. parse_fingerprint: function (line) { // RFC 4572
  808. var parts = line.substring(14).split(' '),
  809. data = {};
  810. data.hash = parts.shift();
  811. data.fingerprint = parts.shift();
  812. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  813. return data;
  814. },
  815. parse_fmtp: function (line) {
  816. var parts = line.split(' '),
  817. i, key, value,
  818. data = [];
  819. parts.shift();
  820. parts = parts.join(' ').split(';');
  821. for (i = 0; i < parts.length; i++) {
  822. key = parts[i].split('=')[0];
  823. while (key.length && key[0] == ' ') {
  824. key = key.substring(1);
  825. }
  826. value = parts[i].split('=')[1];
  827. if (key && value) {
  828. data.push({name: key, value: value});
  829. } else if (key) {
  830. // rfc 4733 (DTMF) style stuff
  831. data.push({name: '', value: key});
  832. }
  833. }
  834. return data;
  835. },
  836. parse_icecandidate: function (line) {
  837. var candidate = {},
  838. elems = line.split(' ');
  839. candidate.foundation = elems[0].substring(12);
  840. candidate.component = elems[1];
  841. candidate.protocol = elems[2].toLowerCase();
  842. candidate.priority = elems[3];
  843. candidate.ip = elems[4];
  844. candidate.port = elems[5];
  845. // elems[6] => "typ"
  846. candidate.type = elems[7];
  847. candidate.generation = 0; // default value, may be overwritten below
  848. for (var i = 8; i < elems.length; i += 2) {
  849. switch (elems[i]) {
  850. case 'raddr':
  851. candidate['rel-addr'] = elems[i + 1];
  852. break;
  853. case 'rport':
  854. candidate['rel-port'] = elems[i + 1];
  855. break;
  856. case 'generation':
  857. candidate.generation = elems[i + 1];
  858. break;
  859. case 'tcptype':
  860. candidate.tcptype = elems[i + 1];
  861. break;
  862. default: // TODO
  863. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  864. }
  865. }
  866. candidate.network = '1';
  867. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  868. return candidate;
  869. },
  870. build_icecandidate: function (cand) {
  871. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  872. line += ' ';
  873. switch (cand.type) {
  874. case 'srflx':
  875. case 'prflx':
  876. case 'relay':
  877. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  878. line += 'raddr';
  879. line += ' ';
  880. line += cand['rel-addr'];
  881. line += ' ';
  882. line += 'rport';
  883. line += ' ';
  884. line += cand['rel-port'];
  885. line += ' ';
  886. }
  887. break;
  888. }
  889. if (cand.hasOwnAttribute('tcptype')) {
  890. line += 'tcptype';
  891. line += ' ';
  892. line += cand.tcptype;
  893. line += ' ';
  894. }
  895. line += 'generation';
  896. line += ' ';
  897. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  898. return line;
  899. },
  900. parse_ssrc: function (desc) {
  901. // proprietary mapping of a=ssrc lines
  902. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  903. // and parse according to that
  904. var lines = desc.split('\r\n'),
  905. data = {};
  906. for (var i = 0; i < lines.length; i++) {
  907. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  908. var idx = lines[i].indexOf(' ');
  909. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  910. }
  911. }
  912. return data;
  913. },
  914. parse_rtcpfb: function (line) {
  915. var parts = line.substr(10).split(' ');
  916. var data = {};
  917. data.pt = parts.shift();
  918. data.type = parts.shift();
  919. data.params = parts;
  920. return data;
  921. },
  922. parse_extmap: function (line) {
  923. var parts = line.substr(9).split(' ');
  924. var data = {};
  925. data.value = parts.shift();
  926. if (data.value.indexOf('/') != -1) {
  927. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  928. data.value = data.value.substr(0, data.value.indexOf('/'));
  929. } else {
  930. data.direction = 'both';
  931. }
  932. data.uri = parts.shift();
  933. data.params = parts;
  934. return data;
  935. },
  936. find_line: function (haystack, needle, sessionpart) {
  937. var lines = haystack.split('\r\n');
  938. for (var i = 0; i < lines.length; i++) {
  939. if (lines[i].substring(0, needle.length) == needle) {
  940. return lines[i];
  941. }
  942. }
  943. if (!sessionpart) {
  944. return false;
  945. }
  946. // search session part
  947. lines = sessionpart.split('\r\n');
  948. for (var j = 0; j < lines.length; j++) {
  949. if (lines[j].substring(0, needle.length) == needle) {
  950. return lines[j];
  951. }
  952. }
  953. return false;
  954. },
  955. find_lines: function (haystack, needle, sessionpart) {
  956. var lines = haystack.split('\r\n'),
  957. needles = [];
  958. for (var i = 0; i < lines.length; i++) {
  959. if (lines[i].substring(0, needle.length) == needle)
  960. needles.push(lines[i]);
  961. }
  962. if (needles.length || !sessionpart) {
  963. return needles;
  964. }
  965. // search session part
  966. lines = sessionpart.split('\r\n');
  967. for (var j = 0; j < lines.length; j++) {
  968. if (lines[j].substring(0, needle.length) == needle) {
  969. needles.push(lines[j]);
  970. }
  971. }
  972. return needles;
  973. },
  974. candidateToJingle: function (line) {
  975. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  976. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  977. if (line.indexOf('candidate:') === 0) {
  978. line = 'a=' + line;
  979. } else if (line.substring(0, 12) != 'a=candidate:') {
  980. console.log('parseCandidate called with a line that is not a candidate line');
  981. console.log(line);
  982. return null;
  983. }
  984. if (line.substring(line.length - 2) == '\r\n') // chomp it
  985. line = line.substring(0, line.length - 2);
  986. var candidate = {},
  987. elems = line.split(' '),
  988. i;
  989. if (elems[6] != 'typ') {
  990. console.log('did not find typ in the right place');
  991. console.log(line);
  992. return null;
  993. }
  994. candidate.foundation = elems[0].substring(12);
  995. candidate.component = elems[1];
  996. candidate.protocol = elems[2].toLowerCase();
  997. candidate.priority = elems[3];
  998. candidate.ip = elems[4];
  999. candidate.port = elems[5];
  1000. // elems[6] => "typ"
  1001. candidate.type = elems[7];
  1002. candidate.generation = '0'; // default, may be overwritten below
  1003. for (i = 8; i < elems.length; i += 2) {
  1004. switch (elems[i]) {
  1005. case 'raddr':
  1006. candidate['rel-addr'] = elems[i + 1];
  1007. break;
  1008. case 'rport':
  1009. candidate['rel-port'] = elems[i + 1];
  1010. break;
  1011. case 'generation':
  1012. candidate.generation = elems[i + 1];
  1013. break;
  1014. case 'tcptype':
  1015. candidate.tcptype = elems[i + 1];
  1016. break;
  1017. default: // TODO
  1018. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  1019. }
  1020. }
  1021. candidate.network = '1';
  1022. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  1023. return candidate;
  1024. },
  1025. candidateFromJingle: function (cand) {
  1026. var line = 'a=candidate:';
  1027. line += cand.getAttribute('foundation');
  1028. line += ' ';
  1029. line += cand.getAttribute('component');
  1030. line += ' ';
  1031. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  1032. line += ' ';
  1033. line += cand.getAttribute('priority');
  1034. line += ' ';
  1035. line += cand.getAttribute('ip');
  1036. line += ' ';
  1037. line += cand.getAttribute('port');
  1038. line += ' ';
  1039. line += 'typ';
  1040. line += ' ' + cand.getAttribute('type');
  1041. line += ' ';
  1042. switch (cand.getAttribute('type')) {
  1043. case 'srflx':
  1044. case 'prflx':
  1045. case 'relay':
  1046. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  1047. line += 'raddr';
  1048. line += ' ';
  1049. line += cand.getAttribute('rel-addr');
  1050. line += ' ';
  1051. line += 'rport';
  1052. line += ' ';
  1053. line += cand.getAttribute('rel-port');
  1054. line += ' ';
  1055. }
  1056. break;
  1057. }
  1058. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  1059. line += 'tcptype';
  1060. line += ' ';
  1061. line += cand.getAttribute('tcptype');
  1062. line += ' ';
  1063. }
  1064. line += 'generation';
  1065. line += ' ';
  1066. line += cand.getAttribute('generation') || '0';
  1067. return line + '\r\n';
  1068. }
  1069. };