Advertisement
Guest User

Untitled

a guest
Oct 13th, 2016
337
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 84.00 KB | None | 0 0
  1. /*
  2. The MIT License (MIT)
  3.  
  4. Copyright (c) 2016 Meetecho
  5.  
  6. Permission is hereby granted, free of charge, to any person obtaining
  7. a copy of this software and associated documentation files (the "Software"),
  8. to deal in the Software without restriction, including without limitation
  9. the rights to use, copy, modify, merge, publish, distribute, sublicense,
  10. and/or sell copies of the Software, and to permit persons to whom the
  11. Software is furnished to do so, subject to the following conditions:
  12.  
  13. The above copyright notice and this permission notice shall be included
  14. in all copies or substantial portions of the Software.
  15.  
  16. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  17. OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  19. THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  20. OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  21. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  22. OTHER DEALINGS IN THE SOFTWARE.
  23. */
  24.  
  25. // List of sessions
  26. Janus.sessions = {};
  27.  
  28. // Screensharing Chrome Extension ID
  29. Janus.extensionId = "hapfgfdkleiggjjpfpenajgdnfckjpaj";
  30. Janus.isExtensionEnabled = function() {
  31. if(window.navigator.userAgent.match('Chrome')) {
  32. var chromever = parseInt(window.navigator.userAgent.match(/Chrome\/(.*) /)[1], 10);
  33. var maxver = 33;
  34. if(window.navigator.userAgent.match('Linux'))
  35. maxver = 35; // "known" crash in chrome 34 and 35 on linux
  36. if(chromever >= 26 && chromever <= maxver) {
  37. // Older versions of Chrome don't support this extension-based approach, so lie
  38. return true;
  39. }
  40. return ($('#janus-extension-installed').length > 0);
  41. } else {
  42. // Firefox of others, no need for the extension (but this doesn't mean it will work)
  43. return true;
  44. }
  45. };
  46.  
  47. Janus.noop = function() {};
  48.  
  49. // Initialization
  50. Janus.init = function(options) {
  51. options = options || {};
  52. options.callback = (typeof options.callback == "function") ? options.callback : Janus.noop;
  53. if(Janus.initDone === true) {
  54. // Already initialized
  55. options.callback();
  56. } else {
  57. if(typeof console == "undefined" || typeof console.log == "undefined")
  58. console = { log: function() {} };
  59. // Console logging (all debugging disabled by default)
  60. Janus.trace = Janus.noop;
  61. Janus.debug = Janus.noop;
  62. Janus.log = Janus.noop;
  63. Janus.warn = Janus.noop;
  64. Janus.error = Janus.noop;
  65. if(options.debug === true || options.debug === "all") {
  66. // Enable all debugging levels
  67. Janus.trace = console.trace.bind(console);
  68. Janus.debug = console.debug.bind(console);
  69. Janus.log = console.log.bind(console);
  70. Janus.warn = console.warn.bind(console);
  71. Janus.error = console.error.bind(console);
  72. } else if(Array.isArray(options.debug)) {
  73. for(var i in options.debug) {
  74. var d = options.debug[i];
  75. switch(d) {
  76. case "trace":
  77. Janus.trace = console.trace.bind(console);
  78. break;
  79. case "debug":
  80. Janus.debug = console.debug.bind(console);
  81. break;
  82. case "log":
  83. Janus.log = console.log.bind(console);
  84. break;
  85. case "warn":
  86. Janus.warn = console.warn.bind(console);
  87. break;
  88. case "error":
  89. Janus.error = console.error.bind(console);
  90. break;
  91. default:
  92. console.error("Unknown debugging option '" + d + "' (supported: 'trace', 'debug', 'log', warn', 'error')");
  93. break;
  94. }
  95. }
  96. }
  97. Janus.log("Initializing library");
  98. // Helper method to enumerate devices
  99. Janus.listDevices = function(callback) {
  100. callback = (typeof callback == "function") ? callback : Janus.noop;
  101. if(navigator.mediaDevices) {
  102. getUserMedia({ audio: true, video: true }, function(stream) {
  103. navigator.mediaDevices.enumerateDevices().then(function(devices) {
  104. Janus.debug(devices);
  105. callback(devices);
  106. // Get rid of the now useless stream
  107. try {
  108. stream.stop();
  109. } catch(e) {}
  110. try {
  111. var tracks = stream.getTracks();
  112. for(var i in tracks) {
  113. var mst = tracks[i];
  114. if(mst !== null && mst !== undefined)
  115. mst.stop();
  116. }
  117. } catch(e) {}
  118. });
  119. }, function(err) {
  120. Janus.error(err);
  121. callback([]);
  122. });
  123. } else {
  124. Janus.warn("navigator.mediaDevices unavailable");
  125. callback([]);
  126. }
  127. }
  128. // Detect tab close
  129. window.onbeforeunload = function() {
  130. Janus.log("Closing window");
  131. for(var s in Janus.sessions) {
  132. if(Janus.sessions[s] !== null && Janus.sessions[s] !== undefined &&
  133. Janus.sessions[s].destroyOnUnload) {
  134. Janus.log("Destroying session " + s);
  135. Janus.sessions[s].destroy();
  136. }
  137. }
  138. }
  139. function addJsList(srcArray) {
  140. if (!srcArray || !Array.isArray(srcArray) || srcArray.length == 0) {
  141. options.callback();
  142. }
  143. var count = 0;
  144. addJs(srcArray[count],next);
  145.  
  146. function next() {
  147. count++;
  148. if (count<srcArray.length) {
  149. addJs(srcArray[count],next);
  150. }
  151. else {
  152. options.callback();
  153. }
  154. }
  155. }
  156. function addJs(src,done) {
  157. if(src === 'jquery.min.js') {
  158. if(window.jQuery) {
  159. // Already loaded
  160. done();
  161. return;
  162. }
  163. }
  164. if(src === 'adapter.js') {
  165. if(window.getUserMedia && window.RTCPeerConnection) {
  166. // Already loaded
  167. done();
  168. return;
  169. }
  170. }
  171. var oHead = document.getElementsByTagName('head').item(0);
  172. var oScript = document.createElement("script");
  173. oScript.type = "text/javascript";
  174. oScript.src = src;
  175. oScript.onload = function() {
  176. Janus.log("Library " + src + " loaded");
  177. done();
  178. }
  179. oHead.appendChild(oScript);
  180. }
  181. Janus.initDone = true;
  182. addJsList(["adapter.js", "jquery.min.js"]);
  183. }
  184. };
  185.  
  186. // Helper method to check whether WebRTC is supported by this browser
  187. Janus.isWebrtcSupported = function() {
  188. return window.RTCPeerConnection && window.getUserMedia;
  189. };
  190.  
  191. function Janus(gatewayCallbacks) {
  192. if(Janus.initDone === undefined) {
  193. gatewayCallbacks.error("Library not initialized");
  194. return {};
  195. }
  196. if(!Janus.isWebrtcSupported()) {
  197. gatewayCallbacks.error("WebRTC not supported by this browser");
  198. return {};
  199. }
  200. Janus.log("Library initialized: " + Janus.initDone);
  201. gatewayCallbacks = gatewayCallbacks || {};
  202. gatewayCallbacks.success = (typeof gatewayCallbacks.success == "function") ? gatewayCallbacks.success : jQuery.noop;
  203. gatewayCallbacks.error = (typeof gatewayCallbacks.error == "function") ? gatewayCallbacks.error : jQuery.noop;
  204. gatewayCallbacks.destroyed = (typeof gatewayCallbacks.destroyed == "function") ? gatewayCallbacks.destroyed : jQuery.noop;
  205. if(gatewayCallbacks.server === null || gatewayCallbacks.server === undefined) {
  206. gatewayCallbacks.error("Invalid gateway url");
  207. return {};
  208. }
  209. var websockets = false;
  210. var ws = null;
  211. var wsHandlers = {};
  212. var wsKeepaliveTimeoutId = null;
  213.  
  214. var servers = null, serversIndex = 0;
  215. var server = gatewayCallbacks.server;
  216. if($.isArray(server)) {
  217. Janus.log("Multiple servers provided (" + server.length + "), will use the first that works");
  218. server = null;
  219. servers = gatewayCallbacks.server;
  220. Janus.debug(servers);
  221. } else {
  222. if(server.indexOf("ws") === 0) {
  223. websockets = true;
  224. Janus.log("Using WebSockets to contact Janus: " + server);
  225. } else {
  226. websockets = false;
  227. Janus.log("Using REST API to contact Janus: " + server);
  228. }
  229. }
  230. var iceServers = gatewayCallbacks.iceServers;
  231. if(iceServers === undefined || iceServers === null)
  232. iceServers = [{"url": "stun:stun.l.google.com:19302"}];
  233. // Whether IPv6 candidates should be gathered
  234. var ipv6Support = gatewayCallbacks.ipv6;
  235. if(ipv6Support === undefined || ipv6Support === null)
  236. ipv6Support = false;
  237. // Optional max events
  238. var maxev = null;
  239. if(gatewayCallbacks.max_poll_events !== undefined && gatewayCallbacks.max_poll_events !== null)
  240. maxev = gatewayCallbacks.max_poll_events;
  241. if(maxev < 1)
  242. maxev = 1;
  243. // Token to use (only if the token based authentication mechanism is enabled)
  244. var token = null;
  245. if(gatewayCallbacks.token !== undefined && gatewayCallbacks.token !== null)
  246. token = gatewayCallbacks.token;
  247. // API secret to use (only if the shared API secret is enabled)
  248. var apisecret = null;
  249. if(gatewayCallbacks.apisecret !== undefined && gatewayCallbacks.apisecret !== null)
  250. apisecret = gatewayCallbacks.apisecret;
  251. // Whether we should destroy this session when onbeforeunload is called
  252. this.destroyOnUnload = true;
  253. if(gatewayCallbacks.destroyOnUnload !== undefined && gatewayCallbacks.destroyOnUnload !== null)
  254. this.destroyOnUnload = (gatewayCallbacks.destroyOnUnload === true);
  255.  
  256. var connected = false;
  257. var sessionId = null;
  258. var pluginHandles = {};
  259. var that = this;
  260. var retries = 0;
  261. var transactions = {};
  262. createSession(gatewayCallbacks);
  263.  
  264. // Public methods
  265. this.getServer = function() { return server; };
  266. this.isConnected = function() { return connected; };
  267. this.getSessionId = function() { return sessionId; };
  268. this.destroy = function(callbacks) { destroySession(callbacks); };
  269. this.attach = function(callbacks) { createHandle(callbacks); };
  270.  
  271. // Private method to create random identifiers (e.g., transaction)
  272. function randomString(len) {
  273. var charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  274. var randomString = '';
  275. for (var i = 0; i < len; i++) {
  276. var randomPoz = Math.floor(Math.random() * charSet.length);
  277. randomString += charSet.substring(randomPoz,randomPoz+1);
  278. }
  279. return randomString;
  280. }
  281.  
  282. function eventHandler() {
  283. if(sessionId == null)
  284. return;
  285. Janus.debug('Long poll...');
  286. if(!connected) {
  287. Janus.warn("Is the gateway down? (connected=false)");
  288. return;
  289. }
  290. var longpoll = server + "/" + sessionId + "?rid=" + new Date().getTime();
  291. if(maxev !== undefined && maxev !== null)
  292. longpoll = longpoll + "&maxev=" + maxev;
  293. if(token !== null && token !== undefined)
  294. longpoll = longpoll + "&token=" + token;
  295. if(apisecret !== null && apisecret !== undefined)
  296. longpoll = longpoll + "&apisecret=" + apisecret;
  297. $.ajax({
  298. type: 'GET',
  299. url: longpoll,
  300. cache: false,
  301. timeout: 60000, // FIXME
  302. success: handleEvent,
  303. error: function(XMLHttpRequest, textStatus, errorThrown) {
  304. Janus.error(textStatus + ": " + errorThrown);
  305. //~ clearTimeout(timeoutTimer);
  306. retries++;
  307. if(retries > 3) {
  308. // Did we just lose the gateway? :-(
  309. connected = false;
  310. gatewayCallbacks.error("Lost connection to the gateway (is it down?)");
  311. return;
  312. }
  313. eventHandler();
  314. },
  315. dataType: "json"
  316. });
  317. }
  318.  
  319. // Private event handler: this will trigger plugin callbacks, if set
  320. function handleEvent(json) {
  321. retries = 0;
  322. if(!websockets && sessionId !== undefined && sessionId !== null)
  323. setTimeout(eventHandler, 200);
  324. Janus.debug("Got event on session " + sessionId);
  325. Janus.debug(json);
  326. if(!websockets && $.isArray(json)) {
  327. // We got an array: it means we passed a maxev > 1, iterate on all objects
  328. for(var i=0; i<json.length; i++) {
  329. handleEvent(json[i]);
  330. }
  331. return;
  332. }
  333. if(json["janus"] === "keepalive") {
  334. // Nothing happened
  335. return;
  336. } else if(json["janus"] === "ack") {
  337. // Just an ack, we can probably ignore
  338. var transaction = json["transaction"];
  339. if(transaction !== null && transaction !== undefined) {
  340. var reportSuccess = transactions[transaction];
  341. if(reportSuccess !== null && reportSuccess !== undefined) {
  342. reportSuccess(json);
  343. }
  344. delete transactions[transaction];
  345. }
  346. return;
  347. } else if(json["janus"] === "success") {
  348. // Success!
  349. var transaction = json["transaction"];
  350. if(transaction !== null && transaction !== undefined) {
  351. var reportSuccess = transactions[transaction];
  352. if(reportSuccess !== null && reportSuccess !== undefined) {
  353. reportSuccess(json);
  354. }
  355. delete transactions[transaction];
  356. }
  357. return;
  358. } else if(json["janus"] === "webrtcup") {
  359. // The PeerConnection with the gateway is up! Notify this
  360. var sender = json["sender"];
  361. if(sender === undefined || sender === null) {
  362. Janus.warn("Missing sender...");
  363. return;
  364. }
  365. var pluginHandle = pluginHandles[sender];
  366. if(pluginHandle === undefined || pluginHandle === null) {
  367. Janus.warn("This handle is not attached to this session");
  368. return;
  369. }
  370. pluginHandle.webrtcState(true);
  371. return;
  372. } else if(json["janus"] === "hangup") {
  373. // A plugin asked the core to hangup a PeerConnection on one of our handles
  374. var sender = json["sender"];
  375. if(sender === undefined || sender === null) {
  376. Janus.warn("Missing sender...");
  377. return;
  378. }
  379. var pluginHandle = pluginHandles[sender];
  380. if(pluginHandle === undefined || pluginHandle === null) {
  381. Janus.warn("This handle is not attached to this session");
  382. return;
  383. }
  384. pluginHandle.webrtcState(false);
  385. pluginHandle.hangup();
  386. } else if(json["janus"] === "detached") {
  387. // A plugin asked the core to detach one of our handles
  388. var sender = json["sender"];
  389. if(sender === undefined || sender === null) {
  390. Janus.warn("Missing sender...");
  391. return;
  392. }
  393. var pluginHandle = pluginHandles[sender];
  394. if(pluginHandle === undefined || pluginHandle === null) {
  395. // Don't warn here because destroyHandle causes this situation.
  396. return;
  397. }
  398. pluginHandle.ondetached();
  399. pluginHandle.detach();
  400. } else if(json["janus"] === "media") {
  401. // Media started/stopped flowing
  402. var sender = json["sender"];
  403. if(sender === undefined || sender === null) {
  404. Janus.warn("Missing sender...");
  405. return;
  406. }
  407. var pluginHandle = pluginHandles[sender];
  408. if(pluginHandle === undefined || pluginHandle === null) {
  409. Janus.warn("This handle is not attached to this session");
  410. return;
  411. }
  412. pluginHandle.mediaState(json["type"], json["receiving"]);
  413. } else if(json["janus"] === "error") {
  414. // Oops, something wrong happened
  415. Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
  416. var transaction = json["transaction"];
  417. if(transaction !== null && transaction !== undefined) {
  418. var reportSuccess = transactions[transaction];
  419. if(reportSuccess !== null && reportSuccess !== undefined) {
  420. reportSuccess(json);
  421. }
  422. delete transactions[transaction];
  423. }
  424. return;
  425. } else if(json["janus"] === "event") {
  426. var sender = json["sender"];
  427. if(sender === undefined || sender === null) {
  428. Janus.warn("Missing sender...");
  429. return;
  430. }
  431. var plugindata = json["plugindata"];
  432. if(plugindata === undefined || plugindata === null) {
  433. Janus.warn("Missing plugindata...");
  434. return;
  435. }
  436. Janus.debug(" -- Event is coming from " + sender + " (" + plugindata["plugin"] + ")");
  437. var data = plugindata["data"];
  438. Janus.debug(data);
  439. var pluginHandle = pluginHandles[sender];
  440. if(pluginHandle === undefined || pluginHandle === null) {
  441. Janus.warn("This handle is not attached to this session");
  442. return;
  443. }
  444. var jsep = json["jsep"];
  445. if(jsep !== undefined && jsep !== null) {
  446. Janus.debug("Handling SDP as well...");
  447. Janus.debug(jsep);
  448. }
  449. var callback = pluginHandle.onmessage;
  450. if(callback !== null && callback !== undefined) {
  451. Janus.debug("Notifying application...");
  452. // Send to callback specified when attaching plugin handle
  453. callback(data, jsep);
  454. } else {
  455. // Send to generic callback (?)
  456. Janus.debug("No provided notification callback");
  457. }
  458. } else {
  459. Janus.warn("Unknown message '" + json["janus"] + "'");
  460. }
  461. }
  462.  
  463. // Private helper to send keep-alive messages on WebSockets
  464. function keepAlive() {
  465. if(server === null || !websockets || !connected)
  466. return;
  467. wsKeepaliveTimeoutId = setTimeout(keepAlive, 30000);
  468. var request = { "janus": "keepalive", "session_id": sessionId, "transaction": randomString(12) };
  469. if(token !== null && token !== undefined)
  470. request["token"] = token;
  471. if(apisecret !== null && apisecret !== undefined)
  472. request["apisecret"] = apisecret;
  473. ws.send(JSON.stringify(request));
  474. }
  475.  
  476. // Private method to create a session
  477. function createSession(callbacks) {
  478. var transaction = randomString(12);
  479. var request = { "janus": "create", "transaction": transaction };
  480. if(token !== null && token !== undefined)
  481. request["token"] = token;
  482. if(apisecret !== null && apisecret !== undefined)
  483. request["apisecret"] = apisecret;
  484. if(server === null && $.isArray(servers)) {
  485. // We still need to find a working server from the list we were given
  486. server = servers[serversIndex];
  487. if(server.indexOf("ws") === 0) {
  488. websockets = true;
  489. Janus.log("Server #" + (serversIndex+1) + ": trying WebSockets to contact Janus (" + server + ")");
  490. } else {
  491. websockets = false;
  492. Janus.log("Server #" + (serversIndex+1) + ": trying REST API to contact Janus (" + server + ")");
  493. }
  494. }
  495. if(websockets) {
  496. ws = new WebSocket(server, 'janus-protocol');
  497. wsHandlers = {
  498. 'error': function() {
  499. Janus.error("Error connecting to the Janus WebSockets server... " + server);
  500. if ($.isArray(servers)) {
  501. serversIndex++;
  502. if (serversIndex == servers.length) {
  503. // We tried all the servers the user gave us and they all failed
  504. callbacks.error("Error connecting to any of the provided Janus servers: Is the gateway down?");
  505. return;
  506. }
  507. // Let's try the next server
  508. server = null;
  509. setTimeout(function() {
  510. createSession(callbacks);
  511. }, 200);
  512. return;
  513. }
  514. callbacks.error("Error connecting to the Janus WebSockets server: Is the gateway down?");
  515. },
  516.  
  517. 'open': function() {
  518. // We need to be notified about the success
  519. transactions[transaction] = function(json) {
  520. Janus.debug(json);
  521. if (json["janus"] !== "success") {
  522. Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
  523. callbacks.error(json["error"].reason);
  524. return;
  525. }
  526. wsKeepaliveTimeoutId = setTimeout(keepAlive, 30000);
  527. connected = true;
  528. sessionId = json.data["id"];
  529. Janus.log("Created session: " + sessionId);
  530. Janus.sessions[sessionId] = that;
  531. callbacks.success();
  532. };
  533. ws.send(JSON.stringify(request));
  534. },
  535.  
  536. 'message': function(event) {
  537. handleEvent(JSON.parse(event.data));
  538. },
  539.  
  540. 'close': function() {
  541. if (server === null || !connected) {
  542. return;
  543. }
  544. connected = false;
  545. // FIXME What if this is called when the page is closed?
  546. gatewayCallbacks.error("Lost connection to the gateway (is it down?)");
  547. }
  548. };
  549.  
  550. for(var eventName in wsHandlers) {
  551. ws.addEventListener(eventName, wsHandlers[eventName]);
  552. }
  553.  
  554. return;
  555. }
  556. $.ajax({
  557. type: 'POST',
  558. url: server,
  559. cache: false,
  560. contentType: "application/json",
  561. data: JSON.stringify(request),
  562. success: function(json) {
  563. Janus.debug(json);
  564. if(json["janus"] !== "success") {
  565. Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
  566. callbacks.error(json["error"].reason);
  567. return;
  568. }
  569. connected = true;
  570. sessionId = json.data["id"];
  571. Janus.log("Created session: " + sessionId);
  572. Janus.sessions[sessionId] = that;
  573. eventHandler();
  574. callbacks.success();
  575. },
  576. error: function(XMLHttpRequest, textStatus, errorThrown) {
  577. Janus.error(textStatus + ": " + errorThrown); // FIXME
  578. if($.isArray(servers)) {
  579. serversIndex++;
  580. if(serversIndex == servers.length) {
  581. // We tried all the servers the user gave us and they all failed
  582. callbacks.error("Error connecting to any of the provided Janus servers: Is the gateway down?");
  583. return;
  584. }
  585. // Let's try the next server
  586. server = null;
  587. setTimeout(function() { createSession(callbacks); }, 200);
  588. return;
  589. }
  590. if(errorThrown === "")
  591. callbacks.error(textStatus + ": Is the gateway down?");
  592. else
  593. callbacks.error(textStatus + ": " + errorThrown);
  594. },
  595. dataType: "json"
  596. });
  597. }
  598.  
  599. // Private method to destroy a session
  600. function destroySession(callbacks, syncRequest) {
  601. syncRequest = (syncRequest === true);
  602. Janus.log("Destroying session " + sessionId + " (sync=" + syncRequest + ")");
  603. callbacks = callbacks || {};
  604. // FIXME This method triggers a success even when we fail
  605. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : jQuery.noop;
  606. if(!connected) {
  607. Janus.warn("Is the gateway down? (connected=false)");
  608. callbacks.success();
  609. return;
  610. }
  611. if(sessionId === undefined || sessionId === null) {
  612. Janus.warn("No session to destroy");
  613. callbacks.success();
  614. gatewayCallbacks.destroyed();
  615. return;
  616. }
  617. delete Janus.sessions[sessionId];
  618. // Destroy all handles first
  619. for(var ph in pluginHandles) {
  620. var phv = pluginHandles[ph];
  621. Janus.log("Destroying handle " + phv.id + " (" + phv.plugin + ")");
  622. destroyHandle(phv.id, null, syncRequest);
  623. }
  624. // Ok, go on
  625. var request = { "janus": "destroy", "transaction": randomString(12) };
  626. if(token !== null && token !== undefined)
  627. request["token"] = token;
  628. if(apisecret !== null && apisecret !== undefined)
  629. request["apisecret"] = apisecret;
  630. if(websockets) {
  631. request["session_id"] = sessionId;
  632.  
  633. var unbindWebSocket = function() {
  634. for(var eventName in wsHandlers) {
  635. ws.removeEventListener(eventName, wsHandlers[eventName]);
  636. }
  637. ws.removeEventListener('message', onUnbindMessage);
  638. ws.removeEventListener('error', onUnbindError);
  639. if(wsKeepaliveTimeoutId) {
  640. clearTimeout(wsKeepaliveTimeoutId);
  641. }
  642. };
  643.  
  644. var onUnbindMessage = function(event){
  645. var data = JSON.parse(event.data);
  646. if(data.session_id == request.session_id && data.transaction == request.transaction) {
  647. unbindWebSocket();
  648. callbacks.success();
  649. gatewayCallbacks.destroyed();
  650. }
  651. };
  652. var onUnbindError = function(event) {
  653. unbindWebSocket();
  654. callbacks.error("Failed to destroy the gateway: Is the gateway down?");
  655. gatewayCallbacks.destroyed();
  656. };
  657.  
  658. ws.addEventListener('message', onUnbindMessage);
  659. ws.addEventListener('error', onUnbindError);
  660.  
  661. ws.send(JSON.stringify(request));
  662. return;
  663. }
  664. $.ajax({
  665. type: 'POST',
  666. url: server + "/" + sessionId,
  667. async: syncRequest, // Sometimes we need false here, or destroying in onbeforeunload won't work
  668. cache: false,
  669. contentType: "application/json",
  670. data: JSON.stringify(request),
  671. success: function(json) {
  672. Janus.log("Destroyed session:");
  673. Janus.debug(json);
  674. sessionId = null;
  675. connected = false;
  676. if(json["janus"] !== "success") {
  677. Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
  678. }
  679. callbacks.success();
  680. gatewayCallbacks.destroyed();
  681. },
  682. error: function(XMLHttpRequest, textStatus, errorThrown) {
  683. Janus.error(textStatus + ": " + errorThrown); // FIXME
  684. // Reset everything anyway
  685. sessionId = null;
  686. connected = false;
  687. callbacks.success();
  688. gatewayCallbacks.destroyed();
  689. },
  690. dataType: "json"
  691. });
  692. }
  693.  
  694. // Private method to create a plugin handle
  695. function createHandle(callbacks) {
  696. callbacks = callbacks || {};
  697. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : jQuery.noop;
  698. callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : jQuery.noop;
  699. callbacks.consentDialog = (typeof callbacks.consentDialog == "function") ? callbacks.consentDialog : jQuery.noop;
  700. callbacks.mediaState = (typeof callbacks.mediaState == "function") ? callbacks.mediaState : jQuery.noop;
  701. callbacks.webrtcState = (typeof callbacks.webrtcState == "function") ? callbacks.webrtcState : jQuery.noop;
  702. callbacks.onmessage = (typeof callbacks.onmessage == "function") ? callbacks.onmessage : jQuery.noop;
  703. callbacks.onlocalstream = (typeof callbacks.onlocalstream == "function") ? callbacks.onlocalstream : jQuery.noop;
  704. callbacks.onremotestream = (typeof callbacks.onremotestream == "function") ? callbacks.onremotestream : jQuery.noop;
  705. callbacks.ondata = (typeof callbacks.ondata == "function") ? callbacks.ondata : jQuery.noop;
  706. callbacks.ondataopen = (typeof callbacks.ondataopen == "function") ? callbacks.ondataopen : jQuery.noop;
  707. callbacks.oncleanup = (typeof callbacks.oncleanup == "function") ? callbacks.oncleanup : jQuery.noop;
  708. callbacks.ondetached = (typeof callbacks.ondetached == "function") ? callbacks.ondetached : jQuery.noop;
  709. if(!connected) {
  710. Janus.warn("Is the gateway down? (connected=false)");
  711. callbacks.error("Is the gateway down? (connected=false)");
  712. return;
  713. }
  714. var plugin = callbacks.plugin;
  715. if(plugin === undefined || plugin === null) {
  716. Janus.error("Invalid plugin");
  717. callbacks.error("Invalid plugin");
  718. return;
  719. }
  720. var transaction = randomString(12);
  721. var request = { "janus": "attach", "plugin": plugin, "transaction": transaction };
  722. if(token !== null && token !== undefined)
  723. request["token"] = token;
  724. if(apisecret !== null && apisecret !== undefined)
  725. request["apisecret"] = apisecret;
  726. if(websockets) {
  727. transactions[transaction] = function(json) {
  728. Janus.debug(json);
  729. if(json["janus"] !== "success") {
  730. Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
  731. callbacks.error("Ooops: " + json["error"].code + " " + json["error"].reason);
  732. return;
  733. }
  734. var handleId = json.data["id"];
  735. Janus.log("Created handle: " + handleId);
  736. var pluginHandle =
  737. {
  738. session : that,
  739. plugin : plugin,
  740. id : handleId,
  741. webrtcStuff : {
  742. started : false,
  743. myStream : null,
  744. streamExternal : false,
  745. remoteStream : null,
  746. mySdp : null,
  747. pc : null,
  748. dataChannel : null,
  749. dtmfSender : null,
  750. trickle : true,
  751. iceDone : false,
  752. sdpSent : false,
  753. volume : {
  754. value : null,
  755. timer : null
  756. },
  757. bitrate : {
  758. value : null,
  759. bsnow : null,
  760. bsbefore : null,
  761. tsnow : null,
  762. tsbefore : null,
  763. timer : null
  764. }
  765. },
  766. getId : function() { return handleId; },
  767. getPlugin : function() { return plugin; },
  768. getVolume : function() { return getVolume(handleId); },
  769. isAudioMuted : function() { return isMuted(handleId, false); },
  770. muteAudio : function() { return mute(handleId, false, true); },
  771. unmuteAudio : function() { return mute(handleId, false, false); },
  772. isVideoMuted : function() { return isMuted(handleId, true); },
  773. muteVideo : function() { return mute(handleId, true, true); },
  774. unmuteVideo : function() { return mute(handleId, true, false); },
  775. getBitrate : function() { return getBitrate(handleId); },
  776. send : function(callbacks) { sendMessage(handleId, callbacks); },
  777. data : function(callbacks) { sendData(handleId, callbacks); },
  778. dtmf : function(callbacks) { sendDtmf(handleId, callbacks); },
  779. consentDialog : callbacks.consentDialog,
  780. mediaState : callbacks.mediaState,
  781. webrtcState : callbacks.webrtcState,
  782. onmessage : callbacks.onmessage,
  783. createOffer : function(callbacks) { prepareWebrtc(handleId, callbacks); },
  784. createAnswer : function(callbacks) { prepareWebrtc(handleId, callbacks); },
  785. handleRemoteJsep : function(callbacks) { prepareWebrtcPeer(handleId, callbacks); },
  786. onlocalstream : callbacks.onlocalstream,
  787. onremotestream : callbacks.onremotestream,
  788. ondata : callbacks.ondata,
  789. ondataopen : callbacks.ondataopen,
  790. oncleanup : callbacks.oncleanup,
  791. ondetached : callbacks.ondetached,
  792. hangup : function(sendRequest) { cleanupWebrtc(handleId, sendRequest === true); },
  793. detach : function(callbacks) { destroyHandle(handleId, callbacks); }
  794. }
  795. pluginHandles[handleId] = pluginHandle;
  796. callbacks.success(pluginHandle);
  797. };
  798. request["session_id"] = sessionId;
  799. ws.send(JSON.stringify(request));
  800. return;
  801. }
  802. $.ajax({
  803. type: 'POST',
  804. url: server + "/" + sessionId,
  805. cache: false,
  806. contentType: "application/json",
  807. data: JSON.stringify(request),
  808. success: function(json) {
  809. Janus.debug(json);
  810. if(json["janus"] !== "success") {
  811. Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
  812. callbacks.error("Ooops: " + json["error"].code + " " + json["error"].reason);
  813. return;
  814. }
  815. var handleId = json.data["id"];
  816. Janus.log("Created handle: " + handleId);
  817. var pluginHandle =
  818. {
  819. session : that,
  820. plugin : plugin,
  821. id : handleId,
  822. webrtcStuff : {
  823. started : false,
  824. myStream : null,
  825. streamExternal : false,
  826. remoteStream : null,
  827. mySdp : null,
  828. pc : null,
  829. dataChannel : null,
  830. dtmfSender : null,
  831. trickle : true,
  832. iceDone : false,
  833. sdpSent : false,
  834. volume : {
  835. value : null,
  836. timer : null
  837. },
  838. bitrate : {
  839. value : null,
  840. bsnow : null,
  841. bsbefore : null,
  842. tsnow : null,
  843. tsbefore : null,
  844. timer : null
  845. }
  846. },
  847. getId : function() { return handleId; },
  848. getPlugin : function() { return plugin; },
  849. getVolume : function() { return getVolume(handleId); },
  850. isAudioMuted : function() { return isMuted(handleId, false); },
  851. muteAudio : function() { return mute(handleId, false, true); },
  852. unmuteAudio : function() { return mute(handleId, false, false); },
  853. isVideoMuted : function() { return isMuted(handleId, true); },
  854. muteVideo : function() { return mute(handleId, true, true); },
  855. unmuteVideo : function() { return mute(handleId, true, false); },
  856. getBitrate : function() { return getBitrate(handleId); },
  857. send : function(callbacks) { sendMessage(handleId, callbacks); },
  858. data : function(callbacks) { sendData(handleId, callbacks); },
  859. dtmf : function(callbacks) { sendDtmf(handleId, callbacks); },
  860. consentDialog : callbacks.consentDialog,
  861. mediaState : callbacks.mediaState,
  862. webrtcState : callbacks.webrtcState,
  863. onmessage : callbacks.onmessage,
  864. createOffer : function(callbacks) { prepareWebrtc(handleId, callbacks); },
  865. createAnswer : function(callbacks) { prepareWebrtc(handleId, callbacks); },
  866. handleRemoteJsep : function(callbacks) { prepareWebrtcPeer(handleId, callbacks); },
  867. onlocalstream : callbacks.onlocalstream,
  868. onremotestream : callbacks.onremotestream,
  869. ondata : callbacks.ondata,
  870. ondataopen : callbacks.ondataopen,
  871. oncleanup : callbacks.oncleanup,
  872. ondetached : callbacks.ondetached,
  873. hangup : function(sendRequest) { cleanupWebrtc(handleId, sendRequest === true); },
  874. detach : function(callbacks) { destroyHandle(handleId, callbacks); }
  875. }
  876. pluginHandles[handleId] = pluginHandle;
  877. callbacks.success(pluginHandle);
  878. },
  879. error: function(XMLHttpRequest, textStatus, errorThrown) {
  880. Janus.error(textStatus + ": " + errorThrown); // FIXME
  881. },
  882. dataType: "json"
  883. });
  884. }
  885.  
  886. // Private method to send a message
  887. function sendMessage(handleId, callbacks) {
  888. callbacks = callbacks || {};
  889. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : jQuery.noop;
  890. callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : jQuery.noop;
  891. if(!connected) {
  892. Janus.warn("Is the gateway down? (connected=false)");
  893. callbacks.error("Is the gateway down? (connected=false)");
  894. return;
  895. }
  896. var message = callbacks.message;
  897. var jsep = callbacks.jsep;
  898. var transaction = randomString(12);
  899. var request = { "janus": "message", "body": message, "transaction": transaction };
  900. if(token !== null && token !== undefined)
  901. request["token"] = token;
  902. if(apisecret !== null && apisecret !== undefined)
  903. request["apisecret"] = apisecret;
  904. if(jsep !== null && jsep !== undefined)
  905. request.jsep = jsep;
  906. Janus.debug("Sending message to plugin (handle=" + handleId + "):");
  907. Janus.debug(request);
  908. if(websockets) {
  909. request["session_id"] = sessionId;
  910. request["handle_id"] = handleId;
  911. transactions[transaction] = function(json) {
  912. Janus.debug("Message sent!");
  913. Janus.debug(json);
  914. if(json["janus"] === "success") {
  915. // We got a success, must have been a synchronous transaction
  916. var plugindata = json["plugindata"];
  917. if(plugindata === undefined || plugindata === null) {
  918. Janus.warn("Request succeeded, but missing plugindata...");
  919. callbacks.success();
  920. return;
  921. }
  922. Janus.log("Synchronous transaction successful (" + plugindata["plugin"] + ")");
  923. var data = plugindata["data"];
  924. Janus.debug(data);
  925. callbacks.success(data);
  926. return;
  927. } else if(json["janus"] !== "ack") {
  928. // Not a success and not an ack, must be an error
  929. if(json["error"] !== undefined && json["error"] !== null) {
  930. Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
  931. callbacks.error(json["error"].code + " " + json["error"].reason);
  932. } else {
  933. Janus.error("Unknown error"); // FIXME
  934. callbacks.error("Unknown error");
  935. }
  936. return;
  937. }
  938. // If we got here, the plugin decided to handle the request asynchronously
  939. callbacks.success();
  940. };
  941. ws.send(JSON.stringify(request));
  942. return;
  943. }
  944. $.ajax({
  945. type: 'POST',
  946. url: server + "/" + sessionId + "/" + handleId,
  947. cache: false,
  948. contentType: "application/json",
  949. data: JSON.stringify(request),
  950. success: function(json) {
  951. Janus.debug("Message sent!");
  952. Janus.debug(json);
  953. if(json["janus"] === "success") {
  954. // We got a success, must have been a synchronous transaction
  955. var plugindata = json["plugindata"];
  956. if(plugindata === undefined || plugindata === null) {
  957. Janus.warn("Request succeeded, but missing plugindata...");
  958. callbacks.success();
  959. return;
  960. }
  961. Janus.log("Synchronous transaction successful (" + plugindata["plugin"] + ")");
  962. var data = plugindata["data"];
  963. Janus.debug(data);
  964. callbacks.success(data);
  965. return;
  966. } else if(json["janus"] !== "ack") {
  967. // Not a success and not an ack, must be an error
  968. if(json["error"] !== undefined && json["error"] !== null) {
  969. Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
  970. callbacks.error(json["error"].code + " " + json["error"].reason);
  971. } else {
  972. Janus.error("Unknown error"); // FIXME
  973. callbacks.error("Unknown error");
  974. }
  975. return;
  976. }
  977. // If we got here, the plugin decided to handle the request asynchronously
  978. callbacks.success();
  979. },
  980. error: function(XMLHttpRequest, textStatus, errorThrown) {
  981. Janus.error(textStatus + ": " + errorThrown); // FIXME
  982. callbacks.error(textStatus + ": " + errorThrown);
  983. },
  984. dataType: "json"
  985. });
  986. }
  987.  
  988. // Private method to send a trickle candidate
  989. function sendTrickleCandidate(handleId, candidate) {
  990. if(!connected) {
  991. Janus.warn("Is the gateway down? (connected=false)");
  992. return;
  993. }
  994. var request = { "janus": "trickle", "candidate": candidate, "transaction": randomString(12) };
  995. if(token !== null && token !== undefined)
  996. request["token"] = token;
  997. if(apisecret !== null && apisecret !== undefined)
  998. request["apisecret"] = apisecret;
  999. Janus.debug("Sending trickle candidate (handle=" + handleId + "):");
  1000. Janus.debug(request);
  1001. if(websockets) {
  1002. request["session_id"] = sessionId;
  1003. request["handle_id"] = handleId;
  1004. ws.send(JSON.stringify(request));
  1005. return;
  1006. }
  1007. $.ajax({
  1008. type: 'POST',
  1009. url: server + "/" + sessionId + "/" + handleId,
  1010. cache: false,
  1011. contentType: "application/json",
  1012. data: JSON.stringify(request),
  1013. success: function(json) {
  1014. Janus.debug("Candidate sent!");
  1015. Janus.debug(json);
  1016. if(json["janus"] !== "ack") {
  1017. Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
  1018. return;
  1019. }
  1020. },
  1021. error: function(XMLHttpRequest, textStatus, errorThrown) {
  1022. Janus.error(textStatus + ": " + errorThrown); // FIXME
  1023. },
  1024. dataType: "json"
  1025. });
  1026. }
  1027.  
  1028. // Private method to send a data channel message
  1029. function sendData(handleId, callbacks) {
  1030. callbacks = callbacks || {};
  1031. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : jQuery.noop;
  1032. callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : jQuery.noop;
  1033. var pluginHandle = pluginHandles[handleId];
  1034. if(pluginHandle === null || pluginHandle === undefined ||
  1035. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  1036. Janus.warn("Invalid handle");
  1037. callbacks.error("Invalid handle");
  1038. return;
  1039. }
  1040. var config = pluginHandle.webrtcStuff;
  1041. var text = callbacks.text;
  1042. if(text === null || text === undefined) {
  1043. Janus.warn("Invalid text");
  1044. callbacks.error("Invalid text");
  1045. return;
  1046. }
  1047. Janus.log("Sending string on data channel: " + text);
  1048. config.dataChannel.send(text);
  1049. callbacks.success();
  1050. }
  1051.  
  1052. // Private method to send a DTMF tone
  1053. function sendDtmf(handleId, callbacks) {
  1054. callbacks = callbacks || {};
  1055. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : jQuery.noop;
  1056. callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : jQuery.noop;
  1057. var pluginHandle = pluginHandles[handleId];
  1058. if(pluginHandle === null || pluginHandle === undefined ||
  1059. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  1060. Janus.warn("Invalid handle");
  1061. callbacks.error("Invalid handle");
  1062. return;
  1063. }
  1064. var config = pluginHandle.webrtcStuff;
  1065. if(config.dtmfSender === null || config.dtmfSender === undefined) {
  1066. // Create the DTMF sender, if possible
  1067. if(config.myStream !== undefined && config.myStream !== null) {
  1068. var tracks = config.myStream.getAudioTracks();
  1069. if(tracks !== null && tracks !== undefined && tracks.length > 0) {
  1070. var local_audio_track = tracks[0];
  1071. config.dtmfSender = config.pc.createDTMFSender(local_audio_track);
  1072. Janus.log("Created DTMF Sender");
  1073. config.dtmfSender.ontonechange = function(tone) { Janus.debug("Sent DTMF tone: " + tone.tone); };
  1074. }
  1075. }
  1076. if(config.dtmfSender === null || config.dtmfSender === undefined) {
  1077. Janus.warn("Invalid DTMF configuration");
  1078. callbacks.error("Invalid DTMF configuration");
  1079. return;
  1080. }
  1081. }
  1082. var dtmf = callbacks.dtmf;
  1083. if(dtmf === null || dtmf === undefined) {
  1084. Janus.warn("Invalid DTMF parameters");
  1085. callbacks.error("Invalid DTMF parameters");
  1086. return;
  1087. }
  1088. var tones = dtmf.tones;
  1089. if(tones === null || tones === undefined) {
  1090. Janus.warn("Invalid DTMF string");
  1091. callbacks.error("Invalid DTMF string");
  1092. return;
  1093. }
  1094. var duration = dtmf.duration;
  1095. if(duration === null || duration === undefined)
  1096. duration = 500; // We choose 500ms as the default duration for a tone
  1097. var gap = dtmf.gap;
  1098. if(gap === null || gap === undefined)
  1099. gap = 50; // We choose 50ms as the default gap between tones
  1100. Janus.debug("Sending DTMF string " + tones + " (duration " + duration + "ms, gap " + gap + "ms");
  1101. config.dtmfSender.insertDTMF(tones, duration, gap);
  1102. }
  1103.  
  1104. // Private method to destroy a plugin handle
  1105. function destroyHandle(handleId, callbacks, syncRequest) {
  1106. syncRequest = (syncRequest === true);
  1107. Janus.log("Destroying handle " + handleId + " (sync=" + syncRequest + ")");
  1108. callbacks = callbacks || {};
  1109. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : jQuery.noop;
  1110. callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : jQuery.noop;
  1111. cleanupWebrtc(handleId);
  1112. if(!connected) {
  1113. Janus.warn("Is the gateway down? (connected=false)");
  1114. callbacks.error("Is the gateway down? (connected=false)");
  1115. return;
  1116. }
  1117. var request = { "janus": "detach", "transaction": randomString(12) };
  1118. if(token !== null && token !== undefined)
  1119. request["token"] = token;
  1120. if(apisecret !== null && apisecret !== undefined)
  1121. request["apisecret"] = apisecret;
  1122. if(websockets) {
  1123. request["session_id"] = sessionId;
  1124. request["handle_id"] = handleId;
  1125. ws.send(JSON.stringify(request));
  1126. delete pluginHandles[handleId];
  1127. callbacks.success();
  1128. return;
  1129. }
  1130. $.ajax({
  1131. type: 'POST',
  1132. url: server + "/" + sessionId + "/" + handleId,
  1133. async: syncRequest, // Sometimes we need false here, or destroying in onbeforeunload won't work
  1134. cache: false,
  1135. contentType: "application/json",
  1136. data: JSON.stringify(request),
  1137. success: function(json) {
  1138. Janus.log("Destroyed handle:");
  1139. Janus.debug(json);
  1140. if(json["janus"] !== "success") {
  1141. Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
  1142. }
  1143. delete pluginHandles[handleId];
  1144. callbacks.success();
  1145. },
  1146. error: function(XMLHttpRequest, textStatus, errorThrown) {
  1147. Janus.error(textStatus + ": " + errorThrown); // FIXME
  1148. // We cleanup anyway
  1149. delete pluginHandles[handleId];
  1150. callbacks.success();
  1151. },
  1152. dataType: "json"
  1153. });
  1154. }
  1155.  
  1156. // WebRTC stuff
  1157. function streamsDone(handleId, jsep, media, callbacks, stream) {
  1158. var pluginHandle = pluginHandles[handleId];
  1159. if(pluginHandle === null || pluginHandle === undefined ||
  1160. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  1161. Janus.warn("Invalid handle");
  1162. callbacks.error("Invalid handle");
  1163. return;
  1164. }
  1165. var config = pluginHandle.webrtcStuff;
  1166. Janus.debug("streamsDone:", stream);
  1167. config.myStream = stream;
  1168. var pc_config = {"iceServers": iceServers};
  1169. //~ var pc_constraints = {'mandatory': {'MozDontOfferDataChannel':true}};
  1170. var pc_constraints = {
  1171. "optional": [{"DtlsSrtpKeyAgreement": true}]
  1172. };
  1173. if(ipv6Support === true) {
  1174. // FIXME This is only supported in Chrome right now
  1175. // For support in Firefox track this: https://bugzilla.mozilla.org/show_bug.cgi?id=797262
  1176. pc_constraints.optional.push({"googIPv6":true});
  1177. }
  1178. Janus.log("Creating PeerConnection");
  1179. Janus.debug(pc_constraints);
  1180. config.pc = new RTCPeerConnection(pc_config, pc_constraints);
  1181. Janus.debug(config.pc);
  1182. if(config.pc.getStats) { // FIXME
  1183. config.volume.value = 0;
  1184. config.bitrate.value = "0 kbits/sec";
  1185. }
  1186. Janus.log("Preparing local SDP and gathering candidates (trickle=" + config.trickle + ")");
  1187. config.pc.onicecandidate = function(event) {
  1188. if (event.candidate == null ||
  1189. (webrtcDetectedBrowser === 'edge' && event.candidate.candidate.indexOf('endOfCandidates') > 0)) {
  1190. Janus.log("End of candidates.");
  1191. config.iceDone = true;
  1192. if(config.trickle === true) {
  1193. // Notify end of candidates
  1194. sendTrickleCandidate(handleId, {"completed": true});
  1195. } else {
  1196. // No trickle, time to send the complete SDP (including all candidates)
  1197. sendSDP(handleId, callbacks);
  1198. }
  1199. } else {
  1200. // JSON.stringify doesn't work on some WebRTC objects anymore
  1201. // See https://code.google.com/p/chromium/issues/detail?id=467366
  1202. var candidate = {
  1203. "candidate": event.candidate.candidate,
  1204. "sdpMid": event.candidate.sdpMid,
  1205. "sdpMLineIndex": event.candidate.sdpMLineIndex
  1206. };
  1207. if(config.trickle === true) {
  1208. // Send candidate
  1209. sendTrickleCandidate(handleId, candidate);
  1210. }
  1211. }
  1212. };
  1213. if(stream !== null && stream !== undefined) {
  1214. Janus.log('Adding local stream');
  1215. config.pc.addStream(stream);
  1216. pluginHandle.onlocalstream(stream);
  1217. }
  1218. config.pc.onaddstream = function(remoteStream) {
  1219. Janus.log("Handling Remote Stream");
  1220. Janus.debug(remoteStream);
  1221. config.remoteStream = remoteStream;
  1222. pluginHandle.onremotestream(remoteStream.stream);
  1223. };
  1224. // Any data channel to create?
  1225. if(isDataEnabled(media)) {
  1226. Janus.log("Creating data channel");
  1227. var onDataChannelMessage = function(event) {
  1228. Janus.log('Received message on data channel: ' + event.data);
  1229. pluginHandle.ondata(event.data); // FIXME
  1230. }
  1231. var onDataChannelStateChange = function() {
  1232. var dcState = config.dataChannel !== null ? config.dataChannel.readyState : "null";
  1233. Janus.log('State change on data channel: ' + dcState);
  1234. if(dcState === 'open') {
  1235. pluginHandle.ondataopen(); // FIXME
  1236. }
  1237. }
  1238. var onDataChannelError = function(error) {
  1239. Janus.error('Got error on data channel:', error);
  1240. // TODO
  1241. }
  1242. // Until we implement the proxying of open requests within the Janus core, we open a channel ourselves whatever the case
  1243. config.dataChannel = config.pc.createDataChannel("JanusDataChannel", {ordered:false}); // FIXME Add options (ordered, maxRetransmits, etc.)
  1244. config.dataChannel.onmessage = onDataChannelMessage;
  1245. config.dataChannel.onopen = onDataChannelStateChange;
  1246. config.dataChannel.onclose = onDataChannelStateChange;
  1247. config.dataChannel.onerror = onDataChannelError;
  1248. }
  1249. // Create offer/answer now
  1250. if(jsep === null || jsep === undefined) {
  1251. createOffer(handleId, media, callbacks);
  1252. } else {
  1253. config.pc.setRemoteDescription(
  1254. new RTCSessionDescription(jsep),
  1255. function() {
  1256. Janus.log("Remote description accepted!");
  1257. createAnswer(handleId, media, callbacks);
  1258. }, callbacks.error);
  1259. }
  1260. }
  1261.  
  1262. function prepareWebrtc(handleId, callbacks) {
  1263. callbacks = callbacks || {};
  1264. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : jQuery.noop;
  1265. callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : webrtcError;
  1266. var jsep = callbacks.jsep;
  1267. var media = callbacks.media;
  1268. var pluginHandle = pluginHandles[handleId];
  1269. if(pluginHandle === null || pluginHandle === undefined ||
  1270. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  1271. Janus.warn("Invalid handle");
  1272. callbacks.error("Invalid handle");
  1273. return;
  1274. }
  1275. var config = pluginHandle.webrtcStuff;
  1276. // Are we updating a session?
  1277. if(config.pc !== undefined && config.pc !== null) {
  1278. Janus.log("Updating existing media session");
  1279. // Create offer/answer now
  1280. if(jsep === null || jsep === undefined) {
  1281. createOffer(handleId, media, callbacks);
  1282. } else {
  1283. config.pc.setRemoteDescription(
  1284. new RTCSessionDescription(jsep),
  1285. function() {
  1286. Janus.log("Remote description accepted!");
  1287. createAnswer(handleId, media, callbacks);
  1288. }, callbacks.error);
  1289. }
  1290. return;
  1291. }
  1292. // Was a MediaStream object passed, or do we need to take care of that?
  1293. if(callbacks.stream !== null && callbacks.stream !== undefined) {
  1294. var stream = callbacks.stream;
  1295. Janus.log("MediaStream provided by the application");
  1296. Janus.debug(stream);
  1297. // Skip the getUserMedia part
  1298. config.streamExternal = true;
  1299. streamsDone(handleId, jsep, media, callbacks, stream);
  1300. return;
  1301. }
  1302. config.trickle = isTrickleEnabled(callbacks.trickle);
  1303. if(isAudioSendEnabled(media) || isVideoSendEnabled(media)) {
  1304. var constraints = { mandatory: {}, optional: []};
  1305. pluginHandle.consentDialog(true);
  1306. var audioSupport = isAudioSendEnabled(media);
  1307. if(audioSupport === true && media != undefined && media != null) {
  1308. if(typeof media.audio === 'object') {
  1309. audioSupport = media.audio;
  1310. }
  1311. }
  1312. var videoSupport = isVideoSendEnabled(media);
  1313. if(videoSupport === true && media != undefined && media != null) {
  1314. if(media.video && media.video != 'screen' && media.video != 'window') {
  1315. var width = 0;
  1316. var height = 0, maxHeight = 0;
  1317. if(media.video === 'lowres') {
  1318. // Small resolution, 4:3
  1319. height = 240;
  1320. maxHeight = 240;
  1321. width = 320;
  1322. } else if(media.video === 'lowres-16:9') {
  1323. // Small resolution, 16:9
  1324. height = 180;
  1325. maxHeight = 180;
  1326. width = 320;
  1327. } else if(media.video === 'hires' || media.video === 'hires-16:9' ) {
  1328. // High resolution is only 16:9
  1329. height = 720;
  1330. maxHeight = 720;
  1331. width = 1280;
  1332. if(navigator.mozGetUserMedia) {
  1333. var firefoxVer = parseInt(window.navigator.userAgent.match(/Firefox\/(.*)/)[1], 10);
  1334. if(firefoxVer < 38) {
  1335. // Unless this is and old Firefox, which doesn't support it
  1336. Janus.warn(media.video + " unsupported, falling back to stdres (old Firefox)");
  1337. height = 480;
  1338. maxHeight = 480;
  1339. width = 640;
  1340. }
  1341. }
  1342. } else if(media.video === 'stdres') {
  1343. // Normal resolution, 4:3
  1344. height = 480;
  1345. maxHeight = 480;
  1346. width = 640;
  1347. } else if(media.video === 'stdres-16:9') {
  1348. // Normal resolution, 16:9
  1349. height = 360;
  1350. maxHeight = 360;
  1351. width = 640;
  1352. } else {
  1353. Janus.log("Default video setting (" + media.video + ") is stdres 4:3");
  1354. height = 480;
  1355. maxHeight = 480;
  1356. width = 640;
  1357. }
  1358. Janus.log("Adding media constraint " + media.video);
  1359. if(navigator.mozGetUserMedia) {
  1360. var firefoxVer = parseInt(window.navigator.userAgent.match(/Firefox\/(.*)/)[1], 10);
  1361. if(firefoxVer < 38) {
  1362. videoSupport = {
  1363. 'require': ['height', 'width'],
  1364. 'height': {'max': maxHeight, 'min': height},
  1365. 'width': {'max': width, 'min': width}
  1366. };
  1367. } else {
  1368. // http://stackoverflow.com/questions/28282385/webrtc-firefox-constraints/28911694#28911694
  1369. // https://github.com/meetecho/janus-gateway/pull/246
  1370. videoSupport = {
  1371. 'height': {'ideal': height},
  1372. 'width': {'ideal': width}
  1373. };
  1374. }
  1375. } else {
  1376. videoSupport = {
  1377. 'mandatory': {
  1378. 'maxHeight': maxHeight,
  1379. 'minHeight': height,
  1380. 'maxWidth': width,
  1381. 'minWidth': width
  1382. },
  1383. 'optional': []
  1384. };
  1385. }
  1386. if(typeof media.video === 'object') {
  1387. videoSupport = media.video;
  1388. }
  1389. Janus.debug(videoSupport);
  1390. } else if(media.video === 'screen' || media.video === 'window') {
  1391. // Not a webcam, but screen capture
  1392. if(window.location.protocol !== 'https:') {
  1393. // Screen sharing mandates HTTPS
  1394. Janus.warn("Screen sharing only works on HTTPS, try the https:// version of this page");
  1395. pluginHandle.consentDialog(false);
  1396. callbacks.error("Screen sharing only works on HTTPS, try the https:// version of this page");
  1397. return;
  1398. }
  1399. // We're going to try and use the extension for Chrome 34+, the old approach
  1400. // for older versions of Chrome, or the experimental support in Firefox 33+
  1401. var cache = {};
  1402. function callbackUserMedia (error, stream) {
  1403. pluginHandle.consentDialog(false);
  1404. if(error) {
  1405. callbacks.error({code: error.code, name: error.name, message: error.message});
  1406. } else {
  1407. streamsDone(handleId, jsep, media, callbacks, stream);
  1408. }
  1409. };
  1410. function getScreenMedia(constraints, gsmCallback) {
  1411. Janus.log("Adding media constraint (screen capture)");
  1412. Janus.debug(constraints);
  1413. navigator.mediaDevices.getUserMedia(constraints)
  1414. .then(function(stream) { gsmCallback(null, stream); })
  1415. .catch(function(error) { pluginHandle.consentDialog(false); gsmCallback(error); });
  1416. };
  1417. if(window.navigator.userAgent.match('Chrome')) {
  1418. var chromever = parseInt(window.navigator.userAgent.match(/Chrome\/(.*) /)[1], 10);
  1419. var maxver = 33;
  1420. if(window.navigator.userAgent.match('Linux'))
  1421. maxver = 35; // "known" crash in chrome 34 and 35 on linux
  1422. if(chromever >= 26 && chromever <= maxver) {
  1423. // Chrome 26->33 requires some awkward chrome://flags manipulation
  1424. constraints = {
  1425. video: {
  1426. mandatory: {
  1427. googLeakyBucket: true,
  1428. maxWidth: window.screen.width,
  1429. maxHeight: window.screen.height,
  1430. maxFrameRate: 3,
  1431. chromeMediaSource: 'screen'
  1432. }
  1433. },
  1434. audio: isAudioSendEnabled(media)
  1435. };
  1436. getScreenMedia(constraints, callbackUserMedia);
  1437. } else {
  1438. // Chrome 34+ requires an extension
  1439. var pending = window.setTimeout(
  1440. function () {
  1441. error = new Error('NavigatorUserMediaError');
  1442. error.name = 'The required Chrome extension is not installed: click <a href="#">here</a> to install it. (NOTE: this will need you to refresh the page)';
  1443. pluginHandle.consentDialog(false);
  1444. return callbacks.error(error);
  1445. }, 1000);
  1446. cache[pending] = [callbackUserMedia, null];
  1447. window.postMessage({ type: 'janusGetScreen', id: pending }, '*');
  1448. }
  1449. } else if (window.navigator.userAgent.match('Firefox')) {
  1450. var ffver = parseInt(window.navigator.userAgent.match(/Firefox\/(.*)/)[1], 10);
  1451. if(ffver >= 33) {
  1452. // Firefox 33+ has experimental support for screen sharing
  1453. constraints = {
  1454. video: {
  1455. mozMediaSource: media.video,
  1456. mediaSource: media.video
  1457. },
  1458. audio: isAudioSendEnabled(media)
  1459. };
  1460. getScreenMedia(constraints, function (err, stream) {
  1461. callbackUserMedia(err, stream);
  1462. // Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=1045810
  1463. if (!err) {
  1464. var lastTime = stream.currentTime;
  1465. var polly = window.setInterval(function () {
  1466. if(!stream)
  1467. window.clearInterval(polly);
  1468. if(stream.currentTime == lastTime) {
  1469. window.clearInterval(polly);
  1470. if(stream.onended) {
  1471. stream.onended();
  1472. }
  1473. }
  1474. lastTime = stream.currentTime;
  1475. }, 500);
  1476. }
  1477. });
  1478. } else {
  1479. var error = new Error('NavigatorUserMediaError');
  1480. error.name = 'Your version of Firefox does not support screen sharing, please install Firefox 33 (or more recent versions)';
  1481. pluginHandle.consentDialog(false);
  1482. callbacks.error(error);
  1483. return;
  1484. }
  1485. }
  1486.  
  1487. // Wait for events from the Chrome Extension
  1488. window.addEventListener('message', function (event) {
  1489. if(event.origin != window.location.origin)
  1490. return;
  1491. if(event.data.type == 'janusGotScreen' && cache[event.data.id]) {
  1492. var data = cache[event.data.id];
  1493. var callback = data[0];
  1494. delete cache[event.data.id];
  1495.  
  1496. if (event.data.sourceId === '') {
  1497. // user canceled
  1498. var error = new Error('NavigatorUserMediaError');
  1499. error.name = 'You cancelled the request for permission, giving up...';
  1500. pluginHandle.consentDialog(false);
  1501. callbacks.error(error);
  1502. } else {
  1503. constraints = {
  1504. audio: isAudioSendEnabled(media),
  1505. video: {
  1506. mandatory: {
  1507. chromeMediaSource: 'desktop',
  1508. maxWidth: window.screen.width,
  1509. maxHeight: window.screen.height,
  1510. maxFrameRate: 3
  1511. },
  1512. optional: [
  1513. {googLeakyBucket: true},
  1514. {googTemporalLayeredScreencast: true}
  1515. ]
  1516. }
  1517. };
  1518. constraints.video.mandatory.chromeMediaSourceId = event.data.sourceId;
  1519. getScreenMedia(constraints, callback);
  1520. }
  1521. } else if (event.data.type == 'janusGetScreenPending') {
  1522. window.clearTimeout(event.data.id);
  1523. }
  1524. });
  1525. return;
  1526. }
  1527. }
  1528. // If we got here, we're not screensharing
  1529. if(media === null || media === undefined || media.video !== 'screen') {
  1530. // Check whether all media sources are actually available or not
  1531. navigator.mediaDevices.enumerateDevices().then(function(devices) {
  1532. var audioExist = devices.some(function(device) {
  1533. return device.kind === 'audioinput';
  1534. }),
  1535. videoExist = devices.some(function(device) {
  1536. return device.kind === 'videoinput';
  1537. });
  1538.  
  1539. // Check whether a missing device is really a problem
  1540. var audioSend = isAudioSendEnabled(media);
  1541. var videoSend = isVideoSendEnabled(media);
  1542. if(audioSend || videoSend) {
  1543. // We need to send either audio or video
  1544. var haveAudioDevice = audioSend ? audioExist : false;
  1545. var haveVideoDevice = videoSend ? videoExist : false;
  1546. if(!haveAudioDevice && !haveVideoDevice) {
  1547. // FIXME Should we really give up, or just assume recvonly for both?
  1548. pluginHandle.consentDialog(false);
  1549. callbacks.error('No capture device found');
  1550. return false;
  1551. }
  1552. }
  1553.  
  1554. navigator.mediaDevices.getUserMedia({
  1555. audio: audioExist ? audioSupport : false,
  1556. video: videoExist ? videoSupport : false
  1557. })
  1558. .then(function(stream) { pluginHandle.consentDialog(false); streamsDone(handleId, jsep, media, callbacks, stream); })
  1559. .catch(function(error) { pluginHandle.consentDialog(false); callbacks.error({code: error.code, name: error.name, message: error.message}); });
  1560. })
  1561. .catch(function(error) {
  1562. pluginHandle.consentDialog(false);
  1563. callbacks.error('enumerateDevices error', error);
  1564. });
  1565. }
  1566. } else {
  1567. // No need to do a getUserMedia, create offer/answer right away
  1568. streamsDone(handleId, jsep, media, callbacks);
  1569. }
  1570. }
  1571.  
  1572. function prepareWebrtcPeer(handleId, callbacks) {
  1573. callbacks = callbacks || {};
  1574. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : jQuery.noop;
  1575. callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : webrtcError;
  1576. var jsep = callbacks.jsep;
  1577. var pluginHandle = pluginHandles[handleId];
  1578. if(pluginHandle === null || pluginHandle === undefined ||
  1579. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  1580. Janus.warn("Invalid handle");
  1581. callbacks.error("Invalid handle");
  1582. return;
  1583. }
  1584. var config = pluginHandle.webrtcStuff;
  1585. if(jsep !== undefined && jsep !== null) {
  1586. if(config.pc === null) {
  1587. Janus.warn("Wait, no PeerConnection?? if this is an answer, use createAnswer and not handleRemoteJsep");
  1588. callbacks.error("No PeerConnection: if this is an answer, use createAnswer and not handleRemoteJsep");
  1589. return;
  1590. }
  1591. config.pc.setRemoteDescription(
  1592. new RTCSessionDescription(jsep),
  1593. function() {
  1594. Janus.log("Remote description accepted!");
  1595. callbacks.success();
  1596. }, callbacks.error);
  1597. } else {
  1598. callbacks.error("Invalid JSEP");
  1599. }
  1600. }
  1601.  
  1602. function createOffer(handleId, media, callbacks) {
  1603. callbacks = callbacks || {};
  1604. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : jQuery.noop;
  1605. callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : jQuery.noop;
  1606. var pluginHandle = pluginHandles[handleId];
  1607. if(pluginHandle === null || pluginHandle === undefined ||
  1608. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  1609. Janus.warn("Invalid handle");
  1610. callbacks.error("Invalid handle");
  1611. return;
  1612. }
  1613. var config = pluginHandle.webrtcStuff;
  1614. Janus.log("Creating offer (iceDone=" + config.iceDone + ")");
  1615. // https://code.google.com/p/webrtc/issues/detail?id=3508
  1616. var mediaConstraints = null;
  1617. if(webrtcDetectedBrowser == "firefox" || webrtcDetectedBrowser == "edge") {
  1618. mediaConstraints = {
  1619. 'offerToReceiveAudio':isAudioRecvEnabled(media),
  1620. 'offerToReceiveVideo':isVideoRecvEnabled(media)
  1621. };
  1622. } else {
  1623. mediaConstraints = {
  1624. 'mandatory': {
  1625. 'OfferToReceiveAudio':isAudioRecvEnabled(media),
  1626. 'OfferToReceiveVideo':isVideoRecvEnabled(media)
  1627. }
  1628. };
  1629. }
  1630. Janus.debug(mediaConstraints);
  1631. config.pc.createOffer(
  1632. function(offer) {
  1633. Janus.debug(offer);
  1634. if(config.mySdp === null || config.mySdp === undefined) {
  1635. Janus.log("Setting local description");
  1636. config.mySdp = offer.sdp;
  1637. config.pc.setLocalDescription(offer);
  1638. }
  1639. if(!config.iceDone && !config.trickle) {
  1640. // Don't do anything until we have all candidates
  1641. Janus.log("Waiting for all candidates...");
  1642. return;
  1643. }
  1644. if(config.sdpSent) {
  1645. Janus.log("Offer already sent, not sending it again");
  1646. return;
  1647. }
  1648. Janus.log("Offer ready");
  1649. Janus.debug(callbacks);
  1650. config.sdpSent = true;
  1651. // JSON.stringify doesn't work on some WebRTC objects anymore
  1652. // See https://code.google.com/p/chromium/issues/detail?id=467366
  1653. var jsep = {
  1654. "type": offer.type,
  1655. "sdp": offer.sdp
  1656. };
  1657. callbacks.success(jsep);
  1658. }, callbacks.error, mediaConstraints);
  1659. }
  1660.  
  1661. function createAnswer(handleId, media, callbacks) {
  1662. callbacks = callbacks || {};
  1663. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : jQuery.noop;
  1664. callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : jQuery.noop;
  1665. var pluginHandle = pluginHandles[handleId];
  1666. if(pluginHandle === null || pluginHandle === undefined ||
  1667. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  1668. Janus.warn("Invalid handle");
  1669. callbacks.error("Invalid handle");
  1670. return;
  1671. }
  1672. var config = pluginHandle.webrtcStuff;
  1673. Janus.log("Creating answer (iceDone=" + config.iceDone + ")");
  1674. var mediaConstraints = null;
  1675. if(webrtcDetectedBrowser == "firefox" || webrtcDetectedBrowser == "edge") {
  1676. mediaConstraints = {
  1677. 'offerToReceiveAudio':isAudioRecvEnabled(media),
  1678. 'offerToReceiveVideo':isVideoRecvEnabled(media)
  1679. };
  1680. } else {
  1681. mediaConstraints = {
  1682. 'mandatory': {
  1683. 'OfferToReceiveAudio':isAudioRecvEnabled(media),
  1684. 'OfferToReceiveVideo':isVideoRecvEnabled(media)
  1685. }
  1686. };
  1687. }
  1688. Janus.debug(mediaConstraints);
  1689. config.pc.createAnswer(
  1690. function(answer) {
  1691. Janus.debug(answer);
  1692. if(config.mySdp === null || config.mySdp === undefined) {
  1693. Janus.log("Setting local description");
  1694. config.mySdp = answer.sdp;
  1695. config.pc.setLocalDescription(answer);
  1696. }
  1697. if(!config.iceDone && !config.trickle) {
  1698. // Don't do anything until we have all candidates
  1699. Janus.log("Waiting for all candidates...");
  1700. return;
  1701. }
  1702. if(config.sdpSent) { // FIXME badly
  1703. Janus.log("Answer already sent, not sending it again");
  1704. return;
  1705. }
  1706. config.sdpSent = true;
  1707. // JSON.stringify doesn't work on some WebRTC objects anymore
  1708. // See https://code.google.com/p/chromium/issues/detail?id=467366
  1709. var jsep = {
  1710. "type": answer.type,
  1711. "sdp": answer.sdp
  1712. };
  1713. callbacks.success(jsep);
  1714. }, callbacks.error, mediaConstraints);
  1715. }
  1716.  
  1717. function sendSDP(handleId, callbacks) {
  1718. callbacks = callbacks || {};
  1719. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : jQuery.noop;
  1720. callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : jQuery.noop;
  1721. var pluginHandle = pluginHandles[handleId];
  1722. if(pluginHandle === null || pluginHandle === undefined ||
  1723. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  1724. Janus.warn("Invalid handle, not sending anything");
  1725. return;
  1726. }
  1727. var config = pluginHandle.webrtcStuff;
  1728. Janus.log("Sending offer/answer SDP...");
  1729. if(config.mySdp === null || config.mySdp === undefined) {
  1730. Janus.warn("Local SDP instance is invalid, not sending anything...");
  1731. return;
  1732. }
  1733. config.mySdp = {
  1734. "type": config.pc.localDescription.type,
  1735. "sdp": config.pc.localDescription.sdp
  1736. };
  1737. if(config.sdpSent) {
  1738. Janus.log("Offer/Answer SDP already sent, not sending it again");
  1739. return;
  1740. }
  1741. if(config.trickle === false)
  1742. config.mySdp["trickle"] = false;
  1743. Janus.debug(callbacks);
  1744. config.sdpSent = true;
  1745. callbacks.success(config.mySdp);
  1746. }
  1747.  
  1748. function getVolume(handleId) {
  1749. var pluginHandle = pluginHandles[handleId];
  1750. if(pluginHandle === null || pluginHandle === undefined ||
  1751. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  1752. Janus.warn("Invalid handle");
  1753. return 0;
  1754. }
  1755. var config = pluginHandle.webrtcStuff;
  1756. // Start getting the volume, if getStats is supported
  1757. if(config.pc.getStats && webrtcDetectedBrowser == "chrome") { // FIXME
  1758. if(config.remoteStream === null || config.remoteStream === undefined) {
  1759. Janus.warn("Remote stream unavailable");
  1760. return 0;
  1761. }
  1762. // http://webrtc.googlecode.com/svn/trunk/samples/js/demos/html/constraints-and-stats.html
  1763. if(config.volume.timer === null || config.volume.timer === undefined) {
  1764. Janus.log("Starting volume monitor");
  1765. config.volume.timer = setInterval(function() {
  1766. config.pc.getStats(function(stats) {
  1767. var results = stats.result();
  1768. for(var i=0; i<results.length; i++) {
  1769. var res = results[i];
  1770. if(res.type == 'ssrc' && res.stat('audioOutputLevel')) {
  1771. config.volume.value = res.stat('audioOutputLevel');
  1772. }
  1773. }
  1774. });
  1775. }, 200);
  1776. return 0; // We don't have a volume to return yet
  1777. }
  1778. return config.volume.value;
  1779. } else {
  1780. Janus.log("Getting the remote volume unsupported by browser");
  1781. return 0;
  1782. }
  1783. }
  1784.  
  1785. function isMuted(handleId, video) {
  1786. var pluginHandle = pluginHandles[handleId];
  1787. if(pluginHandle === null || pluginHandle === undefined ||
  1788. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  1789. Janus.warn("Invalid handle");
  1790. return true;
  1791. }
  1792. var config = pluginHandle.webrtcStuff;
  1793. if(config.pc === null || config.pc === undefined) {
  1794. Janus.warn("Invalid PeerConnection");
  1795. return true;
  1796. }
  1797. if(config.myStream === undefined || config.myStream === null) {
  1798. Janus.warn("Invalid local MediaStream");
  1799. return true;
  1800. }
  1801. if(video) {
  1802. // Check video track
  1803. if(config.myStream.getVideoTracks() === null
  1804. || config.myStream.getVideoTracks() === undefined
  1805. || config.myStream.getVideoTracks().length === 0) {
  1806. Janus.warn("No video track");
  1807. return true;
  1808. }
  1809. return !config.myStream.getVideoTracks()[0].enabled;
  1810. } else {
  1811. // Check audio track
  1812. if(config.myStream.getAudioTracks() === null
  1813. || config.myStream.getAudioTracks() === undefined
  1814. || config.myStream.getAudioTracks().length === 0) {
  1815. Janus.warn("No audio track");
  1816. return true;
  1817. }
  1818. return !config.myStream.getAudioTracks()[0].enabled;
  1819. }
  1820. }
  1821.  
  1822. function mute(handleId, video, mute) {
  1823. var pluginHandle = pluginHandles[handleId];
  1824. if(pluginHandle === null || pluginHandle === undefined ||
  1825. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  1826. Janus.warn("Invalid handle");
  1827. return false;
  1828. }
  1829. var config = pluginHandle.webrtcStuff;
  1830. if(config.pc === null || config.pc === undefined) {
  1831. Janus.warn("Invalid PeerConnection");
  1832. return false;
  1833. }
  1834. if(config.myStream === undefined || config.myStream === null) {
  1835. Janus.warn("Invalid local MediaStream");
  1836. return false;
  1837. }
  1838. if(video) {
  1839. // Mute/unmute video track
  1840. if(config.myStream.getVideoTracks() === null
  1841. || config.myStream.getVideoTracks() === undefined
  1842. || config.myStream.getVideoTracks().length === 0) {
  1843. Janus.warn("No video track");
  1844. return false;
  1845. }
  1846. config.myStream.getVideoTracks()[0].enabled = mute ? false : true;
  1847. return true;
  1848. } else {
  1849. // Mute/unmute audio track
  1850. if(config.myStream.getAudioTracks() === null
  1851. || config.myStream.getAudioTracks() === undefined
  1852. || config.myStream.getAudioTracks().length === 0) {
  1853. Janus.warn("No audio track");
  1854. return false;
  1855. }
  1856. config.myStream.getAudioTracks()[0].enabled = mute ? false : true;
  1857. return true;
  1858. }
  1859. }
  1860.  
  1861. function getBitrate(handleId) {
  1862. var pluginHandle = pluginHandles[handleId];
  1863. if(pluginHandle === null || pluginHandle === undefined ||
  1864. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  1865. Janus.warn("Invalid handle");
  1866. return "Invalid handle";
  1867. }
  1868. var config = pluginHandle.webrtcStuff;
  1869. if(config.pc === null || config.pc === undefined)
  1870. return "Invalid PeerConnection";
  1871. // Start getting the bitrate, if getStats is supported
  1872. if(config.pc.getStats && webrtcDetectedBrowser == "chrome") {
  1873. // Do it the Chrome way
  1874. if(config.remoteStream === null || config.remoteStream === undefined) {
  1875. Janus.warn("Remote stream unavailable");
  1876. return "Remote stream unavailable";
  1877. }
  1878. // http://webrtc.googlecode.com/svn/trunk/samples/js/demos/html/constraints-and-stats.html
  1879. if(config.bitrate.timer === null || config.bitrate.timer === undefined) {
  1880. Janus.log("Starting bitrate timer (Chrome)");
  1881. config.bitrate.timer = setInterval(function() {
  1882. config.pc.getStats(function(stats) {
  1883. var results = stats.result();
  1884. for(var i=0; i<results.length; i++) {
  1885. var res = results[i];
  1886. if(res.type == 'ssrc' && res.stat('googFrameHeightReceived')) {
  1887. config.bitrate.bsnow = res.stat('bytesReceived');
  1888. config.bitrate.tsnow = res.timestamp;
  1889. if(config.bitrate.bsbefore === null || config.bitrate.tsbefore === null) {
  1890. // Skip this round
  1891. config.bitrate.bsbefore = config.bitrate.bsnow;
  1892. config.bitrate.tsbefore = config.bitrate.tsnow;
  1893. } else {
  1894. // Calculate bitrate
  1895. var bitRate = Math.round((config.bitrate.bsnow - config.bitrate.bsbefore) * 8 / (config.bitrate.tsnow - config.bitrate.tsbefore));
  1896. config.bitrate.value = bitRate + ' kbits/sec';
  1897. //~ Janus.log("Estimated bitrate is " + config.bitrate.value);
  1898. config.bitrate.bsbefore = config.bitrate.bsnow;
  1899. config.bitrate.tsbefore = config.bitrate.tsnow;
  1900. }
  1901. }
  1902. }
  1903. });
  1904. }, 1000);
  1905. return "0 kbits/sec"; // We don't have a bitrate value yet
  1906. }
  1907. return config.bitrate.value;
  1908. } else if(config.pc.getStats && webrtcDetectedBrowser == "firefox") {
  1909. // Do it the Firefox way
  1910. if(config.remoteStream === null || config.remoteStream === undefined
  1911. || config.remoteStream.stream === null || config.remoteStream.stream === undefined) {
  1912. Janus.warn("Remote stream unavailable");
  1913. return "Remote stream unavailable";
  1914. }
  1915. var videoTracks = config.remoteStream.stream.getVideoTracks();
  1916. if(videoTracks === null || videoTracks === undefined || videoTracks.length < 1) {
  1917. Janus.warn("No video track");
  1918. return "No video track";
  1919. }
  1920. // https://github.com/muaz-khan/getStats/blob/master/getStats.js
  1921. if(config.bitrate.timer === null || config.bitrate.timer === undefined) {
  1922. Janus.log("Starting bitrate timer (Firefox)");
  1923. config.bitrate.timer = setInterval(function() {
  1924. // We need a helper callback
  1925. var cb = function(res) {
  1926. if(res === null || res === undefined ||
  1927. res.inbound_rtp_video_1 == null || res.inbound_rtp_video_1 == null) {
  1928. config.bitrate.value = "Missing inbound_rtp_video_1";
  1929. return;
  1930. }
  1931. config.bitrate.bsnow = res.inbound_rtp_video_1.bytesReceived;
  1932. config.bitrate.tsnow = res.inbound_rtp_video_1.timestamp;
  1933. if(config.bitrate.bsbefore === null || config.bitrate.tsbefore === null) {
  1934. // Skip this round
  1935. config.bitrate.bsbefore = config.bitrate.bsnow;
  1936. config.bitrate.tsbefore = config.bitrate.tsnow;
  1937. } else {
  1938. // Calculate bitrate
  1939. var bitRate = Math.round((config.bitrate.bsnow - config.bitrate.bsbefore) * 8 / (config.bitrate.tsnow - config.bitrate.tsbefore));
  1940. config.bitrate.value = bitRate + ' kbits/sec';
  1941. config.bitrate.bsbefore = config.bitrate.bsnow;
  1942. config.bitrate.tsbefore = config.bitrate.tsnow;
  1943. }
  1944. };
  1945. // Actually get the stats
  1946. config.pc.getStats(videoTracks[0], function(stats) {
  1947. cb(stats);
  1948. }, cb);
  1949. }, 1000);
  1950. return "0 kbits/sec"; // We don't have a bitrate value yet
  1951. }
  1952. return config.bitrate.value;
  1953. } else {
  1954. Janus.warn("Getting the video bitrate unsupported by browser");
  1955. return "Feature unsupported by browser";
  1956. }
  1957. }
  1958.  
  1959. function webrtcError(error) {
  1960. Janus.error("WebRTC error:", error);
  1961. }
  1962.  
  1963. function cleanupWebrtc(handleId, hangupRequest) {
  1964. Janus.log("Cleaning WebRTC stuff");
  1965. var pluginHandle = pluginHandles[handleId];
  1966. if(pluginHandle === null || pluginHandle === undefined) {
  1967. // Nothing to clean
  1968. return;
  1969. }
  1970. var config = pluginHandle.webrtcStuff;
  1971. if(config !== null && config !== undefined) {
  1972. if(hangupRequest === true) {
  1973. // Send a hangup request (we don't really care about the response)
  1974. var request = { "janus": "hangup", "transaction": randomString(12) };
  1975. if(token !== null && token !== undefined)
  1976. request["token"] = token;
  1977. if(apisecret !== null && apisecret !== undefined)
  1978. request["apisecret"] = apisecret;
  1979. Janus.debug("Sending hangup request (handle=" + handleId + "):");
  1980. Janus.debug(request);
  1981. if(websockets) {
  1982. request["session_id"] = sessionId;
  1983. request["handle_id"] = handleId;
  1984. ws.send(JSON.stringify(request));
  1985. } else {
  1986. $.ajax({
  1987. type: 'POST',
  1988. url: server + "/" + sessionId + "/" + handleId,
  1989. cache: false,
  1990. contentType: "application/json",
  1991. data: JSON.stringify(request),
  1992. dataType: "json"
  1993. });
  1994. }
  1995. }
  1996. // Cleanup stack
  1997. config.remoteStream = null;
  1998. if(config.volume.timer)
  1999. clearInterval(config.volume.timer);
  2000. config.volume.value = null;
  2001. if(config.bitrate.timer)
  2002. clearInterval(config.bitrate.timer);
  2003. config.bitrate.timer = null;
  2004. config.bitrate.bsnow = null;
  2005. config.bitrate.bsbefore = null;
  2006. config.bitrate.tsnow = null;
  2007. config.bitrate.tsbefore = null;
  2008. config.bitrate.value = null;
  2009. try {
  2010. // Try a MediaStream.stop() first
  2011. if(!config.streamExternal && config.myStream !== null && config.myStream !== undefined) {
  2012. Janus.log("Stopping local stream");
  2013. config.myStream.stop();
  2014. }
  2015. } catch(e) {
  2016. // Do nothing if this fails
  2017. }
  2018. try {
  2019. // Try a MediaStreamTrack.stop() for each track as well
  2020. if(!config.streamExternal && config.myStream !== null && config.myStream !== undefined) {
  2021. Janus.log("Stopping local stream tracks");
  2022. var tracks = config.myStream.getTracks();
  2023. for(var i in tracks) {
  2024. var mst = tracks[i];
  2025. Janus.log(mst);
  2026. if(mst !== null && mst !== undefined)
  2027. mst.stop();
  2028. }
  2029. }
  2030. } catch(e) {
  2031. // Do nothing if this fails
  2032. }
  2033. config.streamExternal = false;
  2034. config.myStream = null;
  2035. // Close PeerConnection
  2036. try {
  2037. config.pc.close();
  2038. } catch(e) {
  2039. // Do nothing
  2040. }
  2041. config.pc = null;
  2042. config.mySdp = null;
  2043. config.iceDone = false;
  2044. config.sdpSent = false;
  2045. config.dataChannel = null;
  2046. config.dtmfSender = null;
  2047. }
  2048. pluginHandle.oncleanup();
  2049. }
  2050.  
  2051. // Helper methods to parse a media object
  2052. function isAudioSendEnabled(media) {
  2053. Janus.debug("isAudioSendEnabled:", media);
  2054. if(media === undefined || media === null)
  2055. return true; // Default
  2056. if(media.audio === false)
  2057. return false; // Generic audio has precedence
  2058. if(media.audioSend === undefined || media.audioSend === null)
  2059. return true; // Default
  2060. return (media.audioSend === true);
  2061. }
  2062.  
  2063. function isAudioRecvEnabled(media) {
  2064. Janus.debug("isAudioRecvEnabled:", media);
  2065. if(media === undefined || media === null)
  2066. return true; // Default
  2067. if(media.audio === false)
  2068. return false; // Generic audio has precedence
  2069. if(media.audioRecv === undefined || media.audioRecv === null)
  2070. return true; // Default
  2071. return (media.audioRecv === true);
  2072. }
  2073.  
  2074. function isVideoSendEnabled(media) {
  2075. Janus.debug("isVideoSendEnabled:", media);
  2076. if(webrtcDetectedBrowser == "edge") {
  2077. Janus.warn("Edge doesn't support compatible video yet");
  2078. return false;
  2079. }
  2080. if(media === undefined || media === null)
  2081. return true; // Default
  2082. if(media.video === false)
  2083. return false; // Generic video has precedence
  2084. if(media.videoSend === undefined || media.videoSend === null)
  2085. return true; // Default
  2086. return (media.videoSend === true);
  2087. }
  2088.  
  2089. function isVideoRecvEnabled(media) {
  2090. Janus.debug("isVideoRecvEnabled:", media);
  2091. if(webrtcDetectedBrowser == "edge") {
  2092. Janus.warn("Edge doesn't support compatible video yet");
  2093. return false;
  2094. }
  2095. if(media === undefined || media === null)
  2096. return true; // Default
  2097. if(media.video === false)
  2098. return false; // Generic video has precedence
  2099. if(media.videoRecv === undefined || media.videoRecv === null)
  2100. return true; // Default
  2101. return (media.videoRecv === true);
  2102. }
  2103.  
  2104. function isDataEnabled(media) {
  2105. Janus.debug("isDataEnabled:", media);
  2106. if(webrtcDetectedBrowser == "edge") {
  2107. Janus.warn("Edge doesn't support data channels yet");
  2108. return false;
  2109. }
  2110. if(media === undefined || media === null)
  2111. return false; // Default
  2112. return (media.data === true);
  2113. }
  2114.  
  2115. function isTrickleEnabled(trickle) {
  2116. Janus.debug("isTrickleEnabled:", trickle);
  2117. if(trickle === undefined || trickle === null)
  2118. return true; // Default is true
  2119. return (trickle === true);
  2120. }
  2121. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement