選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

strophe.jingle.adapter.js 22KB

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