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