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

strophe.jingle.adapter.js 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. function TraceablePeerConnection(ice_config, constraints) {
  2. var self = this;
  3. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  4. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  5. this.updateLog = [];
  6. this.stats = {};
  7. this.statsinterval = null;
  8. this.maxstats = 300; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  9. /**
  10. * Array of ssrcs that will be added on next modifySources call.
  11. * @type {Array}
  12. */
  13. this.addssrc = [];
  14. /**
  15. * Array of ssrcs that will be added on next modifySources call.
  16. * @type {Array}
  17. */
  18. this.removessrc = [];
  19. /**
  20. * Pending operation that will be done during modifySources call.
  21. * Currently 'mute'/'unmute' operations are supported.
  22. *
  23. * @type {String}
  24. */
  25. this.pendingop = null;
  26. // override as desired
  27. this.trace = function(what, info) {
  28. //console.warn('WTRACE', what, info);
  29. self.updateLog.push({
  30. time: new Date(),
  31. type: what,
  32. value: info || ""
  33. });
  34. };
  35. this.onicecandidate = null;
  36. this.peerconnection.onicecandidate = function (event) {
  37. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  38. if (self.onicecandidate !== null) {
  39. self.onicecandidate(event);
  40. }
  41. };
  42. this.onaddstream = null;
  43. this.peerconnection.onaddstream = function (event) {
  44. self.trace('onaddstream', event.stream.id);
  45. if (self.onaddstream !== null) {
  46. self.onaddstream(event);
  47. }
  48. };
  49. this.onremovestream = null;
  50. this.peerconnection.onremovestream = function (event) {
  51. self.trace('onremovestream', event.stream.id);
  52. if (self.onremovestream !== null) {
  53. self.onremovestream(event);
  54. }
  55. };
  56. this.onsignalingstatechange = null;
  57. this.peerconnection.onsignalingstatechange = function (event) {
  58. self.trace('onsignalingstatechange', event.srcElement.signalingState);
  59. if (self.onsignalingstatechange !== null) {
  60. self.onsignalingstatechange(event);
  61. }
  62. };
  63. this.oniceconnectionstatechange = null;
  64. this.peerconnection.oniceconnectionstatechange = function (event) {
  65. self.trace('oniceconnectionstatechange', event.srcElement.iceConnectionState);
  66. if (self.oniceconnectionstatechange !== null) {
  67. self.oniceconnectionstatechange(event);
  68. }
  69. };
  70. this.onnegotiationneeded = null;
  71. this.peerconnection.onnegotiationneeded = function (event) {
  72. self.trace('onnegotiationneeded');
  73. if (self.onnegotiationneeded !== null) {
  74. self.onnegotiationneeded(event);
  75. }
  76. };
  77. self.ondatachannel = null;
  78. this.peerconnection.ondatachannel = function (event) {
  79. self.trace('ondatachannel', event);
  80. if (self.ondatachannel !== null) {
  81. self.ondatachannel(event);
  82. }
  83. }
  84. if (!navigator.mozGetUserMedia) {
  85. this.statsinterval = window.setInterval(function() {
  86. self.peerconnection.getStats(function(stats) {
  87. var results = stats.result();
  88. for (var i = 0; i < results.length; ++i) {
  89. //console.log(results[i].type, results[i].id, results[i].names())
  90. var now = new Date();
  91. results[i].names().forEach(function (name) {
  92. var id = results[i].id + '-' + name;
  93. if (!self.stats[id]) {
  94. self.stats[id] = {
  95. startTime: now,
  96. endTime: now,
  97. values: [],
  98. times: []
  99. };
  100. }
  101. self.stats[id].values.push(results[i].stat(name));
  102. self.stats[id].times.push(now.getTime());
  103. if (self.stats[id].values.length > self.maxstats) {
  104. self.stats[id].values.shift();
  105. self.stats[id].times.shift();
  106. }
  107. self.stats[id].endTime = now;
  108. });
  109. }
  110. });
  111. }, 1000);
  112. }
  113. };
  114. dumpSDP = function(description) {
  115. return 'type: ' + description.type + '\r\n' + description.sdp;
  116. }
  117. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  118. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  119. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  120. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() { return this.peerconnection.localDescription; });
  121. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() { return this.peerconnection.remoteDescription; });
  122. }
  123. TraceablePeerConnection.prototype.addStream = function (stream) {
  124. this.trace('addStream', stream.id);
  125. this.peerconnection.addStream(stream);
  126. };
  127. TraceablePeerConnection.prototype.removeStream = function (stream) {
  128. this.trace('removeStream', stream.id);
  129. this.peerconnection.removeStream(stream);
  130. };
  131. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  132. this.trace('createDataChannel', label, opts);
  133. this.peerconnection.createDataChannel(label, opts);
  134. }
  135. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  136. var self = this;
  137. this.trace('setLocalDescription', dumpSDP(description));
  138. this.peerconnection.setLocalDescription(description,
  139. function () {
  140. self.trace('setLocalDescriptionOnSuccess');
  141. successCallback();
  142. },
  143. function (err) {
  144. self.trace('setLocalDescriptionOnFailure', err);
  145. failureCallback(err);
  146. }
  147. );
  148. /*
  149. if (this.statsinterval === null && this.maxstats > 0) {
  150. // start gathering stats
  151. }
  152. */
  153. };
  154. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  155. var self = this;
  156. this.trace('setRemoteDescription', dumpSDP(description));
  157. this.peerconnection.setRemoteDescription(description,
  158. function () {
  159. self.trace('setRemoteDescriptionOnSuccess');
  160. successCallback();
  161. },
  162. function (err) {
  163. self.trace('setRemoteDescriptionOnFailure', err);
  164. failureCallback(err);
  165. }
  166. );
  167. /*
  168. if (this.statsinterval === null && this.maxstats > 0) {
  169. // start gathering stats
  170. }
  171. */
  172. };
  173. TraceablePeerConnection.prototype.hardMuteVideo = function (muted) {
  174. this.pendingop = muted ? 'mute' : 'unmute';
  175. this.modifySources();
  176. };
  177. TraceablePeerConnection.prototype.enqueueAddSsrc = function(channel, ssrcLines) {
  178. if (!this.addssrc[channel]) {
  179. this.addssrc[channel] = '';
  180. }
  181. this.addssrc[channel] += ssrcLines;
  182. }
  183. TraceablePeerConnection.prototype.addSource = function (elem) {
  184. console.log('addssrc', new Date().getTime());
  185. console.log('ice', this.iceConnectionState);
  186. var sdp = new SDP(this.remoteDescription.sdp);
  187. var self = this;
  188. $(elem).each(function (idx, content) {
  189. var name = $(content).attr('name');
  190. var lines = '';
  191. tmp = $(content).find('>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  192. tmp.each(function () {
  193. var ssrc = $(this).attr('ssrc');
  194. $(this).find('>parameter').each(function () {
  195. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  196. if ($(this).attr('value') && $(this).attr('value').length)
  197. lines += ':' + $(this).attr('value');
  198. lines += '\r\n';
  199. });
  200. });
  201. sdp.media.forEach(function(media, idx) {
  202. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  203. return;
  204. sdp.media[idx] += lines;
  205. self.enqueueAddSsrc(idx, lines);
  206. });
  207. sdp.raw = sdp.session + sdp.media.join('');
  208. });
  209. this.modifySources();
  210. };
  211. TraceablePeerConnection.prototype.enqueueRemoveSsrc = function(channel, ssrcLines) {
  212. if (!this.removessrc[channel]){
  213. this.removessrc[channel] = '';
  214. }
  215. this.removessrc[channel] += ssrcLines;
  216. }
  217. TraceablePeerConnection.prototype.removeSource = function (elem) {
  218. console.log('removessrc', new Date().getTime());
  219. console.log('ice', this.iceConnectionState);
  220. var sdp = new SDP(this.remoteDescription.sdp);
  221. var self = this;
  222. $(elem).each(function (idx, content) {
  223. var name = $(content).attr('name');
  224. var lines = '';
  225. tmp = $(content).find('>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  226. tmp.each(function () {
  227. var ssrc = $(this).attr('ssrc');
  228. $(this).find('>parameter').each(function () {
  229. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  230. if ($(this).attr('value') && $(this).attr('value').length)
  231. lines += ':' + $(this).attr('value');
  232. lines += '\r\n';
  233. });
  234. });
  235. sdp.media.forEach(function(media, idx) {
  236. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  237. return;
  238. sdp.media[idx] += lines;
  239. self.enqueueRemoveSsrc(idx, lines);
  240. });
  241. sdp.raw = sdp.session + sdp.media.join('');
  242. });
  243. this.modifySources();
  244. };
  245. TraceablePeerConnection.prototype.modifySources = function(successCallback) {
  246. var self = this;
  247. if (this.signalingState == 'closed') return;
  248. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null)){
  249. if(successCallback){
  250. successCallback();
  251. }
  252. return;
  253. }
  254. // FIXME: this is a big hack
  255. // https://code.google.com/p/webrtc/issues/detail?id=2688
  256. if (!(this.signalingState == 'stable' && this.iceConnectionState == 'connected')) {
  257. console.warn('modifySources not yet', this.signalingState, this.iceConnectionState);
  258. this.wait = true;
  259. window.setTimeout(function() { self.modifySources(); }, 250);
  260. return;
  261. }
  262. if (this.wait) {
  263. window.setTimeout(function() { self.modifySources(); }, 2500);
  264. this.wait = false;
  265. return;
  266. }
  267. var sdp = new SDP(this.remoteDescription.sdp);
  268. // add sources
  269. this.addssrc.forEach(function(lines, idx) {
  270. sdp.media[idx] += lines;
  271. });
  272. this.addssrc = [];
  273. // remove sources
  274. this.removessrc.forEach(function(lines, idx) {
  275. lines = lines.split('\r\n');
  276. lines.pop(); // remove empty last element;
  277. lines.forEach(function(line) {
  278. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  279. });
  280. });
  281. this.removessrc = [];
  282. sdp.raw = sdp.session + sdp.media.join('');
  283. this.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  284. function() {
  285. self.createAnswer(
  286. function(modifiedAnswer) {
  287. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  288. if (self.pendingop !== null) {
  289. var sdp = new SDP(modifiedAnswer.sdp);
  290. if (sdp.media.length > 1) {
  291. switch(self.pendingop) {
  292. case 'mute':
  293. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  294. break;
  295. case 'unmute':
  296. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  297. break;
  298. }
  299. sdp.raw = sdp.session + sdp.media.join('');
  300. modifiedAnswer.sdp = sdp.raw;
  301. }
  302. self.pendingop = null;
  303. }
  304. self.setLocalDescription(modifiedAnswer,
  305. function() {
  306. //console.log('modified setLocalDescription ok');
  307. if(successCallback){
  308. successCallback();
  309. }
  310. },
  311. function(error) {
  312. console.error('modified setLocalDescription failed', error);
  313. }
  314. );
  315. },
  316. function(error) {
  317. console.error('modified answer failed', error);
  318. }
  319. );
  320. },
  321. function(error) {
  322. console.error('modify failed', error);
  323. }
  324. );
  325. };
  326. TraceablePeerConnection.prototype.close = function () {
  327. this.trace('stop');
  328. if (this.statsinterval !== null) {
  329. window.clearInterval(this.statsinterval);
  330. this.statsinterval = null;
  331. }
  332. this.peerconnection.close();
  333. };
  334. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  335. var self = this;
  336. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  337. this.peerconnection.createOffer(
  338. function (offer) {
  339. self.trace('createOfferOnSuccess', dumpSDP(offer));
  340. successCallback(offer);
  341. },
  342. function(err) {
  343. self.trace('createOfferOnFailure', err);
  344. failureCallback(err);
  345. },
  346. constraints
  347. );
  348. };
  349. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  350. var self = this;
  351. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  352. this.peerconnection.createAnswer(
  353. function (answer) {
  354. self.trace('createAnswerOnSuccess', dumpSDP(answer));
  355. successCallback(answer);
  356. },
  357. function(err) {
  358. self.trace('createAnswerOnFailure', err);
  359. failureCallback(err);
  360. },
  361. constraints
  362. );
  363. };
  364. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  365. var self = this;
  366. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  367. this.peerconnection.addIceCandidate(candidate);
  368. /* maybe later
  369. this.peerconnection.addIceCandidate(candidate,
  370. function () {
  371. self.trace('addIceCandidateOnSuccess');
  372. successCallback();
  373. },
  374. function (err) {
  375. self.trace('addIceCandidateOnFailure', err);
  376. failureCallback(err);
  377. }
  378. );
  379. */
  380. };
  381. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  382. if (navigator.mozGetUserMedia) {
  383. // ignore for now...
  384. } else {
  385. this.peerconnection.getStats(callback);
  386. }
  387. };
  388. // mozilla chrome compat layer -- very similar to adapter.js
  389. function setupRTC() {
  390. var RTC = null;
  391. if (navigator.mozGetUserMedia) {
  392. console.log('This appears to be Firefox');
  393. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  394. if (version >= 22) {
  395. RTC = {
  396. peerconnection: mozRTCPeerConnection,
  397. browser: 'firefox',
  398. getUserMedia: navigator.mozGetUserMedia.bind(navigator),
  399. attachMediaStream: function (element, stream) {
  400. element[0].mozSrcObject = stream;
  401. element[0].play();
  402. },
  403. pc_constraints: {}
  404. };
  405. if (!MediaStream.prototype.getVideoTracks)
  406. MediaStream.prototype.getVideoTracks = function () { return []; };
  407. if (!MediaStream.prototype.getAudioTracks)
  408. MediaStream.prototype.getAudioTracks = function () { return []; };
  409. RTCSessionDescription = mozRTCSessionDescription;
  410. RTCIceCandidate = mozRTCIceCandidate;
  411. }
  412. } else if (navigator.webkitGetUserMedia) {
  413. console.log('This appears to be Chrome');
  414. RTC = {
  415. peerconnection: webkitRTCPeerConnection,
  416. browser: 'chrome',
  417. getUserMedia: navigator.webkitGetUserMedia.bind(navigator),
  418. attachMediaStream: function (element, stream) {
  419. element.attr('src', webkitURL.createObjectURL(stream));
  420. },
  421. // DTLS should now be enabled by default but..
  422. pc_constraints: {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]}
  423. };
  424. if (navigator.userAgent.indexOf('Android') != -1) {
  425. RTC.pc_constraints = {}; // disable DTLS on Android
  426. }
  427. if (!webkitMediaStream.prototype.getVideoTracks) {
  428. webkitMediaStream.prototype.getVideoTracks = function () {
  429. return this.videoTracks;
  430. };
  431. }
  432. if (!webkitMediaStream.prototype.getAudioTracks) {
  433. webkitMediaStream.prototype.getAudioTracks = function () {
  434. return this.audioTracks;
  435. };
  436. }
  437. }
  438. if (RTC === null) {
  439. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  440. }
  441. return RTC;
  442. }
  443. function getUserMediaWithConstraints(um, resolution, bandwidth, fps) {
  444. var constraints = {audio: false, video: false};
  445. if (um.indexOf('video') >= 0) {
  446. constraints.video = {mandatory: {}};// same behaviour as true
  447. }
  448. if (um.indexOf('audio') >= 0) {
  449. constraints.audio = {};// same behaviour as true
  450. }
  451. if (um.indexOf('screen') >= 0) {
  452. constraints.video = {
  453. "mandatory": {
  454. "chromeMediaSource": "screen"
  455. }
  456. };
  457. }
  458. if (resolution && !constraints.video) {
  459. constraints.video = {mandatory: {}};// same behaviour as true
  460. }
  461. // see https://code.google.com/p/chromium/issues/detail?id=143631#c9 for list of supported resolutions
  462. switch (resolution) {
  463. // 16:9 first
  464. case '1080':
  465. case 'fullhd':
  466. constraints.video.mandatory.minWidth = 1920;
  467. constraints.video.mandatory.minHeight = 1080;
  468. constraints.video.mandatory.minAspectRatio = 1.77;
  469. break;
  470. case '720':
  471. case 'hd':
  472. constraints.video.mandatory.minWidth = 1280;
  473. constraints.video.mandatory.minHeight = 720;
  474. constraints.video.mandatory.minAspectRatio = 1.77;
  475. break;
  476. case '360':
  477. constraints.video.mandatory.minWidth = 640;
  478. constraints.video.mandatory.minHeight = 360;
  479. constraints.video.mandatory.minAspectRatio = 1.77;
  480. break;
  481. case '180':
  482. constraints.video.mandatory.minWidth = 320;
  483. constraints.video.mandatory.minHeight = 180;
  484. constraints.video.mandatory.minAspectRatio = 1.77;
  485. break;
  486. // 4:3
  487. case '960':
  488. constraints.video.mandatory.minWidth = 960;
  489. constraints.video.mandatory.minHeight = 720;
  490. break;
  491. case '640':
  492. case 'vga':
  493. constraints.video.mandatory.minWidth = 640;
  494. constraints.video.mandatory.minHeight = 480;
  495. break;
  496. case '320':
  497. constraints.video.mandatory.minWidth = 320;
  498. constraints.video.mandatory.minHeight = 240;
  499. break;
  500. default:
  501. if (navigator.userAgent.indexOf('Android') != -1) {
  502. constraints.video.mandatory.minWidth = 320;
  503. constraints.video.mandatory.minHeight = 240;
  504. constraints.video.mandatory.maxFrameRate = 15;
  505. }
  506. break;
  507. }
  508. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  509. if (!constraints.video) constraints.video = {mandatory: {}};//same behaviour as true
  510. constraints.video.optional = [{bandwidth: bandwidth}];
  511. }
  512. if (fps) { // for some cameras it might be necessary to request 30fps
  513. // so they choose 30fps mjpg over 10fps yuy2
  514. if (!constraints.video) constraints.video = {mandatory: {}};// same behaviour as tru;
  515. constraints.video.mandatory.minFrameRate = fps;
  516. }
  517. try {
  518. RTC.getUserMedia(constraints,
  519. function (stream) {
  520. console.log('onUserMediaSuccess');
  521. $(document).trigger('mediaready.jingle', [stream]);
  522. },
  523. function (error) {
  524. console.warn('Failed to get access to local media. Error ', error);
  525. $(document).trigger('mediafailure.jingle');
  526. });
  527. } catch (e) {
  528. console.error('GUM failed: ', e);
  529. $(document).trigger('mediafailure.jingle');
  530. }
  531. }