janus.js 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505
  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. Janus.isExtensionEnabled = function() {
  23. if(navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia) {
  24. // No need for the extension, getDisplayMedia is supported
  25. return true;
  26. }
  27. if(window.navigator.userAgent.match('Chrome')) {
  28. var chromever = parseInt(window.navigator.userAgent.match(/Chrome\/(.*) /)[1], 10);
  29. var maxver = 33;
  30. if(window.navigator.userAgent.match('Linux'))
  31. maxver = 35; // "known" crash in chrome 34 and 35 on linux
  32. if(chromever >= 26 && chromever <= maxver) {
  33. // Older versions of Chrome don't support this extension-based approach, so lie
  34. return true;
  35. }
  36. return Janus.extension.isInstalled();
  37. } else {
  38. // Firefox of others, no need for the extension (but this doesn't mean it will work)
  39. return true;
  40. }
  41. };
  42. var defaultExtension = {
  43. // Screensharing Chrome Extension ID
  44. extensionId: 'hapfgfdkleiggjjpfpenajgdnfckjpaj',
  45. isInstalled: function() { return document.querySelector('#janus-extension-installed') !== null; },
  46. getScreen: function (callback) {
  47. var pending = window.setTimeout(function () {
  48. var error = new Error('NavigatorUserMediaError');
  49. 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)';
  50. return callback(error);
  51. }, 1000);
  52. this.cache[pending] = callback;
  53. window.postMessage({ type: 'janusGetScreen', id: pending }, '*');
  54. },
  55. init: function () {
  56. var cache = {};
  57. this.cache = cache;
  58. // Wait for events from the Chrome Extension
  59. window.addEventListener('message', function (event) {
  60. if(event.origin != window.location.origin)
  61. return;
  62. if(event.data.type == 'janusGotScreen' && cache[event.data.id]) {
  63. var callback = cache[event.data.id];
  64. delete cache[event.data.id];
  65. if (event.data.sourceId === '') {
  66. // user canceled
  67. var error = new Error('NavigatorUserMediaError');
  68. error.name = 'You cancelled the request for permission, giving up...';
  69. callback(error);
  70. } else {
  71. callback(null, event.data.sourceId);
  72. }
  73. } else if (event.data.type == 'janusGetScreenPending') {
  74. console.log('clearing ', event.data.id);
  75. window.clearTimeout(event.data.id);
  76. }
  77. });
  78. }
  79. };
  80. Janus.useDefaultDependencies = function (deps) {
  81. var f = (deps && deps.fetch) || fetch;
  82. var p = (deps && deps.Promise) || Promise;
  83. var socketCls = (deps && deps.WebSocket) || WebSocket;
  84. return {
  85. newWebSocket: function(server, proto) { return new socketCls(server, proto); },
  86. extension: (deps && deps.extension) || defaultExtension,
  87. isArray: function(arr) { return Array.isArray(arr); },
  88. webRTCAdapter: (deps && deps.adapter) || adapter,
  89. httpAPICall: function(url, options) {
  90. var fetchOptions = {
  91. method: options.verb,
  92. headers: {
  93. 'Accept': 'application/json, text/plain, */*'
  94. },
  95. cache: 'no-cache'
  96. };
  97. if(options.verb === "POST") {
  98. fetchOptions.headers['Content-Type'] = 'application/json';
  99. }
  100. if(options.withCredentials !== undefined) {
  101. fetchOptions.credentials = options.withCredentials === true ? 'include' : (options.withCredentials ? options.withCredentials : 'omit');
  102. }
  103. if(options.body !== undefined) {
  104. fetchOptions.body = JSON.stringify(options.body);
  105. }
  106. var fetching = f(url, fetchOptions).catch(function(error) {
  107. return p.reject({message: 'Probably a network error, is the server down?', error: error});
  108. });
  109. /*
  110. * fetch() does not natively support timeouts.
  111. * Work around this by starting a timeout manually, and racing it agains the fetch() to see which thing resolves first.
  112. */
  113. if(options.timeout !== undefined) {
  114. var timeout = new p(function(resolve, reject) {
  115. var timerId = setTimeout(function() {
  116. clearTimeout(timerId);
  117. return reject({message: 'Request timed out', timeout: options.timeout});
  118. }, options.timeout);
  119. });
  120. fetching = p.race([fetching,timeout]);
  121. }
  122. fetching.then(function(response) {
  123. if(response.ok) {
  124. if(typeof(options.success) === typeof(Janus.noop)) {
  125. return response.json().then(function(parsed) {
  126. options.success(parsed);
  127. }).catch(function(error) {
  128. return p.reject({message: 'Failed to parse response body', error: error, response: response});
  129. });
  130. }
  131. }
  132. else {
  133. return p.reject({message: 'API call failed', response: response});
  134. }
  135. }).catch(function(error) {
  136. if(typeof(options.error) === typeof(Janus.noop)) {
  137. options.error(error.message || '<< internal error >>', error);
  138. }
  139. });
  140. return fetching;
  141. }
  142. }
  143. };
  144. Janus.useOldDependencies = function (deps) {
  145. var jq = (deps && deps.jQuery) || jQuery;
  146. var socketCls = (deps && deps.WebSocket) || WebSocket;
  147. return {
  148. newWebSocket: function(server, proto) { return new socketCls(server, proto); },
  149. isArray: function(arr) { return jq.isArray(arr); },
  150. extension: (deps && deps.extension) || defaultExtension,
  151. webRTCAdapter: (deps && deps.adapter) || adapter,
  152. httpAPICall: function(url, options) {
  153. var payload = options.body !== undefined ? {
  154. contentType: 'application/json',
  155. data: JSON.stringify(options.body)
  156. } : {};
  157. var credentials = options.withCredentials !== undefined ? {xhrFields: {withCredentials: options.withCredentials}} : {};
  158. return jq.ajax(jq.extend(payload, credentials, {
  159. url: url,
  160. type: options.verb,
  161. cache: false,
  162. dataType: 'json',
  163. async: options.async,
  164. timeout: options.timeout,
  165. success: function(result) {
  166. if(typeof(options.success) === typeof(Janus.noop)) {
  167. options.success(result);
  168. }
  169. },
  170. error: function(xhr, status, err) {
  171. if(typeof(options.error) === typeof(Janus.noop)) {
  172. options.error(status, err);
  173. }
  174. }
  175. }));
  176. },
  177. };
  178. };
  179. Janus.noop = function() {};
  180. Janus.dataChanDefaultLabel = "JanusDataChannel";
  181. // Note: in the future we may want to change this, e.g., as was
  182. // attempted in https://github.com/meetecho/janus-gateway/issues/1670
  183. Janus.endOfCandidates = null;
  184. // Initialization
  185. Janus.init = function(options) {
  186. options = options || {};
  187. options.callback = (typeof options.callback == "function") ? options.callback : Janus.noop;
  188. if(Janus.initDone === true) {
  189. // Already initialized
  190. options.callback();
  191. } else {
  192. if(typeof console == "undefined" || typeof console.log == "undefined")
  193. console = { log: function() {} };
  194. // Console logging (all debugging disabled by default)
  195. Janus.trace = Janus.noop;
  196. Janus.debug = Janus.noop;
  197. Janus.vdebug = Janus.noop;
  198. Janus.log = Janus.noop;
  199. Janus.warn = Janus.noop;
  200. Janus.error = Janus.noop;
  201. if(options.debug === true || options.debug === "all") {
  202. // Enable all debugging levels
  203. Janus.trace = console.trace.bind(console);
  204. Janus.debug = console.debug.bind(console);
  205. Janus.vdebug = console.debug.bind(console);
  206. Janus.log = console.log.bind(console);
  207. Janus.warn = console.warn.bind(console);
  208. Janus.error = console.error.bind(console);
  209. } else if(Array.isArray(options.debug)) {
  210. for(var i in options.debug) {
  211. var d = options.debug[i];
  212. switch(d) {
  213. case "trace":
  214. Janus.trace = console.trace.bind(console);
  215. break;
  216. case "debug":
  217. Janus.debug = console.debug.bind(console);
  218. break;
  219. case "vdebug":
  220. Janus.vdebug = console.debug.bind(console);
  221. break;
  222. case "log":
  223. Janus.log = console.log.bind(console);
  224. break;
  225. case "warn":
  226. Janus.warn = console.warn.bind(console);
  227. break;
  228. case "error":
  229. Janus.error = console.error.bind(console);
  230. break;
  231. default:
  232. console.error("Unknown debugging option '" + d + "' (supported: 'trace', 'debug', 'vdebug', 'log', warn', 'error')");
  233. break;
  234. }
  235. }
  236. }
  237. var usedDependencies = options.dependencies || Janus.useDefaultDependencies();
  238. Janus.isArray = usedDependencies.isArray;
  239. Janus.webRTCAdapter = usedDependencies.webRTCAdapter;
  240. Janus.httpAPICall = usedDependencies.httpAPICall;
  241. Janus.newWebSocket = usedDependencies.newWebSocket;
  242. Janus.extension = usedDependencies.extension;
  243. Janus.extension.init();
  244. // Helper method to enumerate devices
  245. Janus.listDevices = function(callback, config) {
  246. callback = (typeof callback == "function") ? callback : Janus.noop;
  247. if (config == null) config = { audio: true, video: true };
  248. if(Janus.isGetUserMediaAvailable()) {
  249. navigator.mediaDevices.getUserMedia(config)
  250. .then(function(stream) {
  251. navigator.mediaDevices.enumerateDevices().then(function(devices) {
  252. Janus.debug(devices);
  253. callback(devices);
  254. // Get rid of the now useless stream
  255. try {
  256. var tracks = stream.getTracks();
  257. for(var i in tracks) {
  258. var mst = tracks[i];
  259. if(mst !== null && mst !== undefined)
  260. mst.stop();
  261. }
  262. } catch(e) {}
  263. });
  264. })
  265. .catch(function(err) {
  266. Janus.error(err);
  267. callback([]);
  268. });
  269. } else {
  270. Janus.warn("navigator.mediaDevices unavailable");
  271. callback([]);
  272. }
  273. }
  274. // Helper methods to attach/reattach a stream to a video element (previously part of adapter.js)
  275. Janus.attachMediaStream = function(element, stream) {
  276. if(Janus.webRTCAdapter.browserDetails.browser === 'chrome') {
  277. var chromever = Janus.webRTCAdapter.browserDetails.version;
  278. if(chromever >= 52) {
  279. element.srcObject = stream;
  280. } else if(typeof element.src !== 'undefined') {
  281. element.src = URL.createObjectURL(stream);
  282. } else {
  283. Janus.error("Error attaching stream to element");
  284. }
  285. } else {
  286. element.srcObject = stream;
  287. }
  288. };
  289. Janus.reattachMediaStream = function(to, from) {
  290. if(Janus.webRTCAdapter.browserDetails.browser === 'chrome') {
  291. var chromever = Janus.webRTCAdapter.browserDetails.version;
  292. if(chromever >= 52) {
  293. to.srcObject = from.srcObject;
  294. } else if(typeof to.src !== 'undefined') {
  295. to.src = from.src;
  296. } else {
  297. Janus.error("Error reattaching stream to element");
  298. }
  299. } else {
  300. to.srcObject = from.srcObject;
  301. }
  302. };
  303. // Detect tab close: make sure we don't loose existing onbeforeunload handlers
  304. // (note: for iOS we need to subscribe to a different event, 'pagehide', see
  305. // https://gist.github.com/thehunmonkgroup/6bee8941a49b86be31a787fe8f4b8cfe)
  306. var iOS = ['iPad', 'iPhone', 'iPod'].indexOf(navigator.platform) >= 0;
  307. var eventName = iOS ? 'pagehide' : 'beforeunload';
  308. var oldOBF = window["on" + eventName];
  309. window.addEventListener(eventName, function(event) {
  310. Janus.log("Closing window");
  311. for(var s in Janus.sessions) {
  312. if(Janus.sessions[s] !== null && Janus.sessions[s] !== undefined &&
  313. Janus.sessions[s].destroyOnUnload) {
  314. Janus.log("Destroying session " + s);
  315. Janus.sessions[s].destroy({asyncRequest: false, notifyDestroyed: false});
  316. }
  317. }
  318. if(oldOBF && typeof oldOBF == "function")
  319. oldOBF();
  320. });
  321. // If this is a Safari Technology Preview, check if VP8 is supported
  322. Janus.safariVp8 = false;
  323. if(Janus.webRTCAdapter.browserDetails.browser === 'safari' &&
  324. Janus.webRTCAdapter.browserDetails.version >= 605) {
  325. // Let's see if RTCRtpSender.getCapabilities() is there
  326. if(RTCRtpSender && RTCRtpSender.getCapabilities && RTCRtpSender.getCapabilities("video") &&
  327. RTCRtpSender.getCapabilities("video").codecs && RTCRtpSender.getCapabilities("video").codecs.length) {
  328. for(var i in RTCRtpSender.getCapabilities("video").codecs) {
  329. var codec = RTCRtpSender.getCapabilities("video").codecs[i];
  330. if(codec && codec.mimeType && codec.mimeType.toLowerCase() === "video/vp8") {
  331. Janus.safariVp8 = true;
  332. break;
  333. }
  334. }
  335. if(Janus.safariVp8) {
  336. Janus.log("This version of Safari supports VP8");
  337. } else {
  338. Janus.warn("This version of Safari does NOT support VP8: if you're using a Technology Preview, " +
  339. "try enabling the 'WebRTC VP8 codec' setting in the 'Experimental Features' Develop menu");
  340. }
  341. } else {
  342. // We do it in a very ugly way, as there's no alternative...
  343. // We create a PeerConnection to see if VP8 is in an offer
  344. var testpc = new RTCPeerConnection({}, {});
  345. testpc.createOffer({offerToReceiveVideo: true}).then(function(offer) {
  346. Janus.safariVp8 = offer.sdp.indexOf("VP8") !== -1;
  347. if(Janus.safariVp8) {
  348. Janus.log("This version of Safari supports VP8");
  349. } else {
  350. Janus.warn("This version of Safari does NOT support VP8: if you're using a Technology Preview, " +
  351. "try enabling the 'WebRTC VP8 codec' setting in the 'Experimental Features' Develop menu");
  352. }
  353. testpc.close();
  354. testpc = null;
  355. });
  356. }
  357. }
  358. // Check if this browser supports Unified Plan and transceivers
  359. // Based on https://codepen.io/anon/pen/ZqLwWV?editors=0010
  360. Janus.unifiedPlan = false;
  361. if(Janus.webRTCAdapter.browserDetails.browser === 'firefox' &&
  362. Janus.webRTCAdapter.browserDetails.version >= 59) {
  363. // Firefox definitely does, starting from version 59
  364. Janus.unifiedPlan = true;
  365. } else if(Janus.webRTCAdapter.browserDetails.browser === 'chrome' &&
  366. Janus.webRTCAdapter.browserDetails.version < 72) {
  367. // Chrome does, but it's only usable from version 72 on
  368. Janus.unifiedPlan = false;
  369. } else if(!('currentDirection' in RTCRtpTransceiver.prototype)) {
  370. // Safari supports addTransceiver() but not Unified Plan when
  371. // currentDirection is not defined (see codepen above)
  372. Janus.unifiedPlan = false;
  373. } else {
  374. // Check if addTransceiver() throws an exception
  375. const tempPc = new RTCPeerConnection();
  376. try {
  377. tempPc.addTransceiver('audio');
  378. Janus.unifiedPlan = true;
  379. } catch (e) {}
  380. tempPc.close();
  381. }
  382. Janus.initDone = true;
  383. options.callback();
  384. }
  385. };
  386. // Helper method to check whether WebRTC is supported by this browser
  387. Janus.isWebrtcSupported = function() {
  388. return window.RTCPeerConnection !== undefined && window.RTCPeerConnection !== null;
  389. };
  390. // Helper method to check whether devices can be accessed by this browser (e.g., not possible via plain HTTP)
  391. Janus.isGetUserMediaAvailable = function() {
  392. return navigator.mediaDevices !== undefined && navigator.mediaDevices !== null &&
  393. navigator.mediaDevices.getUserMedia !== undefined && navigator.mediaDevices.getUserMedia !== null;
  394. };
  395. // Helper method to create random identifiers (e.g., transaction)
  396. Janus.randomString = function(len) {
  397. var charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  398. var randomString = '';
  399. for (var i = 0; i < len; i++) {
  400. var randomPoz = Math.floor(Math.random() * charSet.length);
  401. randomString += charSet.substring(randomPoz,randomPoz+1);
  402. }
  403. return randomString;
  404. }
  405. function Janus(gatewayCallbacks) {
  406. if(Janus.initDone === undefined) {
  407. gatewayCallbacks.error("Library not initialized");
  408. return {};
  409. }
  410. if(!Janus.isWebrtcSupported()) {
  411. gatewayCallbacks.error("WebRTC not supported by this browser");
  412. return {};
  413. }
  414. Janus.log("Library initialized: " + Janus.initDone);
  415. gatewayCallbacks = gatewayCallbacks || {};
  416. gatewayCallbacks.success = (typeof gatewayCallbacks.success == "function") ? gatewayCallbacks.success : Janus.noop;
  417. gatewayCallbacks.error = (typeof gatewayCallbacks.error == "function") ? gatewayCallbacks.error : Janus.noop;
  418. gatewayCallbacks.destroyed = (typeof gatewayCallbacks.destroyed == "function") ? gatewayCallbacks.destroyed : Janus.noop;
  419. if(gatewayCallbacks.server === null || gatewayCallbacks.server === undefined) {
  420. gatewayCallbacks.error("Invalid server url");
  421. return {};
  422. }
  423. var websockets = false;
  424. var ws = null;
  425. var wsHandlers = {};
  426. var wsKeepaliveTimeoutId = null;
  427. var servers = null, serversIndex = 0;
  428. var server = gatewayCallbacks.server;
  429. if(Janus.isArray(server)) {
  430. Janus.log("Multiple servers provided (" + server.length + "), will use the first that works");
  431. server = null;
  432. servers = gatewayCallbacks.server;
  433. Janus.debug(servers);
  434. } else {
  435. if(server.indexOf("ws") === 0) {
  436. websockets = true;
  437. Janus.log("Using WebSockets to contact Janus: " + server);
  438. } else {
  439. websockets = false;
  440. Janus.log("Using REST API to contact Janus: " + server);
  441. }
  442. }
  443. var iceServers = gatewayCallbacks.iceServers;
  444. if(iceServers === undefined || iceServers === null)
  445. iceServers = [{urls: "stun:stun.l.google.com:19302"}];
  446. var iceTransportPolicy = gatewayCallbacks.iceTransportPolicy;
  447. var bundlePolicy = gatewayCallbacks.bundlePolicy;
  448. // Whether IPv6 candidates should be gathered
  449. var ipv6Support = gatewayCallbacks.ipv6;
  450. if(ipv6Support === undefined || ipv6Support === null)
  451. ipv6Support = false;
  452. // Whether we should enable the withCredentials flag for XHR requests
  453. var withCredentials = false;
  454. if(gatewayCallbacks.withCredentials !== undefined && gatewayCallbacks.withCredentials !== null)
  455. withCredentials = gatewayCallbacks.withCredentials === true;
  456. // Optional max events
  457. var maxev = 10;
  458. if(gatewayCallbacks.max_poll_events !== undefined && gatewayCallbacks.max_poll_events !== null)
  459. maxev = gatewayCallbacks.max_poll_events;
  460. if(maxev < 1)
  461. maxev = 1;
  462. // Token to use (only if the token based authentication mechanism is enabled)
  463. var token = null;
  464. if(gatewayCallbacks.token !== undefined && gatewayCallbacks.token !== null)
  465. token = gatewayCallbacks.token;
  466. // API secret to use (only if the shared API secret is enabled)
  467. var apisecret = null;
  468. if(gatewayCallbacks.apisecret !== undefined && gatewayCallbacks.apisecret !== null)
  469. apisecret = gatewayCallbacks.apisecret;
  470. // Whether we should destroy this session when onbeforeunload is called
  471. this.destroyOnUnload = true;
  472. if(gatewayCallbacks.destroyOnUnload !== undefined && gatewayCallbacks.destroyOnUnload !== null)
  473. this.destroyOnUnload = (gatewayCallbacks.destroyOnUnload === true);
  474. // Some timeout-related values
  475. var keepAlivePeriod = 25000;
  476. if(gatewayCallbacks.keepAlivePeriod !== undefined && gatewayCallbacks.keepAlivePeriod !== null)
  477. keepAlivePeriod = gatewayCallbacks.keepAlivePeriod;
  478. if(isNaN(keepAlivePeriod))
  479. keepAlivePeriod = 25000;
  480. var longPollTimeout = 60000;
  481. if(gatewayCallbacks.longPollTimeout !== undefined && gatewayCallbacks.longPollTimeout !== null)
  482. longPollTimeout = gatewayCallbacks.longPollTimeout;
  483. if(isNaN(longPollTimeout))
  484. longPollTimeout = 60000;
  485. // overrides for default maxBitrate values for simulcasting
  486. function getMaxBitrates(simulcastMaxBitrates) {
  487. var maxBitrates = {
  488. high: 900000,
  489. medium: 300000,
  490. low: 100000,
  491. };
  492. if (simulcastMaxBitrates !== undefined && simulcastMaxBitrates !== null) {
  493. if (simulcastMaxBitrates.high)
  494. maxBitrates.high = simulcastMaxBitrates.high;
  495. if (simulcastMaxBitrates.medium)
  496. maxBitrates.medium = simulcastMaxBitrates.medium;
  497. if (simulcastMaxBitrates.low)
  498. maxBitrates.low = simulcastMaxBitrates.low;
  499. }
  500. return maxBitrates;
  501. }
  502. var connected = false;
  503. var sessionId = null;
  504. var pluginHandles = {};
  505. var that = this;
  506. var retries = 0;
  507. var transactions = {};
  508. createSession(gatewayCallbacks);
  509. // Public methods
  510. this.getServer = function() { return server; };
  511. this.isConnected = function() { return connected; };
  512. this.reconnect = function(callbacks) {
  513. callbacks = callbacks || {};
  514. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
  515. callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : Janus.noop;
  516. callbacks["reconnect"] = true;
  517. createSession(callbacks);
  518. };
  519. this.getSessionId = function() { return sessionId; };
  520. this.destroy = function(callbacks) { destroySession(callbacks); };
  521. this.attach = function(callbacks) { createHandle(callbacks); };
  522. function eventHandler() {
  523. if(sessionId == null)
  524. return;
  525. Janus.debug('Long poll...');
  526. if(!connected) {
  527. Janus.warn("Is the server down? (connected=false)");
  528. return;
  529. }
  530. var longpoll = server + "/" + sessionId + "?rid=" + new Date().getTime();
  531. if(maxev !== undefined && maxev !== null)
  532. longpoll = longpoll + "&maxev=" + maxev;
  533. if(token !== null && token !== undefined)
  534. longpoll = longpoll + "&token=" + encodeURIComponent(token);
  535. if(apisecret !== null && apisecret !== undefined)
  536. longpoll = longpoll + "&apisecret=" + encodeURIComponent(apisecret);
  537. Janus.httpAPICall(longpoll, {
  538. verb: 'GET',
  539. withCredentials: withCredentials,
  540. success: handleEvent,
  541. timeout: longPollTimeout,
  542. error: function(textStatus, errorThrown) {
  543. Janus.error(textStatus + ":", errorThrown);
  544. retries++;
  545. if(retries > 3) {
  546. // Did we just lose the server? :-(
  547. connected = false;
  548. gatewayCallbacks.error("Lost connection to the server (is it down?)");
  549. return;
  550. }
  551. eventHandler();
  552. }
  553. });
  554. }
  555. // Private event handler: this will trigger plugin callbacks, if set
  556. function handleEvent(json, skipTimeout) {
  557. retries = 0;
  558. if(!websockets && sessionId !== undefined && sessionId !== null && skipTimeout !== true)
  559. eventHandler();
  560. if(!websockets && Janus.isArray(json)) {
  561. // We got an array: it means we passed a maxev > 1, iterate on all objects
  562. for(var i=0; i<json.length; i++) {
  563. handleEvent(json[i], true);
  564. }
  565. return;
  566. }
  567. if(json["rtcgw"] === "keepalive") {
  568. // Nothing happened
  569. Janus.vdebug("Got a keepalive on session " + sessionId);
  570. return;
  571. } else if(json["rtcgw"] === "ack") {
  572. // Just an ack, we can probably ignore
  573. Janus.debug("Got an ack on session " + sessionId);
  574. Janus.debug(json);
  575. var transaction = json["transaction"];
  576. if(transaction !== null && transaction !== undefined) {
  577. var reportSuccess = transactions[transaction];
  578. if(reportSuccess !== null && reportSuccess !== undefined) {
  579. reportSuccess(json);
  580. }
  581. delete transactions[transaction];
  582. }
  583. return;
  584. } else if(json["rtcgw"] === "success") {
  585. // Success!
  586. Janus.debug("Got a success on session " + sessionId);
  587. Janus.debug(json);
  588. var transaction = json["transaction"];
  589. if(transaction !== null && transaction !== undefined) {
  590. var reportSuccess = transactions[transaction];
  591. if(reportSuccess !== null && reportSuccess !== undefined) {
  592. reportSuccess(json);
  593. }
  594. delete transactions[transaction];
  595. }
  596. return;
  597. } else if(json["rtcgw"] === "trickle") {
  598. // We got a trickle candidate from Janus
  599. var sender = json["sender"];
  600. if(sender === undefined || sender === null) {
  601. Janus.warn("Missing sender...");
  602. return;
  603. }
  604. var pluginHandle = pluginHandles[sender];
  605. if(pluginHandle === undefined || pluginHandle === null) {
  606. Janus.debug("This handle is not attached to this session");
  607. return;
  608. }
  609. var candidate = json["candidate"];
  610. Janus.debug("Got a trickled candidate on session " + sessionId);
  611. Janus.debug(candidate);
  612. var config = pluginHandle.webrtcStuff;
  613. if(config.pc && config.remoteSdp) {
  614. // Add candidate right now
  615. Janus.debug("Adding remote candidate:", candidate);
  616. if(!candidate || candidate.completed === true) {
  617. // end-of-candidates
  618. config.pc.addIceCandidate(Janus.endOfCandidates);
  619. } else {
  620. // New candidate
  621. config.pc.addIceCandidate(candidate);
  622. }
  623. } else {
  624. // We didn't do setRemoteDescription (trickle got here before the offer?)
  625. Janus.debug("We didn't do setRemoteDescription (trickle got here before the offer?), caching candidate");
  626. if(!config.candidates)
  627. config.candidates = [];
  628. config.candidates.push(candidate);
  629. Janus.debug(config.candidates);
  630. }
  631. } else if(json["rtcgw"] === "webrtcup") {
  632. // The PeerConnection with the server is up! Notify this
  633. Janus.debug("Got a webrtcup event on session " + sessionId);
  634. Janus.debug(json);
  635. var sender = json["sender"];
  636. if(sender === undefined || sender === null) {
  637. Janus.warn("Missing sender...");
  638. return;
  639. }
  640. var pluginHandle = pluginHandles[sender];
  641. if(pluginHandle === undefined || pluginHandle === null) {
  642. Janus.debug("This handle is not attached to this session");
  643. return;
  644. }
  645. pluginHandle.webrtcState(true);
  646. return;
  647. } else if(json["rtcgw"] === "hangup") {
  648. // A plugin asked the core to hangup a PeerConnection on one of our handles
  649. Janus.debug("Got a hangup event on session " + sessionId);
  650. Janus.debug(json);
  651. var sender = json["sender"];
  652. if(sender === undefined || sender === null) {
  653. Janus.warn("Missing sender...");
  654. return;
  655. }
  656. var pluginHandle = pluginHandles[sender];
  657. if(pluginHandle === undefined || pluginHandle === null) {
  658. Janus.debug("This handle is not attached to this session");
  659. return;
  660. }
  661. pluginHandle.webrtcState(false, json["reason"]);
  662. pluginHandle.hangup();
  663. } else if(json["rtcgw"] === "detached") {
  664. // A plugin asked the core to detach one of our handles
  665. Janus.debug("Got a detached event on session " + sessionId);
  666. Janus.debug(json);
  667. var sender = json["sender"];
  668. if(sender === undefined || sender === null) {
  669. Janus.warn("Missing sender...");
  670. return;
  671. }
  672. var pluginHandle = pluginHandles[sender];
  673. if(pluginHandle === undefined || pluginHandle === null) {
  674. // Don't warn here because destroyHandle causes this situation.
  675. return;
  676. }
  677. pluginHandle.detached = true;
  678. pluginHandle.ondetached();
  679. pluginHandle.detach();
  680. } else if(json["rtcgw"] === "media") {
  681. // Media started/stopped flowing
  682. Janus.debug("Got a media event on session " + sessionId);
  683. Janus.debug(json);
  684. var sender = json["sender"];
  685. if(sender === undefined || sender === null) {
  686. Janus.warn("Missing sender...");
  687. return;
  688. }
  689. var pluginHandle = pluginHandles[sender];
  690. if(pluginHandle === undefined || pluginHandle === null) {
  691. Janus.debug("This handle is not attached to this session");
  692. return;
  693. }
  694. pluginHandle.mediaState(json["type"], json["receiving"]);
  695. } else if(json["rtcgw"] === "slowlink") {
  696. Janus.debug("Got a slowlink event on session " + sessionId);
  697. Janus.debug(json);
  698. // Trouble uplink or downlink
  699. var sender = json["sender"];
  700. if(sender === undefined || sender === null) {
  701. Janus.warn("Missing sender...");
  702. return;
  703. }
  704. var pluginHandle = pluginHandles[sender];
  705. if(pluginHandle === undefined || pluginHandle === null) {
  706. Janus.debug("This handle is not attached to this session");
  707. return;
  708. }
  709. pluginHandle.slowLink(json["uplink"], json["lost"]);
  710. } else if(json["rtcgw"] === "error") {
  711. // Oops, something wrong happened
  712. Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
  713. Janus.debug(json);
  714. var transaction = json["transaction"];
  715. if(transaction !== null && transaction !== undefined) {
  716. var reportSuccess = transactions[transaction];
  717. if(reportSuccess !== null && reportSuccess !== undefined) {
  718. reportSuccess(json);
  719. }
  720. delete transactions[transaction];
  721. }
  722. return;
  723. } else if(json["rtcgw"] === "event") {
  724. Janus.debug("Got a plugin event on session " + sessionId);
  725. Janus.debug(json);
  726. var sender = json["sender"];
  727. if(sender === undefined || sender === null) {
  728. Janus.warn("Missing sender...");
  729. return;
  730. }
  731. var plugindata = json["plugindata"];
  732. if(plugindata === undefined || plugindata === null) {
  733. Janus.warn("Missing plugindata...");
  734. return;
  735. }
  736. Janus.debug(" -- Event is coming from " + sender + " (" + plugindata["plugin"] + ")");
  737. var data = plugindata["data"];
  738. Janus.debug(data);
  739. var pluginHandle = pluginHandles[sender];
  740. if(pluginHandle === undefined || pluginHandle === null) {
  741. Janus.warn("This handle is not attached to this session");
  742. return;
  743. }
  744. var jsep = json["jsep"];
  745. if(jsep !== undefined && jsep !== null) {
  746. Janus.debug("Handling SDP as well...");
  747. Janus.debug(jsep);
  748. }
  749. var callback = pluginHandle.onmessage;
  750. if(callback !== null && callback !== undefined) {
  751. Janus.debug("Notifying application...");
  752. // Send to callback specified when attaching plugin handle
  753. callback(data, jsep);
  754. } else {
  755. // Send to generic callback (?)
  756. Janus.debug("No provided notification callback");
  757. }
  758. } else if(json["rtcgw"] === "timeout") {
  759. Janus.error("Timeout on session " + sessionId);
  760. Janus.debug(json);
  761. if (websockets) {
  762. ws.close(3504, "Gateway timeout");
  763. }
  764. return;
  765. } else {
  766. Janus.warn("Unknown message/event '" + json["rtcgw"] + "' on session " + sessionId);
  767. Janus.debug(json);
  768. }
  769. }
  770. // Private helper to send keep-alive messages on WebSockets
  771. function keepAlive() {
  772. if(server === null || !websockets || !connected)
  773. return;
  774. wsKeepaliveTimeoutId = setTimeout(keepAlive, keepAlivePeriod);
  775. var request = { "rtcgw": "keepalive", "session_id": sessionId, "transaction": Janus.randomString(12) };
  776. if(token !== null && token !== undefined)
  777. request["token"] = token;
  778. if(apisecret !== null && apisecret !== undefined)
  779. request["apisecret"] = apisecret;
  780. ws.send(JSON.stringify(request));
  781. }
  782. // Private method to create a session
  783. function createSession(callbacks) {
  784. var transaction = Janus.randomString(12);
  785. // console.log("jannus create_token",stream);
  786. var request = {
  787. "rtcgw": "create",
  788. "transaction": transaction,
  789. "token":window.EZUIKit.opt.stream,
  790. "device": window.EZUIKit.opt.deviceSerial,
  791. "channel": window.EZUIKit.opt.channelNo,
  792. };
  793. if(callbacks["reconnect"]) {
  794. // We're reconnecting, claim the session
  795. connected = false;
  796. request["rtcgw"] = "claim";
  797. request["session_id"] = sessionId;
  798. // If we were using websockets, ignore the old connection
  799. if(ws) {
  800. ws.onopen = null;
  801. ws.onerror = null;
  802. ws.onclose = null;
  803. if(wsKeepaliveTimeoutId) {
  804. clearTimeout(wsKeepaliveTimeoutId);
  805. wsKeepaliveTimeoutId = null;
  806. }
  807. }
  808. }
  809. if(token !== null && token !== undefined)
  810. request["token"] = token;
  811. if(apisecret !== null && apisecret !== undefined)
  812. request["apisecret"] = apisecret;
  813. if(server === null && Janus.isArray(servers)) {
  814. // We still need to find a working server from the list we were given
  815. server = servers[serversIndex];
  816. if(server.indexOf("ws") === 0) {
  817. websockets = true;
  818. Janus.log("Server #" + (serversIndex+1) + ": trying WebSockets to contact Janus (" + server + ")");
  819. } else {
  820. websockets = false;
  821. Janus.log("Server #" + (serversIndex+1) + ": trying REST API to contact Janus (" + server + ")");
  822. }
  823. }
  824. if(websockets) {
  825. ws = Janus.newWebSocket(server, 'rtcgw-protocol');
  826. wsHandlers = {
  827. 'error': function() {
  828. Janus.error("Error connecting to the Janus WebSockets server... " + server);
  829. if (Janus.isArray(servers) && !callbacks["reconnect"]) {
  830. serversIndex++;
  831. if (serversIndex == servers.length) {
  832. // We tried all the servers the user gave us and they all failed
  833. callbacks.error("Error connecting to any of the provided Janus servers: Is the server down?");
  834. return;
  835. }
  836. // Let's try the next server
  837. server = null;
  838. setTimeout(function() {
  839. createSession(callbacks);
  840. }, 200);
  841. return;
  842. }
  843. callbacks.error("Error connecting to the Janus WebSockets server: Is the server down?");
  844. },
  845. 'open': function() {
  846. // We need to be notified about the success
  847. transactions[transaction] = function(json) {
  848. Janus.debug(json);
  849. if (json["rtcgw"] !== "success") {
  850. Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
  851. callbacks.error(json["error"].reason);
  852. return;
  853. }
  854. wsKeepaliveTimeoutId = setTimeout(keepAlive, keepAlivePeriod);
  855. connected = true;
  856. sessionId = json["session_id"] ? json["session_id"] : json.data["id"];
  857. if(callbacks["reconnect"]) {
  858. Janus.log("Claimed session: " + sessionId);
  859. } else {
  860. Janus.log("Created session: " + sessionId);
  861. }
  862. Janus.sessions[sessionId] = that;
  863. callbacks.success();
  864. };
  865. ws.send(JSON.stringify(request));
  866. },
  867. 'message': function(event) {
  868. handleEvent(JSON.parse(event.data));
  869. },
  870. 'close': function() {
  871. if (server === null || !connected) {
  872. return;
  873. }
  874. connected = false;
  875. // FIXME What if this is called when the page is closed?
  876. gatewayCallbacks.error("Lost connection to the server (is it down?)");
  877. }
  878. };
  879. for(var eventName in wsHandlers) {
  880. ws.addEventListener(eventName, wsHandlers[eventName]);
  881. }
  882. return;
  883. }
  884. Janus.httpAPICall(server, {
  885. verb: 'POST',
  886. withCredentials: withCredentials,
  887. body: request,
  888. success: function(json) {
  889. Janus.debug(json);
  890. if(json["rtcgw"] !== "success") {
  891. Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
  892. callbacks.error(json["error"].reason);
  893. return;
  894. }
  895. connected = true;
  896. sessionId = json["session_id"] ? json["session_id"] : json.data["id"];
  897. if(callbacks["reconnect"]) {
  898. Janus.log("Claimed session: " + sessionId);
  899. } else {
  900. Janus.log("Created session: " + sessionId);
  901. }
  902. Janus.sessions[sessionId] = that;
  903. eventHandler();
  904. callbacks.success();
  905. },
  906. error: function(textStatus, errorThrown) {
  907. Janus.error(textStatus + ":", errorThrown); // FIXME
  908. if(Janus.isArray(servers) && !callbacks["reconnect"]) {
  909. serversIndex++;
  910. if(serversIndex == servers.length) {
  911. // We tried all the servers the user gave us and they all failed
  912. callbacks.error("Error connecting to any of the provided Janus servers: Is the server down?");
  913. return;
  914. }
  915. // Let's try the next server
  916. server = null;
  917. setTimeout(function() { createSession(callbacks); }, 200);
  918. return;
  919. }
  920. if(errorThrown === "")
  921. callbacks.error(textStatus + ": Is the server down?");
  922. else
  923. callbacks.error(textStatus + ": " + errorThrown);
  924. }
  925. });
  926. }
  927. // Private method to destroy a session
  928. function destroySession(callbacks) {
  929. callbacks = callbacks || {};
  930. // FIXME This method triggers a success even when we fail
  931. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
  932. var asyncRequest = true;
  933. if(callbacks.asyncRequest !== undefined && callbacks.asyncRequest !== null)
  934. asyncRequest = (callbacks.asyncRequest === true);
  935. var notifyDestroyed = true;
  936. if(callbacks.notifyDestroyed !== undefined && callbacks.notifyDestroyed !== null)
  937. notifyDestroyed = (callbacks.notifyDestroyed === true);
  938. var cleanupHandles = false;
  939. if(callbacks.cleanupHandles !== undefined && callbacks.cleanupHandles !== null)
  940. cleanupHandles = (callbacks.cleanupHandles === true);
  941. Janus.log("Destroying session " + sessionId + " (async=" + asyncRequest + ")");
  942. if(!connected) {
  943. Janus.warn("Is the server down? (connected=false)");
  944. callbacks.success();
  945. return;
  946. }
  947. if(sessionId === undefined || sessionId === null) {
  948. Janus.warn("No session to destroy");
  949. callbacks.success();
  950. if(notifyDestroyed)
  951. gatewayCallbacks.destroyed();
  952. return;
  953. }
  954. if(cleanupHandles) {
  955. for(var handleId in pluginHandles)
  956. destroyHandle(handleId, { noRequest: true });
  957. }
  958. // No need to destroy all handles first, Janus will do that itself
  959. var request = { "rtcgw": "destroy", "transaction": Janus.randomString(12) };
  960. if(token !== null && token !== undefined)
  961. request["token"] = token;
  962. if(apisecret !== null && apisecret !== undefined)
  963. request["apisecret"] = apisecret;
  964. if(websockets) {
  965. request["session_id"] = sessionId;
  966. var unbindWebSocket = function() {
  967. for(var eventName in wsHandlers) {
  968. ws.removeEventListener(eventName, wsHandlers[eventName]);
  969. }
  970. ws.removeEventListener('message', onUnbindMessage);
  971. ws.removeEventListener('error', onUnbindError);
  972. if(wsKeepaliveTimeoutId) {
  973. clearTimeout(wsKeepaliveTimeoutId);
  974. }
  975. ws.close();
  976. };
  977. var onUnbindMessage = function(event){
  978. var data = JSON.parse(event.data);
  979. if(data.session_id == request.session_id && data.transaction == request.transaction) {
  980. unbindWebSocket();
  981. callbacks.success();
  982. if(notifyDestroyed)
  983. gatewayCallbacks.destroyed();
  984. }
  985. };
  986. var onUnbindError = function(event) {
  987. unbindWebSocket();
  988. callbacks.error("Failed to destroy the server: Is the server down?");
  989. if(notifyDestroyed)
  990. gatewayCallbacks.destroyed();
  991. };
  992. ws.addEventListener('message', onUnbindMessage);
  993. ws.addEventListener('error', onUnbindError);
  994. ws.send(JSON.stringify(request));
  995. return;
  996. }
  997. Janus.httpAPICall(server + "/" + sessionId, {
  998. verb: 'POST',
  999. async: asyncRequest, // Sometimes we need false here, or destroying in onbeforeunload won't work
  1000. withCredentials: withCredentials,
  1001. body: request,
  1002. success: function(json) {
  1003. Janus.log("Destroyed session:");
  1004. Janus.debug(json);
  1005. sessionId = null;
  1006. connected = false;
  1007. if(json["rtcgw"] !== "success") {
  1008. Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
  1009. }
  1010. callbacks.success();
  1011. if(notifyDestroyed)
  1012. gatewayCallbacks.destroyed();
  1013. },
  1014. error: function(textStatus, errorThrown) {
  1015. Janus.error(textStatus + ":", errorThrown); // FIXME
  1016. // Reset everything anyway
  1017. sessionId = null;
  1018. connected = false;
  1019. callbacks.success();
  1020. if(notifyDestroyed)
  1021. gatewayCallbacks.destroyed();
  1022. }
  1023. });
  1024. }
  1025. // Private method to create a plugin handle
  1026. function createHandle(callbacks) {
  1027. callbacks = callbacks || {};
  1028. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
  1029. callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : Janus.noop;
  1030. callbacks.consentDialog = (typeof callbacks.consentDialog == "function") ? callbacks.consentDialog : Janus.noop;
  1031. callbacks.iceState = (typeof callbacks.iceState == "function") ? callbacks.iceState : Janus.noop;
  1032. callbacks.mediaState = (typeof callbacks.mediaState == "function") ? callbacks.mediaState : Janus.noop;
  1033. callbacks.webrtcState = (typeof callbacks.webrtcState == "function") ? callbacks.webrtcState : Janus.noop;
  1034. callbacks.slowLink = (typeof callbacks.slowLink == "function") ? callbacks.slowLink : Janus.noop;
  1035. callbacks.onmessage = (typeof callbacks.onmessage == "function") ? callbacks.onmessage : Janus.noop;
  1036. callbacks.onlocalstream = (typeof callbacks.onlocalstream == "function") ? callbacks.onlocalstream : Janus.noop;
  1037. callbacks.onremotestream = (typeof callbacks.onremotestream == "function") ? callbacks.onremotestream : Janus.noop;
  1038. callbacks.ondata = (typeof callbacks.ondata == "function") ? callbacks.ondata : Janus.noop;
  1039. callbacks.ondataopen = (typeof callbacks.ondataopen == "function") ? callbacks.ondataopen : Janus.noop;
  1040. callbacks.oncleanup = (typeof callbacks.oncleanup == "function") ? callbacks.oncleanup : Janus.noop;
  1041. callbacks.ondetached = (typeof callbacks.ondetached == "function") ? callbacks.ondetached : Janus.noop;
  1042. if(!connected) {
  1043. Janus.warn("Is the server down? (connected=false)");
  1044. callbacks.error("Is the server down? (connected=false)");
  1045. return;
  1046. }
  1047. var plugin = callbacks.plugin;
  1048. if(plugin === undefined || plugin === null) {
  1049. Janus.error("Invalid plugin");
  1050. callbacks.error("Invalid plugin");
  1051. return;
  1052. }
  1053. var opaqueId = callbacks.opaqueId;
  1054. var handleToken = callbacks.token ? callbacks.token : token;
  1055. var transaction = Janus.randomString(12);
  1056. var request = { "rtcgw": "attach", "plugin": plugin, "opaque_id": opaqueId, "transaction": transaction };
  1057. if(handleToken !== null && handleToken !== undefined)
  1058. request["token"] = handleToken;
  1059. if(apisecret !== null && apisecret !== undefined)
  1060. request["apisecret"] = apisecret;
  1061. if(websockets) {
  1062. transactions[transaction] = function(json) {
  1063. Janus.debug(json);
  1064. if(json["rtcgw"] !== "success") {
  1065. Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
  1066. callbacks.error("Ooops: " + json["error"].code + " " + json["error"].reason);
  1067. return;
  1068. }
  1069. var handleId = json.data["id"];
  1070. Janus.log("Created handle: " + handleId);
  1071. var pluginHandle =
  1072. {
  1073. session : that,
  1074. plugin : plugin,
  1075. id : handleId,
  1076. token : handleToken,
  1077. detached : false,
  1078. webrtcStuff : {
  1079. started : false,
  1080. myStream : null,
  1081. streamExternal : false,
  1082. remoteStream : null,
  1083. mySdp : null,
  1084. mediaConstraints : null,
  1085. pc : null,
  1086. dataChannel : {},
  1087. dtmfSender : null,
  1088. trickle : true,
  1089. iceDone : false,
  1090. volume : {
  1091. value : null,
  1092. timer : null
  1093. },
  1094. bitrate : {
  1095. value : null,
  1096. bsnow : null,
  1097. bsbefore : null,
  1098. tsnow : null,
  1099. tsbefore : null,
  1100. timer : null
  1101. }
  1102. },
  1103. getId : function() { return handleId; },
  1104. getPlugin : function() { return plugin; },
  1105. getVolume : function() { return getVolume(handleId, true); },
  1106. getRemoteVolume : function() { return getVolume(handleId, true); },
  1107. getLocalVolume : function() { return getVolume(handleId, false); },
  1108. isAudioMuted : function() { return isMuted(handleId, false); },
  1109. muteAudio : function() { return mute(handleId, false, true); },
  1110. unmuteAudio : function() { return mute(handleId, false, false); },
  1111. isVideoMuted : function() { return isMuted(handleId, true); },
  1112. muteVideo : function() { return mute(handleId, true, true); },
  1113. unmuteVideo : function() { return mute(handleId, true, false); },
  1114. getBitrate : function() { return getBitrate(handleId); },
  1115. send : function(callbacks) { sendMessage(handleId, callbacks); },
  1116. data : function(callbacks) { sendData(handleId, callbacks); },
  1117. dtmf : function(callbacks) { sendDtmf(handleId, callbacks); },
  1118. consentDialog : callbacks.consentDialog,
  1119. iceState : callbacks.iceState,
  1120. mediaState : callbacks.mediaState,
  1121. webrtcState : callbacks.webrtcState,
  1122. slowLink : callbacks.slowLink,
  1123. onmessage : callbacks.onmessage,
  1124. createOffer : function(callbacks) { prepareWebrtc(handleId, true, callbacks); },
  1125. createAnswer : function(callbacks) { prepareWebrtc(handleId, false, callbacks); },
  1126. handleRemoteJsep : function(callbacks) { prepareWebrtcPeer(handleId, callbacks); },
  1127. onlocalstream : callbacks.onlocalstream,
  1128. onremotestream : callbacks.onremotestream,
  1129. ondata : callbacks.ondata,
  1130. ondataopen : callbacks.ondataopen,
  1131. oncleanup : callbacks.oncleanup,
  1132. ondetached : callbacks.ondetached,
  1133. hangup : function(sendRequest) { cleanupWebrtc(handleId, sendRequest === true); },
  1134. detach : function(callbacks) { destroyHandle(handleId, callbacks); }
  1135. }
  1136. pluginHandles[handleId] = pluginHandle;
  1137. callbacks.success(pluginHandle);
  1138. };
  1139. request["session_id"] = sessionId;
  1140. ws.send(JSON.stringify(request));
  1141. return;
  1142. }
  1143. Janus.httpAPICall(server + "/" + sessionId, {
  1144. verb: 'POST',
  1145. withCredentials: withCredentials,
  1146. body: request,
  1147. success: function(json) {
  1148. Janus.debug(json);
  1149. if(json["rtcgw"] !== "success") {
  1150. Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
  1151. callbacks.error("Ooops: " + json["error"].code + " " + json["error"].reason);
  1152. return;
  1153. }
  1154. var handleId = json.data["id"];
  1155. Janus.log("Created handle: " + handleId);
  1156. var pluginHandle =
  1157. {
  1158. session : that,
  1159. plugin : plugin,
  1160. id : handleId,
  1161. token : handleToken,
  1162. detached : false,
  1163. webrtcStuff : {
  1164. started : false,
  1165. myStream : null,
  1166. streamExternal : false,
  1167. remoteStream : null,
  1168. mySdp : null,
  1169. mediaConstraints : null,
  1170. pc : null,
  1171. dataChannel : {},
  1172. dtmfSender : null,
  1173. trickle : true,
  1174. iceDone : false,
  1175. volume : {
  1176. value : null,
  1177. timer : null
  1178. },
  1179. bitrate : {
  1180. value : null,
  1181. bsnow : null,
  1182. bsbefore : null,
  1183. tsnow : null,
  1184. tsbefore : null,
  1185. timer : null
  1186. }
  1187. },
  1188. getId : function() { return handleId; },
  1189. getPlugin : function() { return plugin; },
  1190. getVolume : function() { return getVolume(handleId, true); },
  1191. getRemoteVolume : function() { return getVolume(handleId, true); },
  1192. getLocalVolume : function() { return getVolume(handleId, false); },
  1193. isAudioMuted : function() { return isMuted(handleId, false); },
  1194. muteAudio : function() { return mute(handleId, false, true); },
  1195. unmuteAudio : function() { return mute(handleId, false, false); },
  1196. isVideoMuted : function() { return isMuted(handleId, true); },
  1197. muteVideo : function() { return mute(handleId, true, true); },
  1198. unmuteVideo : function() { return mute(handleId, true, false); },
  1199. getBitrate : function() { return getBitrate(handleId); },
  1200. send : function(callbacks) { sendMessage(handleId, callbacks); },
  1201. data : function(callbacks) { sendData(handleId, callbacks); },
  1202. dtmf : function(callbacks) { sendDtmf(handleId, callbacks); },
  1203. consentDialog : callbacks.consentDialog,
  1204. iceState : callbacks.iceState,
  1205. mediaState : callbacks.mediaState,
  1206. webrtcState : callbacks.webrtcState,
  1207. slowLink : callbacks.slowLink,
  1208. onmessage : callbacks.onmessage,
  1209. createOffer : function(callbacks) { prepareWebrtc(handleId, true, callbacks); },
  1210. createAnswer : function(callbacks) { prepareWebrtc(handleId, false, callbacks); },
  1211. handleRemoteJsep : function(callbacks) { prepareWebrtcPeer(handleId, callbacks); },
  1212. onlocalstream : callbacks.onlocalstream,
  1213. onremotestream : callbacks.onremotestream,
  1214. ondata : callbacks.ondata,
  1215. ondataopen : callbacks.ondataopen,
  1216. oncleanup : callbacks.oncleanup,
  1217. ondetached : callbacks.ondetached,
  1218. hangup : function(sendRequest) { cleanupWebrtc(handleId, sendRequest === true); },
  1219. detach : function(callbacks) { destroyHandle(handleId, callbacks); }
  1220. }
  1221. pluginHandles[handleId] = pluginHandle;
  1222. callbacks.success(pluginHandle);
  1223. },
  1224. error: function(textStatus, errorThrown) {
  1225. Janus.error(textStatus + ":", errorThrown); // FIXME
  1226. }
  1227. });
  1228. }
  1229. // Private method to send a message
  1230. function sendMessage(handleId, callbacks) {
  1231. callbacks = callbacks || {};
  1232. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
  1233. callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : Janus.noop;
  1234. if(!connected) {
  1235. Janus.warn("Is the server down? (connected=false)");
  1236. callbacks.error("Is the server down? (connected=false)");
  1237. return;
  1238. }
  1239. var pluginHandle = pluginHandles[handleId];
  1240. if(pluginHandle === null || pluginHandle === undefined ||
  1241. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  1242. Janus.warn("Invalid handle");
  1243. callbacks.error("Invalid handle");
  1244. return;
  1245. }
  1246. var message = callbacks.message;
  1247. var jsep = callbacks.jsep;
  1248. var transaction = Janus.randomString(12);
  1249. var request = { "rtcgw": "message", "body": message, "transaction": transaction };
  1250. if(pluginHandle.token !== null && pluginHandle.token !== undefined)
  1251. request["token"] = pluginHandle.token;
  1252. if(apisecret !== null && apisecret !== undefined)
  1253. request["apisecret"] = apisecret;
  1254. if(jsep !== null && jsep !== undefined)
  1255. request.jsep = jsep;
  1256. Janus.debug("Sending message to plugin (handle=" + handleId + "):");
  1257. Janus.debug(request);
  1258. if(websockets) {
  1259. request["session_id"] = sessionId;
  1260. request["handle_id"] = handleId;
  1261. transactions[transaction] = function(json) {
  1262. Janus.debug("Message sent!");
  1263. Janus.debug(json);
  1264. if(json["rtcgw"] === "success") {
  1265. // We got a success, must have been a synchronous transaction
  1266. var plugindata = json["plugindata"];
  1267. if(plugindata === undefined || plugindata === null) {
  1268. Janus.warn("Request succeeded, but missing plugindata...");
  1269. callbacks.success();
  1270. return;
  1271. }
  1272. Janus.log("Synchronous transaction successful (" + plugindata["plugin"] + ")");
  1273. var data = plugindata["data"];
  1274. Janus.debug(data);
  1275. callbacks.success(data);
  1276. return;
  1277. } else if(json["rtcgw"] !== "ack") {
  1278. // Not a success and not an ack, must be an error
  1279. if(json["error"] !== undefined && json["error"] !== null) {
  1280. Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
  1281. callbacks.error(json["error"].code + " " + json["error"].reason);
  1282. } else {
  1283. Janus.error("Unknown error"); // FIXME
  1284. callbacks.error("Unknown error");
  1285. }
  1286. return;
  1287. }
  1288. // If we got here, the plugin decided to handle the request asynchronously
  1289. callbacks.success();
  1290. };
  1291. ws.send(JSON.stringify(request));
  1292. return;
  1293. }
  1294. Janus.httpAPICall(server + "/" + sessionId + "/" + handleId, {
  1295. verb: 'POST',
  1296. withCredentials: withCredentials,
  1297. body: request,
  1298. success: function(json) {
  1299. Janus.debug("Message sent!");
  1300. Janus.debug(json);
  1301. if(json["rtcgw"] === "success") {
  1302. // We got a success, must have been a synchronous transaction
  1303. var plugindata = json["plugindata"];
  1304. if(plugindata === undefined || plugindata === null) {
  1305. Janus.warn("Request succeeded, but missing plugindata...");
  1306. callbacks.success();
  1307. return;
  1308. }
  1309. Janus.log("Synchronous transaction successful (" + plugindata["plugin"] + ")");
  1310. var data = plugindata["data"];
  1311. Janus.debug(data);
  1312. callbacks.success(data);
  1313. return;
  1314. } else if(json["rtcgw"] !== "ack") {
  1315. // Not a success and not an ack, must be an error
  1316. if(json["error"] !== undefined && json["error"] !== null) {
  1317. Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
  1318. callbacks.error(json["error"].code + " " + json["error"].reason);
  1319. } else {
  1320. Janus.error("Unknown error"); // FIXME
  1321. callbacks.error("Unknown error");
  1322. }
  1323. return;
  1324. }
  1325. // If we got here, the plugin decided to handle the request asynchronously
  1326. callbacks.success();
  1327. },
  1328. error: function(textStatus, errorThrown) {
  1329. Janus.error(textStatus + ":", errorThrown); // FIXME
  1330. callbacks.error(textStatus + ": " + errorThrown);
  1331. }
  1332. });
  1333. }
  1334. // Private method to send a trickle candidate
  1335. function sendTrickleCandidate(handleId, candidate) {
  1336. if(!connected) {
  1337. Janus.warn("Is the server down? (connected=false)");
  1338. return;
  1339. }
  1340. var pluginHandle = pluginHandles[handleId];
  1341. if(pluginHandle === null || pluginHandle === undefined ||
  1342. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  1343. Janus.warn("Invalid handle");
  1344. return;
  1345. }
  1346. var request = { "rtcgw": "trickle", "candidate": candidate, "transaction": Janus.randomString(12) };
  1347. if(pluginHandle.token !== null && pluginHandle.token !== undefined)
  1348. request["token"] = pluginHandle.token;
  1349. if(apisecret !== null && apisecret !== undefined)
  1350. request["apisecret"] = apisecret;
  1351. Janus.vdebug("Sending trickle candidate (handle=" + handleId + "):");
  1352. Janus.vdebug(request);
  1353. if(websockets) {
  1354. request["session_id"] = sessionId;
  1355. request["handle_id"] = handleId;
  1356. ws.send(JSON.stringify(request));
  1357. return;
  1358. }
  1359. Janus.httpAPICall(server + "/" + sessionId + "/" + handleId, {
  1360. verb: 'POST',
  1361. withCredentials: withCredentials,
  1362. body: request,
  1363. success: function(json) {
  1364. Janus.vdebug("Candidate sent!");
  1365. Janus.vdebug(json);
  1366. if(json["rtcgw"] !== "ack") {
  1367. Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
  1368. return;
  1369. }
  1370. },
  1371. error: function(textStatus, errorThrown) {
  1372. Janus.error(textStatus + ":", errorThrown); // FIXME
  1373. }
  1374. });
  1375. }
  1376. // Private method to create a data channel
  1377. function createDataChannel(handleId, dclabel, incoming, pendingText) {
  1378. var pluginHandle = pluginHandles[handleId];
  1379. if(pluginHandle === null || pluginHandle === undefined ||
  1380. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  1381. Janus.warn("Invalid handle");
  1382. return;
  1383. }
  1384. var config = pluginHandle.webrtcStuff;
  1385. var onDataChannelMessage = function(event) {
  1386. Janus.log('Received message on data channel:', event);
  1387. var label = event.target.label;
  1388. pluginHandle.ondata(event.data, label);
  1389. }
  1390. var onDataChannelStateChange = function(event) {
  1391. Janus.log('Received state change on data channel:', event);
  1392. var label = event.target.label;
  1393. var dcState = config.dataChannel[label] ? config.dataChannel[label].readyState : "null";
  1394. Janus.log('State change on <' + label + '> data channel: ' + dcState);
  1395. if(dcState === 'open') {
  1396. // Any pending messages to send?
  1397. if(config.dataChannel[label].pending && config.dataChannel[label].pending.length > 0) {
  1398. Janus.log("Sending pending messages on <" + label + ">:", config.dataChannel[label].pending.length);
  1399. for(var i in config.dataChannel[label].pending) {
  1400. var text = config.dataChannel[label].pending[i];
  1401. Janus.log("Sending string on data channel <" + label + ">: " + text);
  1402. config.dataChannel[label].send(text);
  1403. }
  1404. config.dataChannel[label].pending = [];
  1405. }
  1406. // Notify the open data channel
  1407. pluginHandle.ondataopen(label);
  1408. }
  1409. }
  1410. var onDataChannelError = function(error) {
  1411. Janus.error('Got error on data channel:', error);
  1412. // TODO
  1413. }
  1414. if(!incoming) {
  1415. // FIXME Add options (ordered, maxRetransmits, etc.)
  1416. config.dataChannel[dclabel] = config.pc.createDataChannel(dclabel, {ordered:false});
  1417. } else {
  1418. // The channel was created by Janus
  1419. config.dataChannel[dclabel] = incoming;
  1420. }
  1421. config.dataChannel[dclabel].onmessage = onDataChannelMessage;
  1422. config.dataChannel[dclabel].onopen = onDataChannelStateChange;
  1423. config.dataChannel[dclabel].onclose = onDataChannelStateChange;
  1424. config.dataChannel[dclabel].onerror = onDataChannelError;
  1425. config.dataChannel[dclabel].pending = [];
  1426. if(pendingText)
  1427. config.dataChannel[dclabel].pending.push(pendingText);
  1428. }
  1429. // Private method to send a data channel message
  1430. function sendData(handleId, callbacks) {
  1431. callbacks = callbacks || {};
  1432. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
  1433. callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : Janus.noop;
  1434. var pluginHandle = pluginHandles[handleId];
  1435. if(pluginHandle === null || pluginHandle === undefined ||
  1436. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  1437. Janus.warn("Invalid handle");
  1438. callbacks.error("Invalid handle");
  1439. return;
  1440. }
  1441. var config = pluginHandle.webrtcStuff;
  1442. var text = callbacks.text;
  1443. if(text === null || text === undefined) {
  1444. Janus.warn("Invalid text");
  1445. callbacks.error("Invalid text");
  1446. return;
  1447. }
  1448. var label = callbacks.label ? callbacks.label : Janus.dataChanDefaultLabel;
  1449. if(!config.dataChannel[label]) {
  1450. // Create new data channel and wait for it to open
  1451. createDataChannel(handleId, label, false, text);
  1452. callbacks.success();
  1453. return;
  1454. }
  1455. if(config.dataChannel[label].readyState !== "open") {
  1456. config.dataChannel[label].pending.push(text);
  1457. callbacks.success();
  1458. return;
  1459. }
  1460. Janus.log("Sending string on data channel <" + label + ">: " + text);
  1461. config.dataChannel[label].send(text);
  1462. callbacks.success();
  1463. }
  1464. // Private method to send a DTMF tone
  1465. function sendDtmf(handleId, callbacks) {
  1466. callbacks = callbacks || {};
  1467. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
  1468. callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : Janus.noop;
  1469. var pluginHandle = pluginHandles[handleId];
  1470. if(pluginHandle === null || pluginHandle === undefined ||
  1471. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  1472. Janus.warn("Invalid handle");
  1473. callbacks.error("Invalid handle");
  1474. return;
  1475. }
  1476. var config = pluginHandle.webrtcStuff;
  1477. if(config.dtmfSender === null || config.dtmfSender === undefined) {
  1478. // Create the DTMF sender the proper way, if possible
  1479. if(config.pc !== undefined && config.pc !== null) {
  1480. var senders = config.pc.getSenders();
  1481. var audioSender = senders.find(function(sender) {
  1482. return sender.track && sender.track.kind === 'audio';
  1483. });
  1484. if(!audioSender) {
  1485. Janus.warn("Invalid DTMF configuration (no audio track)");
  1486. callbacks.error("Invalid DTMF configuration (no audio track)");
  1487. return;
  1488. }
  1489. config.dtmfSender = audioSender.dtmf;
  1490. if(config.dtmfSender) {
  1491. Janus.log("Created DTMF Sender");
  1492. config.dtmfSender.ontonechange = function(tone) { Janus.debug("Sent DTMF tone: " + tone.tone); };
  1493. }
  1494. }
  1495. if(config.dtmfSender === null || config.dtmfSender === undefined) {
  1496. Janus.warn("Invalid DTMF configuration");
  1497. callbacks.error("Invalid DTMF configuration");
  1498. return;
  1499. }
  1500. }
  1501. var dtmf = callbacks.dtmf;
  1502. if(dtmf === null || dtmf === undefined) {
  1503. Janus.warn("Invalid DTMF parameters");
  1504. callbacks.error("Invalid DTMF parameters");
  1505. return;
  1506. }
  1507. var tones = dtmf.tones;
  1508. if(tones === null || tones === undefined) {
  1509. Janus.warn("Invalid DTMF string");
  1510. callbacks.error("Invalid DTMF string");
  1511. return;
  1512. }
  1513. var duration = dtmf.duration;
  1514. if(duration === null || duration === undefined)
  1515. duration = 500; // We choose 500ms as the default duration for a tone
  1516. var gap = dtmf.gap;
  1517. if(gap === null || gap === undefined)
  1518. gap = 50; // We choose 50ms as the default gap between tones
  1519. Janus.debug("Sending DTMF string " + tones + " (duration " + duration + "ms, gap " + gap + "ms)");
  1520. config.dtmfSender.insertDTMF(tones, duration, gap);
  1521. callbacks.success();
  1522. }
  1523. // Private method to destroy a plugin handle
  1524. function destroyHandle(handleId, callbacks) {
  1525. callbacks = callbacks || {};
  1526. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
  1527. callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : Janus.noop;
  1528. var asyncRequest = true;
  1529. if(callbacks.asyncRequest !== undefined && callbacks.asyncRequest !== null)
  1530. asyncRequest = (callbacks.asyncRequest === true);
  1531. var noRequest = true;
  1532. if(callbacks.noRequest !== undefined && callbacks.noRequest !== null)
  1533. noRequest = (callbacks.noRequest === true);
  1534. Janus.log("Destroying handle " + handleId + " (async=" + asyncRequest + ")");
  1535. cleanupWebrtc(handleId);
  1536. var pluginHandle = pluginHandles[handleId];
  1537. if(pluginHandle === null || pluginHandle === undefined || pluginHandle.detached) {
  1538. // Plugin was already detached by Janus, calling detach again will return a handle not found error, so just exit here
  1539. delete pluginHandles[handleId];
  1540. callbacks.success();
  1541. return;
  1542. }
  1543. if(noRequest) {
  1544. // We're only removing the handle locally
  1545. delete pluginHandles[handleId];
  1546. callbacks.success();
  1547. return;
  1548. }
  1549. if(!connected) {
  1550. Janus.warn("Is the server down? (connected=false)");
  1551. callbacks.error("Is the server down? (connected=false)");
  1552. return;
  1553. }
  1554. var request = { "rtcgw": "detach", "transaction": Janus.randomString(12) };
  1555. if(pluginHandle.token !== null && pluginHandle.token !== undefined)
  1556. request["token"] = pluginHandle.token;
  1557. if(apisecret !== null && apisecret !== undefined)
  1558. request["apisecret"] = apisecret;
  1559. if(websockets) {
  1560. request["session_id"] = sessionId;
  1561. request["handle_id"] = handleId;
  1562. ws.send(JSON.stringify(request));
  1563. delete pluginHandles[handleId];
  1564. callbacks.success();
  1565. return;
  1566. }
  1567. Janus.httpAPICall(server + "/" + sessionId + "/" + handleId, {
  1568. verb: 'POST',
  1569. async: asyncRequest, // Sometimes we need false here, or destroying in onbeforeunload won't work
  1570. withCredentials: withCredentials,
  1571. body: request,
  1572. success: function(json) {
  1573. Janus.log("Destroyed handle:");
  1574. Janus.debug(json);
  1575. if(json["rtcgw"] !== "success") {
  1576. Janus.error("Ooops: " + json["error"].code + " " + json["error"].reason); // FIXME
  1577. }
  1578. delete pluginHandles[handleId];
  1579. callbacks.success();
  1580. },
  1581. error: function(textStatus, errorThrown) {
  1582. Janus.error(textStatus + ":", errorThrown); // FIXME
  1583. // We cleanup anyway
  1584. delete pluginHandles[handleId];
  1585. callbacks.success();
  1586. }
  1587. });
  1588. }
  1589. // WebRTC stuff
  1590. function streamsDone(handleId, jsep, media, callbacks, stream) {
  1591. var pluginHandle = pluginHandles[handleId];
  1592. if(pluginHandle === null || pluginHandle === undefined ||
  1593. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  1594. Janus.warn("Invalid handle");
  1595. callbacks.error("Invalid handle");
  1596. return;
  1597. }
  1598. var config = pluginHandle.webrtcStuff;
  1599. Janus.debug("streamsDone:", stream);
  1600. if(stream) {
  1601. Janus.debug(" -- Audio tracks:", stream.getAudioTracks());
  1602. Janus.debug(" -- Video tracks:", stream.getVideoTracks());
  1603. }
  1604. // We're now capturing the new stream: check if we're updating or if it's a new thing
  1605. var addTracks = false;
  1606. if(!config.myStream || !media.update || config.streamExternal) {
  1607. config.myStream = stream;
  1608. addTracks = true;
  1609. } else {
  1610. // We only need to update the existing stream
  1611. if(((!media.update && isAudioSendEnabled(media)) || (media.update && (media.addAudio || media.replaceAudio))) &&
  1612. stream.getAudioTracks() && stream.getAudioTracks().length) {
  1613. config.myStream.addTrack(stream.getAudioTracks()[0]);
  1614. if(Janus.unifiedPlan) {
  1615. // Use Transceivers
  1616. Janus.log((media.replaceAudio ? "Replacing" : "Adding") + " audio track:", stream.getAudioTracks()[0]);
  1617. var audioTransceiver = null;
  1618. var transceivers = config.pc.getTransceivers();
  1619. if(transceivers && transceivers.length > 0) {
  1620. for(var i in transceivers) {
  1621. var t = transceivers[i];
  1622. if((t.sender && t.sender.track && t.sender.track.kind === "audio") ||
  1623. (t.receiver && t.receiver.track && t.receiver.track.kind === "audio")) {
  1624. audioTransceiver = t;
  1625. break;
  1626. }
  1627. }
  1628. }
  1629. if(audioTransceiver && audioTransceiver.sender) {
  1630. audioTransceiver.sender.replaceTrack(stream.getAudioTracks()[0]);
  1631. } else {
  1632. config.pc.addTrack(stream.getAudioTracks()[0], stream);
  1633. }
  1634. } else {
  1635. Janus.log((media.replaceAudio ? "Replacing" : "Adding") + " audio track:", stream.getAudioTracks()[0]);
  1636. config.pc.addTrack(stream.getAudioTracks()[0], stream);
  1637. }
  1638. }
  1639. if(((!media.update && isVideoSendEnabled(media)) || (media.update && (media.addVideo || media.replaceVideo))) &&
  1640. stream.getVideoTracks() && stream.getVideoTracks().length) {
  1641. config.myStream.addTrack(stream.getVideoTracks()[0]);
  1642. if(Janus.unifiedPlan) {
  1643. // Use Transceivers
  1644. Janus.log((media.replaceVideo ? "Replacing" : "Adding") + " video track:", stream.getVideoTracks()[0]);
  1645. var videoTransceiver = null;
  1646. var transceivers = config.pc.getTransceivers();
  1647. if(transceivers && transceivers.length > 0) {
  1648. for(var i in transceivers) {
  1649. var t = transceivers[i];
  1650. if((t.sender && t.sender.track && t.sender.track.kind === "video") ||
  1651. (t.receiver && t.receiver.track && t.receiver.track.kind === "video")) {
  1652. videoTransceiver = t;
  1653. break;
  1654. }
  1655. }
  1656. }
  1657. if(videoTransceiver && videoTransceiver.sender) {
  1658. videoTransceiver.sender.replaceTrack(stream.getVideoTracks()[0]);
  1659. } else {
  1660. config.pc.addTrack(stream.getVideoTracks()[0], stream);
  1661. }
  1662. } else {
  1663. Janus.log((media.replaceVideo ? "Replacing" : "Adding") + " video track:", stream.getVideoTracks()[0]);
  1664. config.pc.addTrack(stream.getVideoTracks()[0], stream);
  1665. }
  1666. }
  1667. }
  1668. // If we still need to create a PeerConnection, let's do that
  1669. if(!config.pc) {
  1670. var pc_config = {"iceServers": iceServers, "iceTransportPolicy": iceTransportPolicy, "bundlePolicy": bundlePolicy};
  1671. if(Janus.webRTCAdapter.browserDetails.browser === "chrome") {
  1672. // For Chrome versions before 72, we force a plan-b semantic, and unified-plan otherwise
  1673. pc_config["sdpSemantics"] = (Janus.webRTCAdapter.browserDetails.version < 72) ? "plan-b" : "unified-plan";
  1674. }
  1675. var pc_constraints = {
  1676. "optional": [{"DtlsSrtpKeyAgreement": true}]
  1677. };
  1678. if(ipv6Support === true) {
  1679. pc_constraints.optional.push({"googIPv6":true});
  1680. }
  1681. // Any custom constraint to add?
  1682. if(callbacks.rtcConstraints && typeof callbacks.rtcConstraints === 'object') {
  1683. Janus.debug("Adding custom PeerConnection constraints:", callbacks.rtcConstraints);
  1684. for(var i in callbacks.rtcConstraints) {
  1685. pc_constraints.optional.push(callbacks.rtcConstraints[i]);
  1686. }
  1687. }
  1688. if(Janus.webRTCAdapter.browserDetails.browser === "edge") {
  1689. // This is Edge, enable BUNDLE explicitly
  1690. pc_config.bundlePolicy = "max-bundle";
  1691. }
  1692. Janus.log("Creating PeerConnection");
  1693. Janus.debug(pc_constraints);
  1694. config.pc = new RTCPeerConnection(pc_config, pc_constraints);
  1695. Janus.debug(config.pc);
  1696. if(config.pc.getStats) { // FIXME
  1697. config.volume = {};
  1698. config.bitrate.value = "0 kbits/sec";
  1699. }
  1700. Janus.log("Preparing local SDP and gathering candidates (trickle=" + config.trickle + ")");
  1701. config.pc.oniceconnectionstatechange = function(e) {
  1702. if(config.pc)
  1703. pluginHandle.iceState(config.pc.iceConnectionState);
  1704. };
  1705. config.pc.onicecandidate = function(event) {
  1706. if (event.candidate == null ||
  1707. (Janus.webRTCAdapter.browserDetails.browser === 'edge' && event.candidate.candidate.indexOf('endOfCandidates') > 0)) {
  1708. Janus.log("End of candidates.");
  1709. config.iceDone = true;
  1710. if(config.trickle === true) {
  1711. // Notify end of candidates
  1712. sendTrickleCandidate(handleId, {"completed": true});
  1713. } else {
  1714. // No trickle, time to send the complete SDP (including all candidates)
  1715. sendSDP(handleId, callbacks);
  1716. }
  1717. } else {
  1718. // JSON.stringify doesn't work on some WebRTC objects anymore
  1719. // See https://code.google.com/p/chromium/issues/detail?id=467366
  1720. var candidate = {
  1721. "candidate": event.candidate.candidate,
  1722. "sdpMid": event.candidate.sdpMid,
  1723. "sdpMLineIndex": event.candidate.sdpMLineIndex
  1724. };
  1725. if(config.trickle === true) {
  1726. // Send candidate
  1727. sendTrickleCandidate(handleId, candidate);
  1728. }
  1729. }
  1730. };
  1731. config.pc.ontrack = function(event) {
  1732. Janus.log("Handling Remote Track");
  1733. Janus.debug(event);
  1734. if(!event.streams)
  1735. return;
  1736. config.remoteStream = event.streams[0];
  1737. pluginHandle.onremotestream(config.remoteStream);
  1738. if(event.track.onended)
  1739. return;
  1740. Janus.log("Adding onended callback to track:", event.track);
  1741. event.track.onended = function(ev) {
  1742. Janus.log("Remote track muted/removed:", ev);
  1743. if(config.remoteStream) {
  1744. config.remoteStream.removeTrack(ev.target);
  1745. pluginHandle.onremotestream(config.remoteStream);
  1746. }
  1747. };
  1748. event.track.onmute = event.track.onended;
  1749. event.track.onunmute = function(ev) {
  1750. Janus.log("Remote track flowing again:", ev);
  1751. try {
  1752. config.remoteStream.addTrack(ev.target);
  1753. pluginHandle.onremotestream(config.remoteStream);
  1754. } catch(e) {
  1755. Janus.error(e);
  1756. };
  1757. };
  1758. };
  1759. }
  1760. if(addTracks && stream !== null && stream !== undefined) {
  1761. Janus.log('Adding local stream');
  1762. var simulcast2 = callbacks.simulcast2 === true ? true : false;
  1763. stream.getTracks().forEach(function(track) {
  1764. Janus.log('Adding local track:', track);
  1765. if(!simulcast2) {
  1766. config.pc.addTrack(track, stream);
  1767. } else {
  1768. if(track.kind === "audio") {
  1769. config.pc.addTrack(track, stream);
  1770. } else {
  1771. Janus.log('Enabling rid-based simulcasting:', track);
  1772. const maxBitrates = getMaxBitrates(callbacks.simulcastMaxBitrates);
  1773. config.pc.addTransceiver(track, {
  1774. direction: "sendrecv",
  1775. streams: [stream],
  1776. sendEncodings: [
  1777. { rid: "h", active: true, maxBitrate: maxBitrates.high },
  1778. { rid: "m", active: true, maxBitrate: maxBitrates.medium, scaleResolutionDownBy: 2 },
  1779. { rid: "l", active: true, maxBitrate: maxBitrates.low, scaleResolutionDownBy: 4 }
  1780. ]
  1781. });
  1782. }
  1783. }
  1784. });
  1785. }
  1786. // Any data channel to create?
  1787. if(isDataEnabled(media) && !config.dataChannel[Janus.dataChanDefaultLabel]) {
  1788. Janus.log("Creating data channel");
  1789. createDataChannel(handleId, Janus.dataChanDefaultLabel, false);
  1790. config.pc.ondatachannel = function(event) {
  1791. Janus.log("Data channel created by Janus:", event);
  1792. createDataChannel(handleId, event.channel.label, event.channel);
  1793. };
  1794. }
  1795. // If there's a new local stream, let's notify the application
  1796. if(config.myStream)
  1797. pluginHandle.onlocalstream(config.myStream);
  1798. // Create offer/answer now
  1799. if(jsep === null || jsep === undefined) {
  1800. createOffer(handleId, media, callbacks);
  1801. } else {
  1802. config.pc.setRemoteDescription(jsep)
  1803. .then(function() {
  1804. Janus.log("Remote description accepted!");
  1805. config.remoteSdp = jsep.sdp;
  1806. // Any trickle candidate we cached?
  1807. if(config.candidates && config.candidates.length > 0) {
  1808. for(var i = 0; i< config.candidates.length; i++) {
  1809. var candidate = config.candidates[i];
  1810. Janus.debug("Adding remote candidate:", candidate);
  1811. if(!candidate || candidate.completed === true) {
  1812. // end-of-candidates
  1813. config.pc.addIceCandidate(Janus.endOfCandidates);
  1814. } else {
  1815. // New candidate
  1816. config.pc.addIceCandidate(candidate);
  1817. }
  1818. }
  1819. config.candidates = [];
  1820. }
  1821. // Create the answer now
  1822. createAnswer(handleId, media, callbacks);
  1823. }, callbacks.error);
  1824. }
  1825. }
  1826. function prepareWebrtc(handleId, offer, callbacks) {
  1827. callbacks = callbacks || {};
  1828. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
  1829. callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : webrtcError;
  1830. var jsep = callbacks.jsep;
  1831. if(offer && jsep) {
  1832. Janus.error("Provided a JSEP to a createOffer");
  1833. callbacks.error("Provided a JSEP to a createOffer");
  1834. return;
  1835. } else if(!offer && (!jsep || !jsep.type || !jsep.sdp)) {
  1836. Janus.error("A valid JSEP is required for createAnswer");
  1837. callbacks.error("A valid JSEP is required for createAnswer");
  1838. return;
  1839. }
  1840. callbacks.media = callbacks.media || { audio: true, video: true };
  1841. var media = callbacks.media;
  1842. var pluginHandle = pluginHandles[handleId];
  1843. if(pluginHandle === null || pluginHandle === undefined ||
  1844. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  1845. Janus.warn("Invalid handle");
  1846. callbacks.error("Invalid handle");
  1847. return;
  1848. }
  1849. var config = pluginHandle.webrtcStuff;
  1850. config.trickle = isTrickleEnabled(callbacks.trickle);
  1851. // Are we updating a session?
  1852. if(config.pc === undefined || config.pc === null) {
  1853. // Nope, new PeerConnection
  1854. media.update = false;
  1855. media.keepAudio = false;
  1856. media.keepVideo = false;
  1857. } else if(config.pc !== undefined && config.pc !== null) {
  1858. Janus.log("Updating existing media session");
  1859. media.update = true;
  1860. // Check if there's anything to add/remove/replace, or if we
  1861. // can go directly to preparing the new SDP offer or answer
  1862. if(callbacks.stream !== null && callbacks.stream !== undefined) {
  1863. // External stream: is this the same as the one we were using before?
  1864. if(callbacks.stream !== config.myStream) {
  1865. Janus.log("Renegotiation involves a new external stream");
  1866. }
  1867. } else {
  1868. // Check if there are changes on audio
  1869. if(media.addAudio) {
  1870. media.keepAudio = false;
  1871. media.replaceAudio = false;
  1872. media.removeAudio = false;
  1873. media.audioSend = true;
  1874. if(config.myStream && config.myStream.getAudioTracks() && config.myStream.getAudioTracks().length) {
  1875. Janus.error("Can't add audio stream, there already is one");
  1876. callbacks.error("Can't add audio stream, there already is one");
  1877. return;
  1878. }
  1879. } else if(media.removeAudio) {
  1880. media.keepAudio = false;
  1881. media.replaceAudio = false;
  1882. media.addAudio = false;
  1883. media.audioSend = false;
  1884. } else if(media.replaceAudio) {
  1885. media.keepAudio = false;
  1886. media.addAudio = false;
  1887. media.removeAudio = false;
  1888. media.audioSend = true;
  1889. }
  1890. if(config.myStream === null || config.myStream === undefined) {
  1891. // No media stream: if we were asked to replace, it's actually an "add"
  1892. if(media.replaceAudio) {
  1893. media.keepAudio = false;
  1894. media.replaceAudio = false;
  1895. media.addAudio = true;
  1896. media.audioSend = true;
  1897. }
  1898. if(isAudioSendEnabled(media)) {
  1899. media.keepAudio = false;
  1900. media.addAudio = true;
  1901. }
  1902. } else {
  1903. if(config.myStream.getAudioTracks() === null
  1904. || config.myStream.getAudioTracks() === undefined
  1905. || config.myStream.getAudioTracks().length === 0) {
  1906. // No audio track: if we were asked to replace, it's actually an "add"
  1907. if(media.replaceAudio) {
  1908. media.keepAudio = false;
  1909. media.replaceAudio = false;
  1910. media.addAudio = true;
  1911. media.audioSend = true;
  1912. }
  1913. if(isAudioSendEnabled(media)) {
  1914. media.keepVideo = false;
  1915. media.addAudio = true;
  1916. }
  1917. } else {
  1918. // We have an audio track: should we keep it as it is?
  1919. if(isAudioSendEnabled(media) &&
  1920. !media.removeAudio && !media.replaceAudio) {
  1921. media.keepAudio = true;
  1922. }
  1923. }
  1924. }
  1925. // Check if there are changes on video
  1926. if(media.addVideo) {
  1927. media.keepVideo = false;
  1928. media.replaceVideo = false;
  1929. media.removeVideo = false;
  1930. media.videoSend = true;
  1931. if(config.myStream && config.myStream.getVideoTracks() && config.myStream.getVideoTracks().length) {
  1932. Janus.error("Can't add video stream, there already is one");
  1933. callbacks.error("Can't add video stream, there already is one");
  1934. return;
  1935. }
  1936. } else if(media.removeVideo) {
  1937. media.keepVideo = false;
  1938. media.replaceVideo = false;
  1939. media.addVideo = false;
  1940. media.videoSend = false;
  1941. } else if(media.replaceVideo) {
  1942. media.keepVideo = false;
  1943. media.addVideo = false;
  1944. media.removeVideo = false;
  1945. media.videoSend = true;
  1946. }
  1947. if(config.myStream === null || config.myStream === undefined) {
  1948. // No media stream: if we were asked to replace, it's actually an "add"
  1949. if(media.replaceVideo) {
  1950. media.keepVideo = false;
  1951. media.replaceVideo = false;
  1952. media.addVideo = true;
  1953. media.videoSend = true;
  1954. }
  1955. if(isVideoSendEnabled(media)) {
  1956. media.keepVideo = false;
  1957. media.addVideo = true;
  1958. }
  1959. } else {
  1960. if(config.myStream.getVideoTracks() === null
  1961. || config.myStream.getVideoTracks() === undefined
  1962. || config.myStream.getVideoTracks().length === 0) {
  1963. // No video track: if we were asked to replace, it's actually an "add"
  1964. if(media.replaceVideo) {
  1965. media.keepVideo = false;
  1966. media.replaceVideo = false;
  1967. media.addVideo = true;
  1968. media.videoSend = true;
  1969. }
  1970. if(isVideoSendEnabled(media)) {
  1971. media.keepVideo = false;
  1972. media.addVideo = true;
  1973. }
  1974. } else {
  1975. // We have a video track: should we keep it as it is?
  1976. if(isVideoSendEnabled(media) &&
  1977. !media.removeVideo && !media.replaceVideo) {
  1978. media.keepVideo = true;
  1979. }
  1980. }
  1981. }
  1982. // Data channels can only be added
  1983. if(media.addData)
  1984. media.data = true;
  1985. }
  1986. // If we're updating and keeping all tracks, let's skip the getUserMedia part
  1987. if((isAudioSendEnabled(media) && media.keepAudio) &&
  1988. (isVideoSendEnabled(media) && media.keepVideo)) {
  1989. pluginHandle.consentDialog(false);
  1990. streamsDone(handleId, jsep, media, callbacks, config.myStream);
  1991. return;
  1992. }
  1993. }
  1994. // If we're updating, check if we need to remove/replace one of the tracks
  1995. if(media.update && !config.streamExternal) {
  1996. if(media.removeAudio || media.replaceAudio) {
  1997. if(config.myStream && config.myStream.getAudioTracks() && config.myStream.getAudioTracks().length) {
  1998. var s = config.myStream.getAudioTracks()[0];
  1999. Janus.log("Removing audio track:", s);
  2000. config.myStream.removeTrack(s);
  2001. try {
  2002. s.stop();
  2003. } catch(e) {};
  2004. }
  2005. if(config.pc.getSenders() && config.pc.getSenders().length) {
  2006. var ra = true;
  2007. if(media.replaceAudio && Janus.unifiedPlan) {
  2008. // We can use replaceTrack
  2009. ra = false;
  2010. }
  2011. if(ra) {
  2012. for(var index in config.pc.getSenders()) {
  2013. var s = config.pc.getSenders()[index];
  2014. if(s && s.track && s.track.kind === "audio") {
  2015. Janus.log("Removing audio sender:", s);
  2016. config.pc.removeTrack(s);
  2017. }
  2018. }
  2019. }
  2020. }
  2021. }
  2022. if(media.removeVideo || media.replaceVideo) {
  2023. if(config.myStream && config.myStream.getVideoTracks() && config.myStream.getVideoTracks().length) {
  2024. var s = config.myStream.getVideoTracks()[0];
  2025. Janus.log("Removing video track:", s);
  2026. config.myStream.removeTrack(s);
  2027. try {
  2028. s.stop();
  2029. } catch(e) {};
  2030. }
  2031. if(config.pc.getSenders() && config.pc.getSenders().length) {
  2032. var rv = true;
  2033. if(media.replaceVideo && Janus.unifiedPlan) {
  2034. // We can use replaceTrack
  2035. rv = false;
  2036. }
  2037. if(rv) {
  2038. for(var index in config.pc.getSenders()) {
  2039. var s = config.pc.getSenders()[index];
  2040. if(s && s.track && s.track.kind === "video") {
  2041. Janus.log("Removing video sender:", s);
  2042. config.pc.removeTrack(s);
  2043. }
  2044. }
  2045. }
  2046. }
  2047. }
  2048. }
  2049. // Was a MediaStream object passed, or do we need to take care of that?
  2050. if(callbacks.stream !== null && callbacks.stream !== undefined) {
  2051. var stream = callbacks.stream;
  2052. Janus.log("MediaStream provided by the application");
  2053. Janus.debug(stream);
  2054. // If this is an update, let's check if we need to release the previous stream
  2055. if(media.update) {
  2056. if(config.myStream && config.myStream !== callbacks.stream && !config.streamExternal) {
  2057. // We're replacing a stream we captured ourselves with an external one
  2058. try {
  2059. // Try a MediaStreamTrack.stop() for each track
  2060. var tracks = config.myStream.getTracks();
  2061. for(var i in tracks) {
  2062. var mst = tracks[i];
  2063. Janus.log(mst);
  2064. if(mst !== null && mst !== undefined)
  2065. mst.stop();
  2066. }
  2067. } catch(e) {
  2068. // Do nothing if this fails
  2069. }
  2070. config.myStream = null;
  2071. }
  2072. }
  2073. // Skip the getUserMedia part
  2074. config.streamExternal = true;
  2075. pluginHandle.consentDialog(false);
  2076. streamsDone(handleId, jsep, media, callbacks, stream);
  2077. return;
  2078. }
  2079. if(isAudioSendEnabled(media) || isVideoSendEnabled(media)) {
  2080. if(!Janus.isGetUserMediaAvailable()) {
  2081. callbacks.error("getUserMedia not available");
  2082. return;
  2083. }
  2084. var constraints = { mandatory: {}, optional: []};
  2085. pluginHandle.consentDialog(true);
  2086. var audioSupport = isAudioSendEnabled(media);
  2087. if(audioSupport === true && media != undefined && media != null) {
  2088. if(typeof media.audio === 'object') {
  2089. audioSupport = media.audio;
  2090. }
  2091. }
  2092. var videoSupport = isVideoSendEnabled(media);
  2093. if(videoSupport === true && media != undefined && media != null) {
  2094. var simulcast = callbacks.simulcast === true ? true : false;
  2095. var simulcast2 = callbacks.simulcast2 === true ? true : false;
  2096. if((simulcast || simulcast2) && !jsep && (media.video === undefined || media.video === false))
  2097. media.video = "hires";
  2098. if(media.video && media.video != 'screen' && media.video != 'window') {
  2099. if(typeof media.video === 'object') {
  2100. videoSupport = media.video;
  2101. } else {
  2102. var width = 0;
  2103. var height = 0, maxHeight = 0;
  2104. if(media.video === 'lowres') {
  2105. // Small resolution, 4:3
  2106. height = 240;
  2107. maxHeight = 240;
  2108. width = 320;
  2109. } else if(media.video === 'lowres-16:9') {
  2110. // Small resolution, 16:9
  2111. height = 180;
  2112. maxHeight = 180;
  2113. width = 320;
  2114. } else if(media.video === 'hires' || media.video === 'hires-16:9' || media.video === 'hdres') {
  2115. // High(HD) resolution is only 16:9
  2116. height = 720;
  2117. maxHeight = 720;
  2118. width = 1280;
  2119. } else if(media.video === 'fhdres') {
  2120. // Full HD resolution is only 16:9
  2121. height = 1080;
  2122. maxHeight = 1080;
  2123. width = 1920;
  2124. } else if(media.video === '4kres') {
  2125. // 4K resolution is only 16:9
  2126. height = 2160;
  2127. maxHeight = 2160;
  2128. width = 3840;
  2129. } else if(media.video === 'stdres') {
  2130. // Normal resolution, 4:3
  2131. height = 480;
  2132. maxHeight = 480;
  2133. width = 640;
  2134. } else if(media.video === 'stdres-16:9') {
  2135. // Normal resolution, 16:9
  2136. height = 360;
  2137. maxHeight = 360;
  2138. width = 640;
  2139. } else {
  2140. Janus.log("Default video setting is stdres 4:3");
  2141. height = 480;
  2142. maxHeight = 480;
  2143. width = 640;
  2144. }
  2145. Janus.log("Adding media constraint:", media.video);
  2146. videoSupport = {
  2147. 'height': {'ideal': height},
  2148. 'width': {'ideal': width}
  2149. };
  2150. Janus.log("Adding video constraint:", videoSupport);
  2151. }
  2152. } else if(media.video === 'screen' || media.video === 'window') {
  2153. if(!media.screenshareFrameRate) {
  2154. media.screenshareFrameRate = 3;
  2155. }
  2156. if(navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia) {
  2157. // The new experimental getDisplayMedia API is available, let's use that
  2158. // https://groups.google.com/forum/#!topic/discuss-webrtc/Uf0SrR4uxzk
  2159. // https://webrtchacks.com/chrome-screensharing-getdisplaymedia/
  2160. navigator.mediaDevices.getDisplayMedia({ video: true })
  2161. .then(function(stream) {
  2162. pluginHandle.consentDialog(false);
  2163. if(isAudioSendEnabled(media) && !media.keepAudio) {
  2164. navigator.mediaDevices.getUserMedia({ audio: true, video: false })
  2165. .then(function (audioStream) {
  2166. stream.addTrack(audioStream.getAudioTracks()[0]);
  2167. streamsDone(handleId, jsep, media, callbacks, stream);
  2168. })
  2169. } else {
  2170. streamsDone(handleId, jsep, media, callbacks, stream);
  2171. }
  2172. }, function (error) {
  2173. pluginHandle.consentDialog(false);
  2174. callbacks.error(error);
  2175. });
  2176. return;
  2177. }
  2178. // We're going to try and use the extension for Chrome 34+, the old approach
  2179. // for older versions of Chrome, or the experimental support in Firefox 33+
  2180. function callbackUserMedia (error, stream) {
  2181. pluginHandle.consentDialog(false);
  2182. if(error) {
  2183. callbacks.error(error);
  2184. } else {
  2185. streamsDone(handleId, jsep, media, callbacks, stream);
  2186. }
  2187. };
  2188. function getScreenMedia(constraints, gsmCallback, useAudio) {
  2189. Janus.log("Adding media constraint (screen capture)");
  2190. Janus.debug(constraints);
  2191. navigator.mediaDevices.getUserMedia(constraints)
  2192. .then(function(stream) {
  2193. if(useAudio) {
  2194. navigator.mediaDevices.getUserMedia({ audio: true, video: false })
  2195. .then(function (audioStream) {
  2196. stream.addTrack(audioStream.getAudioTracks()[0]);
  2197. gsmCallback(null, stream);
  2198. })
  2199. } else {
  2200. gsmCallback(null, stream);
  2201. }
  2202. })
  2203. .catch(function(error) { pluginHandle.consentDialog(false); gsmCallback(error); });
  2204. };
  2205. if(Janus.webRTCAdapter.browserDetails.browser === 'chrome') {
  2206. var chromever = Janus.webRTCAdapter.browserDetails.version;
  2207. var maxver = 33;
  2208. if(window.navigator.userAgent.match('Linux'))
  2209. maxver = 35; // "known" crash in chrome 34 and 35 on linux
  2210. if(chromever >= 26 && chromever <= maxver) {
  2211. // Chrome 26->33 requires some awkward chrome://flags manipulation
  2212. constraints = {
  2213. video: {
  2214. mandatory: {
  2215. googLeakyBucket: true,
  2216. maxWidth: window.screen.width,
  2217. maxHeight: window.screen.height,
  2218. minFrameRate: media.screenshareFrameRate,
  2219. maxFrameRate: media.screenshareFrameRate,
  2220. chromeMediaSource: 'screen'
  2221. }
  2222. },
  2223. audio: isAudioSendEnabled(media) && !media.keepAudio
  2224. };
  2225. getScreenMedia(constraints, callbackUserMedia);
  2226. } else {
  2227. // Chrome 34+ requires an extension
  2228. Janus.extension.getScreen(function (error, sourceId) {
  2229. if (error) {
  2230. pluginHandle.consentDialog(false);
  2231. return callbacks.error(error);
  2232. }
  2233. constraints = {
  2234. audio: false,
  2235. video: {
  2236. mandatory: {
  2237. chromeMediaSource: 'desktop',
  2238. maxWidth: window.screen.width,
  2239. maxHeight: window.screen.height,
  2240. minFrameRate: media.screenshareFrameRate,
  2241. maxFrameRate: media.screenshareFrameRate,
  2242. },
  2243. optional: [
  2244. {googLeakyBucket: true},
  2245. {googTemporalLayeredScreencast: true}
  2246. ]
  2247. }
  2248. };
  2249. constraints.video.mandatory.chromeMediaSourceId = sourceId;
  2250. getScreenMedia(constraints, callbackUserMedia,
  2251. isAudioSendEnabled(media) && !media.keepAudio);
  2252. });
  2253. }
  2254. } else if(Janus.webRTCAdapter.browserDetails.browser === 'firefox') {
  2255. if(Janus.webRTCAdapter.browserDetails.version >= 33) {
  2256. // Firefox 33+ has experimental support for screen sharing
  2257. constraints = {
  2258. video: {
  2259. mozMediaSource: media.video,
  2260. mediaSource: media.video
  2261. },
  2262. audio: isAudioSendEnabled(media) && !media.keepAudio
  2263. };
  2264. getScreenMedia(constraints, function (err, stream) {
  2265. callbackUserMedia(err, stream);
  2266. // Workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=1045810
  2267. if (!err) {
  2268. var lastTime = stream.currentTime;
  2269. var polly = window.setInterval(function () {
  2270. if(!stream)
  2271. window.clearInterval(polly);
  2272. if(stream.currentTime == lastTime) {
  2273. window.clearInterval(polly);
  2274. if(stream.onended) {
  2275. stream.onended();
  2276. }
  2277. }
  2278. lastTime = stream.currentTime;
  2279. }, 500);
  2280. }
  2281. });
  2282. } else {
  2283. var error = new Error('NavigatorUserMediaError');
  2284. error.name = 'Your version of Firefox does not support screen sharing, please install Firefox 33 (or more recent versions)';
  2285. pluginHandle.consentDialog(false);
  2286. callbacks.error(error);
  2287. return;
  2288. }
  2289. }
  2290. return;
  2291. }
  2292. }
  2293. // If we got here, we're not screensharing
  2294. if(media === null || media === undefined || media.video !== 'screen') {
  2295. // Check whether all media sources are actually available or not
  2296. navigator.mediaDevices.enumerateDevices().then(function(devices) {
  2297. var audioExist = devices.some(function(device) {
  2298. return device.kind === 'audioinput';
  2299. }),
  2300. videoExist = isScreenSendEnabled(media) || devices.some(function(device) {
  2301. return device.kind === 'videoinput';
  2302. });
  2303. // Check whether a missing device is really a problem
  2304. var audioSend = isAudioSendEnabled(media);
  2305. var videoSend = isVideoSendEnabled(media);
  2306. var needAudioDevice = isAudioSendRequired(media);
  2307. var needVideoDevice = isVideoSendRequired(media);
  2308. if(audioSend || videoSend || needAudioDevice || needVideoDevice) {
  2309. // We need to send either audio or video
  2310. var haveAudioDevice = audioSend ? audioExist : false;
  2311. var haveVideoDevice = videoSend ? videoExist : false;
  2312. if(!haveAudioDevice && !haveVideoDevice) {
  2313. // FIXME Should we really give up, or just assume recvonly for both?
  2314. pluginHandle.consentDialog(false);
  2315. callbacks.error('No capture device found');
  2316. return false;
  2317. } else if(!haveAudioDevice && needAudioDevice) {
  2318. pluginHandle.consentDialog(false);
  2319. callbacks.error('Audio capture is required, but no capture device found');
  2320. return false;
  2321. } else if(!haveVideoDevice && needVideoDevice) {
  2322. pluginHandle.consentDialog(false);
  2323. callbacks.error('Video capture is required, but no capture device found');
  2324. return false;
  2325. }
  2326. }
  2327. var gumConstraints = {
  2328. audio: (audioExist && !media.keepAudio) ? audioSupport : false,
  2329. video: (videoExist && !media.keepVideo) ? videoSupport : false
  2330. };
  2331. Janus.debug("getUserMedia constraints", gumConstraints);
  2332. if (!gumConstraints.audio && !gumConstraints.video) {
  2333. pluginHandle.consentDialog(false);
  2334. streamsDone(handleId, jsep, media, callbacks, stream);
  2335. } else {
  2336. navigator.mediaDevices.getUserMedia(gumConstraints)
  2337. .then(function(stream) {
  2338. pluginHandle.consentDialog(false);
  2339. streamsDone(handleId, jsep, media, callbacks, stream);
  2340. }).catch(function(error) {
  2341. pluginHandle.consentDialog(false);
  2342. callbacks.error({code: error.code, name: error.name, message: error.message});
  2343. });
  2344. }
  2345. })
  2346. .catch(function(error) {
  2347. pluginHandle.consentDialog(false);
  2348. callbacks.error('enumerateDevices error', error);
  2349. });
  2350. }
  2351. } else {
  2352. // No need to do a getUserMedia, create offer/answer right away
  2353. streamsDone(handleId, jsep, media, callbacks);
  2354. }
  2355. }
  2356. function prepareWebrtcPeer(handleId, callbacks) {
  2357. callbacks = callbacks || {};
  2358. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
  2359. callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : webrtcError;
  2360. var jsep = callbacks.jsep;
  2361. var pluginHandle = pluginHandles[handleId];
  2362. if(pluginHandle === null || pluginHandle === undefined ||
  2363. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  2364. Janus.warn("Invalid handle");
  2365. callbacks.error("Invalid handle");
  2366. return;
  2367. }
  2368. var config = pluginHandle.webrtcStuff;
  2369. if(jsep !== undefined && jsep !== null) {
  2370. if(config.pc === null) {
  2371. Janus.warn("Wait, no PeerConnection?? if this is an answer, use createAnswer and not handleRemoteJsep");
  2372. callbacks.error("No PeerConnection: if this is an answer, use createAnswer and not handleRemoteJsep");
  2373. return;
  2374. }
  2375. config.pc.setRemoteDescription(jsep)
  2376. .then(function() {
  2377. Janus.log("Remote description accepted!");
  2378. config.remoteSdp = jsep.sdp;
  2379. // Any trickle candidate we cached?
  2380. if(config.candidates && config.candidates.length > 0) {
  2381. for(var i = 0; i< config.candidates.length; i++) {
  2382. var candidate = config.candidates[i];
  2383. Janus.debug("Adding remote candidate:", candidate);
  2384. if(!candidate || candidate.completed === true) {
  2385. // end-of-candidates
  2386. config.pc.addIceCandidate(Janus.endOfCandidates);
  2387. } else {
  2388. // New candidate
  2389. config.pc.addIceCandidate(candidate);
  2390. }
  2391. }
  2392. config.candidates = [];
  2393. }
  2394. // Done
  2395. callbacks.success();
  2396. }, callbacks.error);
  2397. } else {
  2398. callbacks.error("Invalid JSEP");
  2399. }
  2400. }
  2401. function createOffer(handleId, media, callbacks) {
  2402. callbacks = callbacks || {};
  2403. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
  2404. callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : Janus.noop;
  2405. callbacks.customizeSdp = (typeof callbacks.customizeSdp == "function") ? callbacks.customizeSdp : Janus.noop;
  2406. var pluginHandle = pluginHandles[handleId];
  2407. if(pluginHandle === null || pluginHandle === undefined ||
  2408. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  2409. Janus.warn("Invalid handle");
  2410. callbacks.error("Invalid handle");
  2411. return;
  2412. }
  2413. var config = pluginHandle.webrtcStuff;
  2414. var simulcast = callbacks.simulcast === true ? true : false;
  2415. if(!simulcast) {
  2416. Janus.log("Creating offer (iceDone=" + config.iceDone + ")");
  2417. } else {
  2418. Janus.log("Creating offer (iceDone=" + config.iceDone + ", simulcast=" + simulcast + ")");
  2419. }
  2420. // https://code.google.com/p/webrtc/issues/detail?id=3508
  2421. var mediaConstraints = {};
  2422. if(Janus.unifiedPlan) {
  2423. // We can use Transceivers
  2424. var audioTransceiver = null, videoTransceiver = null;
  2425. var transceivers = config.pc.getTransceivers();
  2426. if(transceivers && transceivers.length > 0) {
  2427. for(var i in transceivers) {
  2428. var t = transceivers[i];
  2429. if((t.sender && t.sender.track && t.sender.track.kind === "audio") ||
  2430. (t.receiver && t.receiver.track && t.receiver.track.kind === "audio")) {
  2431. if(!audioTransceiver)
  2432. audioTransceiver = t;
  2433. continue;
  2434. }
  2435. if((t.sender && t.sender.track && t.sender.track.kind === "video") ||
  2436. (t.receiver && t.receiver.track && t.receiver.track.kind === "video")) {
  2437. if(!videoTransceiver)
  2438. videoTransceiver = t;
  2439. continue;
  2440. }
  2441. }
  2442. }
  2443. // Handle audio (and related changes, if any)
  2444. var audioSend = isAudioSendEnabled(media);
  2445. var audioRecv = isAudioRecvEnabled(media);
  2446. if(!audioSend && !audioRecv) {
  2447. // Audio disabled: have we removed it?
  2448. if(media.removeAudio && audioTransceiver) {
  2449. if (audioTransceiver.setDirection) {
  2450. audioTransceiver.setDirection("inactive");
  2451. } else {
  2452. audioTransceiver.direction = "inactive";
  2453. }
  2454. Janus.log("Setting audio transceiver to inactive:", audioTransceiver);
  2455. }
  2456. } else {
  2457. // Take care of audio m-line
  2458. if(audioSend && audioRecv) {
  2459. if(audioTransceiver) {
  2460. if (audioTransceiver.setDirection) {
  2461. audioTransceiver.setDirection("sendrecv");
  2462. } else {
  2463. audioTransceiver.direction = "sendrecv";
  2464. }
  2465. Janus.log("Setting audio transceiver to sendrecv:", audioTransceiver);
  2466. }
  2467. } else if(audioSend && !audioRecv) {
  2468. if(audioTransceiver) {
  2469. if (audioTransceiver.setDirection) {
  2470. audioTransceiver.setDirection("sendonly");
  2471. } else {
  2472. audioTransceiver.direction = "sendonly";
  2473. }
  2474. Janus.log("Setting audio transceiver to sendonly:", audioTransceiver);
  2475. }
  2476. } else if(!audioSend && audioRecv) {
  2477. if(audioTransceiver) {
  2478. if (audioTransceiver.setDirection) {
  2479. audioTransceiver.setDirection("recvonly");
  2480. } else {
  2481. audioTransceiver.direction = "recvonly";
  2482. }
  2483. Janus.log("Setting audio transceiver to recvonly:", audioTransceiver);
  2484. } else {
  2485. // In theory, this is the only case where we might not have a transceiver yet
  2486. audioTransceiver = config.pc.addTransceiver("audio", { direction: "recvonly" });
  2487. Janus.log("Adding recvonly audio transceiver:", audioTransceiver);
  2488. }
  2489. }
  2490. }
  2491. // Handle video (and related changes, if any)
  2492. var videoSend = isVideoSendEnabled(media);
  2493. var videoRecv = isVideoRecvEnabled(media);
  2494. if(!videoSend && !videoRecv) {
  2495. // Video disabled: have we removed it?
  2496. if(media.removeVideo && videoTransceiver) {
  2497. if (videoTransceiver.setDirection) {
  2498. videoTransceiver.setDirection("inactive");
  2499. } else {
  2500. videoTransceiver.direction = "inactive";
  2501. }
  2502. Janus.log("Setting video transceiver to inactive:", videoTransceiver);
  2503. }
  2504. } else {
  2505. // Take care of video m-line
  2506. if(videoSend && videoRecv) {
  2507. if(videoTransceiver) {
  2508. if (videoTransceiver.setDirection) {
  2509. videoTransceiver.setDirection("sendrecv");
  2510. } else {
  2511. videoTransceiver.direction = "sendrecv";
  2512. }
  2513. Janus.log("Setting video transceiver to sendrecv:", videoTransceiver);
  2514. }
  2515. } else if(videoSend && !videoRecv) {
  2516. if(videoTransceiver) {
  2517. if (videoTransceiver.setDirection) {
  2518. videoTransceiver.setDirection("sendonly");
  2519. } else {
  2520. videoTransceiver.direction = "sendonly";
  2521. }
  2522. Janus.log("Setting video transceiver to sendonly:", videoTransceiver);
  2523. }
  2524. } else if(!videoSend && videoRecv) {
  2525. if(videoTransceiver) {
  2526. if (videoTransceiver.setDirection) {
  2527. videoTransceiver.setDirection("recvonly");
  2528. } else {
  2529. videoTransceiver.direction = "recvonly";
  2530. }
  2531. Janus.log("Setting video transceiver to recvonly:", videoTransceiver);
  2532. } else {
  2533. // In theory, this is the only case where we might not have a transceiver yet
  2534. videoTransceiver = config.pc.addTransceiver("video", { direction: "recvonly" });
  2535. Janus.log("Adding recvonly video transceiver:", videoTransceiver);
  2536. }
  2537. }
  2538. }
  2539. } else {
  2540. mediaConstraints["offerToReceiveAudio"] = isAudioRecvEnabled(media);
  2541. mediaConstraints["offerToReceiveVideo"] = isVideoRecvEnabled(media);
  2542. }
  2543. var iceRestart = callbacks.iceRestart === true ? true : false;
  2544. if(iceRestart) {
  2545. mediaConstraints["iceRestart"] = true;
  2546. }
  2547. Janus.debug(mediaConstraints);
  2548. // Check if this is Firefox and we've been asked to do simulcasting
  2549. var sendVideo = isVideoSendEnabled(media);
  2550. if(sendVideo && simulcast && Janus.webRTCAdapter.browserDetails.browser === "firefox") {
  2551. // FIXME Based on https://gist.github.com/voluntas/088bc3cc62094730647b
  2552. Janus.log("Enabling Simulcasting for Firefox (RID)");
  2553. var sender = config.pc.getSenders().find(function(s) {return s.track.kind == "video"});
  2554. if(sender) {
  2555. var parameters = sender.getParameters();
  2556. if(!parameters)
  2557. parameters = {};
  2558. const maxBitrates = getMaxBitrates(callbacks.simulcastMaxBitrates);
  2559. parameters.encodings = [
  2560. { rid: "h", active: true, maxBitrate: maxBitrates.high },
  2561. { rid: "m", active: true, maxBitrate: maxBitrates.medium, scaleResolutionDownBy: 2 },
  2562. { rid: "l", active: true, maxBitrate: maxBitrates.low, scaleResolutionDownBy: 4 }
  2563. ];
  2564. sender.setParameters(parameters);
  2565. }
  2566. }
  2567. config.pc.createOffer(mediaConstraints)
  2568. .then(function(offer) {
  2569. Janus.debug(offer);
  2570. // JSON.stringify doesn't work on some WebRTC objects anymore
  2571. // See https://code.google.com/p/chromium/issues/detail?id=467366
  2572. var jsep = {
  2573. "type": offer.type,
  2574. "sdp": offer.sdp
  2575. };
  2576. callbacks.customizeSdp(jsep);
  2577. offer.sdp = jsep.sdp;
  2578. Janus.log("Setting local description");
  2579. if(sendVideo && simulcast) {
  2580. // This SDP munging only works with Chrome (Safari STP may support it too)
  2581. if(Janus.webRTCAdapter.browserDetails.browser === "chrome" ||
  2582. Janus.webRTCAdapter.browserDetails.browser === "safari") {
  2583. Janus.log("Enabling Simulcasting for Chrome (SDP munging)");
  2584. offer.sdp = mungeSdpForSimulcasting(offer.sdp);
  2585. } else if(Janus.webRTCAdapter.browserDetails.browser !== "firefox") {
  2586. Janus.warn("simulcast=true, but this is not Chrome nor Firefox, ignoring");
  2587. }
  2588. }
  2589. config.mySdp = offer.sdp;
  2590. config.pc.setLocalDescription(offer)
  2591. .catch(callbacks.error);
  2592. config.mediaConstraints = mediaConstraints;
  2593. if(!config.iceDone && !config.trickle) {
  2594. // Don't do anything until we have all candidates
  2595. Janus.log("Waiting for all candidates...");
  2596. return;
  2597. }
  2598. Janus.log("Offer ready");
  2599. Janus.debug(callbacks);
  2600. callbacks.success(offer);
  2601. }, callbacks.error);
  2602. }
  2603. function createAnswer(handleId, media, callbacks) {
  2604. callbacks = callbacks || {};
  2605. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
  2606. callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : Janus.noop;
  2607. callbacks.customizeSdp = (typeof callbacks.customizeSdp == "function") ? callbacks.customizeSdp : Janus.noop;
  2608. var pluginHandle = pluginHandles[handleId];
  2609. if(pluginHandle === null || pluginHandle === undefined ||
  2610. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  2611. Janus.warn("Invalid handle");
  2612. callbacks.error("Invalid handle");
  2613. return;
  2614. }
  2615. var config = pluginHandle.webrtcStuff;
  2616. var simulcast = callbacks.simulcast === true ? true : false;
  2617. if(!simulcast) {
  2618. Janus.log("Creating answer (iceDone=" + config.iceDone + ")");
  2619. } else {
  2620. Janus.log("Creating answer (iceDone=" + config.iceDone + ", simulcast=" + simulcast + ")");
  2621. }
  2622. var mediaConstraints = null;
  2623. if(Janus.unifiedPlan) {
  2624. // We can use Transceivers
  2625. mediaConstraints = {};
  2626. var audioTransceiver = null, videoTransceiver = null;
  2627. var transceivers = config.pc.getTransceivers();
  2628. if(transceivers && transceivers.length > 0) {
  2629. for(var i in transceivers) {
  2630. var t = transceivers[i];
  2631. if((t.sender && t.sender.track && t.sender.track.kind === "audio") ||
  2632. (t.receiver && t.receiver.track && t.receiver.track.kind === "audio")) {
  2633. if(!audioTransceiver)
  2634. audioTransceiver = t;
  2635. continue;
  2636. }
  2637. if((t.sender && t.sender.track && t.sender.track.kind === "video") ||
  2638. (t.receiver && t.receiver.track && t.receiver.track.kind === "video")) {
  2639. if(!videoTransceiver)
  2640. videoTransceiver = t;
  2641. continue;
  2642. }
  2643. }
  2644. }
  2645. // Handle audio (and related changes, if any)
  2646. var audioSend = isAudioSendEnabled(media);
  2647. var audioRecv = isAudioRecvEnabled(media);
  2648. if(!audioSend && !audioRecv) {
  2649. // Audio disabled: have we removed it?
  2650. if(media.removeAudio && audioTransceiver) {
  2651. try {
  2652. if (audioTransceiver.setDirection) {
  2653. audioTransceiver.setDirection("inactive");
  2654. } else {
  2655. audioTransceiver.direction = "inactive";
  2656. }
  2657. Janus.log("Setting audio transceiver to inactive:", audioTransceiver);
  2658. } catch(e) {
  2659. Janus.error(e);
  2660. }
  2661. }
  2662. } else {
  2663. // Take care of audio m-line
  2664. if(audioSend && audioRecv) {
  2665. if(audioTransceiver) {
  2666. try {
  2667. if (audioTransceiver.setDirection) {
  2668. audioTransceiver.setDirection("sendrecv");
  2669. } else {
  2670. audioTransceiver.direction = "sendrecv";
  2671. }
  2672. Janus.log("Setting audio transceiver to sendrecv:", audioTransceiver);
  2673. } catch(e) {
  2674. Janus.error(e);
  2675. }
  2676. }
  2677. } else if(audioSend && !audioRecv) {
  2678. try {
  2679. if(audioTransceiver) {
  2680. if (audioTransceiver.setDirection) {
  2681. audioTransceiver.setDirection("sendonly");
  2682. } else {
  2683. audioTransceiver.direction = "sendonly";
  2684. }
  2685. Janus.log("Setting audio transceiver to sendonly:", audioTransceiver);
  2686. }
  2687. } catch(e) {
  2688. Janus.error(e);
  2689. }
  2690. } else if(!audioSend && audioRecv) {
  2691. if(audioTransceiver) {
  2692. try {
  2693. if (audioTransceiver.setDirection) {
  2694. audioTransceiver.setDirection("recvonly");
  2695. } else {
  2696. audioTransceiver.direction = "recvonly";
  2697. }
  2698. Janus.log("Setting audio transceiver to recvonly:", audioTransceiver);
  2699. } catch(e) {
  2700. Janus.error(e);
  2701. }
  2702. } else {
  2703. // In theory, this is the only case where we might not have a transceiver yet
  2704. audioTransceiver = config.pc.addTransceiver("audio", { direction: "recvonly" });
  2705. Janus.log("Adding recvonly audio transceiver:", audioTransceiver);
  2706. }
  2707. }
  2708. }
  2709. // Handle video (and related changes, if any)
  2710. var videoSend = isVideoSendEnabled(media);
  2711. var videoRecv = isVideoRecvEnabled(media);
  2712. if(!videoSend && !videoRecv) {
  2713. // Video disabled: have we removed it?
  2714. if(media.removeVideo && videoTransceiver) {
  2715. try {
  2716. if (videoTransceiver.setDirection) {
  2717. videoTransceiver.setDirection("inactive");
  2718. } else {
  2719. videoTransceiver.direction = "inactive";
  2720. }
  2721. Janus.log("Setting video transceiver to inactive:", videoTransceiver);
  2722. } catch(e) {
  2723. Janus.error(e);
  2724. }
  2725. }
  2726. } else {
  2727. // Take care of video m-line
  2728. if(videoSend && videoRecv) {
  2729. if(videoTransceiver) {
  2730. try {
  2731. if (videoTransceiver.setDirection) {
  2732. videoTransceiver.setDirection("sendrecv");
  2733. } else {
  2734. videoTransceiver.direction = "sendrecv";
  2735. }
  2736. Janus.log("Setting video transceiver to sendrecv:", videoTransceiver);
  2737. } catch(e) {
  2738. Janus.error(e);
  2739. }
  2740. }
  2741. } else if(videoSend && !videoRecv) {
  2742. if(videoTransceiver) {
  2743. try {
  2744. if (videoTransceiver.setDirection) {
  2745. videoTransceiver.setDirection("sendonly");
  2746. } else {
  2747. videoTransceiver.direction = "sendonly";
  2748. }
  2749. Janus.log("Setting video transceiver to sendonly:", videoTransceiver);
  2750. } catch(e) {
  2751. Janus.error(e);
  2752. }
  2753. }
  2754. } else if(!videoSend && videoRecv) {
  2755. if(videoTransceiver) {
  2756. try {
  2757. if (videoTransceiver.setDirection) {
  2758. videoTransceiver.setDirection("recvonly");
  2759. } else {
  2760. videoTransceiver.direction = "recvonly";
  2761. }
  2762. Janus.log("Setting video transceiver to recvonly:", videoTransceiver);
  2763. } catch(e) {
  2764. Janus.error(e);
  2765. }
  2766. } else {
  2767. // In theory, this is the only case where we might not have a transceiver yet
  2768. videoTransceiver = config.pc.addTransceiver("video", { direction: "recvonly" });
  2769. Janus.log("Adding recvonly video transceiver:", videoTransceiver);
  2770. }
  2771. }
  2772. }
  2773. } else {
  2774. if(Janus.webRTCAdapter.browserDetails.browser == "firefox" || Janus.webRTCAdapter.browserDetails.browser == "edge") {
  2775. mediaConstraints = {
  2776. offerToReceiveAudio: isAudioRecvEnabled(media),
  2777. offerToReceiveVideo: isVideoRecvEnabled(media)
  2778. };
  2779. } else {
  2780. mediaConstraints = {
  2781. mandatory: {
  2782. OfferToReceiveAudio: isAudioRecvEnabled(media),
  2783. OfferToReceiveVideo: isVideoRecvEnabled(media)
  2784. }
  2785. };
  2786. }
  2787. }
  2788. Janus.debug(mediaConstraints);
  2789. // Check if this is Firefox and we've been asked to do simulcasting
  2790. var sendVideo = isVideoSendEnabled(media);
  2791. if(sendVideo && simulcast && Janus.webRTCAdapter.browserDetails.browser === "firefox") {
  2792. // FIXME Based on https://gist.github.com/voluntas/088bc3cc62094730647b
  2793. Janus.log("Enabling Simulcasting for Firefox (RID)");
  2794. var sender = config.pc.getSenders()[1];
  2795. Janus.log(sender);
  2796. var parameters = sender.getParameters();
  2797. Janus.log(parameters);
  2798. const maxBitrates = getMaxBitrates(callbacks.simulcastMaxBitrates);
  2799. sender.setParameters({encodings: [
  2800. { rid: "high", active: true, priority: "high", maxBitrate: maxBitrates.high },
  2801. { rid: "medium", active: true, priority: "medium", maxBitrate: maxBitrates.medium },
  2802. { rid: "low", active: true, priority: "low", maxBitrate: maxBitrates.low }
  2803. ]});
  2804. }
  2805. config.pc.createAnswer(mediaConstraints)
  2806. .then(function(answer) {
  2807. Janus.debug(answer);
  2808. // JSON.stringify doesn't work on some WebRTC objects anymore
  2809. // See https://code.google.com/p/chromium/issues/detail?id=467366
  2810. var jsep = {
  2811. "type": answer.type,
  2812. "sdp": answer.sdp
  2813. };
  2814. callbacks.customizeSdp(jsep);
  2815. answer.sdp = jsep.sdp;
  2816. Janus.log("Setting local description");
  2817. if(sendVideo && simulcast) {
  2818. // This SDP munging only works with Chrome
  2819. if(Janus.webRTCAdapter.browserDetails.browser === "chrome") {
  2820. // FIXME Apparently trying to simulcast when answering breaks video in Chrome...
  2821. //~ Janus.log("Enabling Simulcasting for Chrome (SDP munging)");
  2822. //~ answer.sdp = mungeSdpForSimulcasting(answer.sdp);
  2823. Janus.warn("simulcast=true, but this is an answer, and video breaks in Chrome if we enable it");
  2824. } else if(Janus.webRTCAdapter.browserDetails.browser !== "firefox") {
  2825. Janus.warn("simulcast=true, but this is not Chrome nor Firefox, ignoring");
  2826. }
  2827. }
  2828. config.mySdp = answer.sdp;
  2829. config.pc.setLocalDescription(answer)
  2830. .catch(callbacks.error);
  2831. config.mediaConstraints = mediaConstraints;
  2832. if(!config.iceDone && !config.trickle) {
  2833. // Don't do anything until we have all candidates
  2834. Janus.log("Waiting for all candidates...");
  2835. return;
  2836. }
  2837. callbacks.success(answer);
  2838. }, callbacks.error);
  2839. }
  2840. function sendSDP(handleId, callbacks) {
  2841. callbacks = callbacks || {};
  2842. callbacks.success = (typeof callbacks.success == "function") ? callbacks.success : Janus.noop;
  2843. callbacks.error = (typeof callbacks.error == "function") ? callbacks.error : Janus.noop;
  2844. var pluginHandle = pluginHandles[handleId];
  2845. if(pluginHandle === null || pluginHandle === undefined ||
  2846. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  2847. Janus.warn("Invalid handle, not sending anything");
  2848. return;
  2849. }
  2850. var config = pluginHandle.webrtcStuff;
  2851. Janus.log("Sending offer/answer SDP...");
  2852. if(config.mySdp === null || config.mySdp === undefined) {
  2853. Janus.warn("Local SDP instance is invalid, not sending anything...");
  2854. return;
  2855. }
  2856. config.mySdp = {
  2857. "type": config.pc.localDescription.type,
  2858. "sdp": config.pc.localDescription.sdp
  2859. };
  2860. if(config.trickle === false)
  2861. config.mySdp["trickle"] = false;
  2862. Janus.debug(callbacks);
  2863. config.sdpSent = true;
  2864. callbacks.success(config.mySdp);
  2865. }
  2866. function getVolume(handleId, remote) {
  2867. var pluginHandle = pluginHandles[handleId];
  2868. if(pluginHandle === null || pluginHandle === undefined ||
  2869. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  2870. Janus.warn("Invalid handle");
  2871. return 0;
  2872. }
  2873. var stream = remote ? "remote" : "local";
  2874. var config = pluginHandle.webrtcStuff;
  2875. if(!config.volume[stream])
  2876. config.volume[stream] = { value: 0 };
  2877. // Start getting the volume, if getStats is supported
  2878. if(config.pc.getStats && Janus.webRTCAdapter.browserDetails.browser === "chrome") {
  2879. if(remote && (config.remoteStream === null || config.remoteStream === undefined)) {
  2880. Janus.warn("Remote stream unavailable");
  2881. return 0;
  2882. } else if(!remote && (config.myStream === null || config.myStream === undefined)) {
  2883. Janus.warn("Local stream unavailable");
  2884. return 0;
  2885. }
  2886. if(config.volume[stream].timer === null || config.volume[stream].timer === undefined) {
  2887. Janus.log("Starting " + stream + " volume monitor");
  2888. config.volume[stream].timer = setInterval(function() {
  2889. config.pc.getStats(function(stats) {
  2890. var results = stats.result();
  2891. for(var i=0; i<results.length; i++) {
  2892. var res = results[i];
  2893. if(res.type == 'ssrc') {
  2894. if(remote && res.stat('audioOutputLevel'))
  2895. config.volume[stream].value = parseInt(res.stat('audioOutputLevel'));
  2896. else if(!remote && res.stat('audioInputLevel'))
  2897. config.volume[stream].value = parseInt(res.stat('audioInputLevel'));
  2898. }
  2899. }
  2900. });
  2901. }, 200);
  2902. return 0; // We don't have a volume to return yet
  2903. }
  2904. return config.volume[stream].value;
  2905. } else {
  2906. // audioInputLevel and audioOutputLevel seem only available in Chrome? audioLevel
  2907. // seems to be available on Chrome and Firefox, but they don't seem to work
  2908. Janus.warn("Getting the " + stream + " volume unsupported by browser");
  2909. return 0;
  2910. }
  2911. }
  2912. function isMuted(handleId, video) {
  2913. var pluginHandle = pluginHandles[handleId];
  2914. if(pluginHandle === null || pluginHandle === undefined ||
  2915. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  2916. Janus.warn("Invalid handle");
  2917. return true;
  2918. }
  2919. var config = pluginHandle.webrtcStuff;
  2920. if(config.pc === null || config.pc === undefined) {
  2921. Janus.warn("Invalid PeerConnection");
  2922. return true;
  2923. }
  2924. if(config.myStream === undefined || config.myStream === null) {
  2925. Janus.warn("Invalid local MediaStream");
  2926. return true;
  2927. }
  2928. if(video) {
  2929. // Check video track
  2930. if(config.myStream.getVideoTracks() === null
  2931. || config.myStream.getVideoTracks() === undefined
  2932. || config.myStream.getVideoTracks().length === 0) {
  2933. Janus.warn("No video track");
  2934. return true;
  2935. }
  2936. return !config.myStream.getVideoTracks()[0].enabled;
  2937. } else {
  2938. // Check audio track
  2939. if(config.myStream.getAudioTracks() === null
  2940. || config.myStream.getAudioTracks() === undefined
  2941. || config.myStream.getAudioTracks().length === 0) {
  2942. Janus.warn("No audio track");
  2943. return true;
  2944. }
  2945. return !config.myStream.getAudioTracks()[0].enabled;
  2946. }
  2947. }
  2948. function mute(handleId, video, mute) {
  2949. var pluginHandle = pluginHandles[handleId];
  2950. if(pluginHandle === null || pluginHandle === undefined ||
  2951. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  2952. Janus.warn("Invalid handle");
  2953. return false;
  2954. }
  2955. var config = pluginHandle.webrtcStuff;
  2956. if(config.pc === null || config.pc === undefined) {
  2957. Janus.warn("Invalid PeerConnection");
  2958. return false;
  2959. }
  2960. if(config.myStream === undefined || config.myStream === null) {
  2961. Janus.warn("Invalid local MediaStream");
  2962. return false;
  2963. }
  2964. if(video) {
  2965. // Mute/unmute video track
  2966. if(config.myStream.getVideoTracks() === null
  2967. || config.myStream.getVideoTracks() === undefined
  2968. || config.myStream.getVideoTracks().length === 0) {
  2969. Janus.warn("No video track");
  2970. return false;
  2971. }
  2972. config.myStream.getVideoTracks()[0].enabled = mute ? false : true;
  2973. return true;
  2974. } else {
  2975. // Mute/unmute audio track
  2976. if(config.myStream.getAudioTracks() === null
  2977. || config.myStream.getAudioTracks() === undefined
  2978. || config.myStream.getAudioTracks().length === 0) {
  2979. Janus.warn("No audio track");
  2980. return false;
  2981. }
  2982. config.myStream.getAudioTracks()[0].enabled = mute ? false : true;
  2983. return true;
  2984. }
  2985. }
  2986. function getBitrate(handleId) {
  2987. var pluginHandle = pluginHandles[handleId];
  2988. if(pluginHandle === null || pluginHandle === undefined ||
  2989. pluginHandle.webrtcStuff === null || pluginHandle.webrtcStuff === undefined) {
  2990. Janus.warn("Invalid handle");
  2991. return "Invalid handle";
  2992. }
  2993. var config = pluginHandle.webrtcStuff;
  2994. if(config.pc === null || config.pc === undefined)
  2995. return "Invalid PeerConnection";
  2996. // Start getting the bitrate, if getStats is supported
  2997. if(config.pc.getStats) {
  2998. if(config.bitrate.timer === null || config.bitrate.timer === undefined) {
  2999. Janus.log("Starting bitrate timer (via getStats)");
  3000. config.bitrate.timer = setInterval(function() {
  3001. config.pc.getStats()
  3002. .then(function(stats) {
  3003. stats.forEach(function (res) {
  3004. if(!res)
  3005. return;
  3006. var inStats = false;
  3007. // Check if these are statistics on incoming media
  3008. if((res.mediaType === "video" || res.id.toLowerCase().indexOf("video") > -1) &&
  3009. res.type === "inbound-rtp" && res.id.indexOf("rtcp") < 0) {
  3010. // New stats
  3011. inStats = true;
  3012. } else if(res.type == 'ssrc' && res.bytesReceived &&
  3013. (res.googCodecName === "VP8" || res.googCodecName === "")) {
  3014. // Older Chromer versions
  3015. inStats = true;
  3016. }
  3017. // Parse stats now
  3018. if(inStats) {
  3019. config.bitrate.bsnow = res.bytesReceived;
  3020. config.bitrate.tsnow = res.timestamp;
  3021. if(config.bitrate.bsbefore === null || config.bitrate.tsbefore === null) {
  3022. // Skip this round
  3023. config.bitrate.bsbefore = config.bitrate.bsnow;
  3024. config.bitrate.tsbefore = config.bitrate.tsnow;
  3025. } else {
  3026. // Calculate bitrate
  3027. var timePassed = config.bitrate.tsnow - config.bitrate.tsbefore;
  3028. if(Janus.webRTCAdapter.browserDetails.browser == "safari")
  3029. timePassed = timePassed/1000; // Apparently the timestamp is in microseconds, in Safari
  3030. var bitRate = Math.round((config.bitrate.bsnow - config.bitrate.bsbefore) * 8 / timePassed);
  3031. if(Janus.webRTCAdapter.browserDetails.browser === 'safari')
  3032. bitRate = parseInt(bitRate/1000);
  3033. config.bitrate.value = bitRate + ' kbits/sec';
  3034. //~ Janus.log("Estimated bitrate is " + config.bitrate.value);
  3035. config.bitrate.bsbefore = config.bitrate.bsnow;
  3036. config.bitrate.tsbefore = config.bitrate.tsnow;
  3037. }
  3038. }
  3039. });
  3040. });
  3041. }, 1000);
  3042. return "0 kbits/sec"; // We don't have a bitrate value yet
  3043. }
  3044. return config.bitrate.value;
  3045. } else {
  3046. Janus.warn("Getting the video bitrate unsupported by browser");
  3047. return "Feature unsupported by browser";
  3048. }
  3049. }
  3050. function webrtcError(error) {
  3051. Janus.error("WebRTC error:", error);
  3052. }
  3053. function cleanupWebrtc(handleId, hangupRequest) {
  3054. Janus.log("Cleaning WebRTC stuff");
  3055. var pluginHandle = pluginHandles[handleId];
  3056. if(pluginHandle === null || pluginHandle === undefined) {
  3057. // Nothing to clean
  3058. return;
  3059. }
  3060. var config = pluginHandle.webrtcStuff;
  3061. if(config !== null && config !== undefined) {
  3062. if(hangupRequest === true) {
  3063. // Send a hangup request (we don't really care about the response)
  3064. var request = { "rtcgw": "hangup", "transaction": Janus.randomString(12) };
  3065. if(pluginHandle.token !== null && pluginHandle.token !== undefined)
  3066. request["token"] = pluginHandle.token;
  3067. if(apisecret !== null && apisecret !== undefined)
  3068. request["apisecret"] = apisecret;
  3069. Janus.debug("Sending hangup request (handle=" + handleId + "):");
  3070. Janus.debug(request);
  3071. if(websockets) {
  3072. request["session_id"] = sessionId;
  3073. request["handle_id"] = handleId;
  3074. ws.send(JSON.stringify(request));
  3075. } else {
  3076. Janus.httpAPICall(server + "/" + sessionId + "/" + handleId, {
  3077. verb: 'POST',
  3078. withCredentials: withCredentials,
  3079. body: request
  3080. });
  3081. }
  3082. }
  3083. // Cleanup stack
  3084. config.remoteStream = null;
  3085. if(config.volume) {
  3086. if(config.volume["local"] && config.volume["local"].timer)
  3087. clearInterval(config.volume["local"].timer);
  3088. if(config.volume["remote"] && config.volume["remote"].timer)
  3089. clearInterval(config.volume["remote"].timer);
  3090. }
  3091. config.volume = {};
  3092. if(config.bitrate.timer)
  3093. clearInterval(config.bitrate.timer);
  3094. config.bitrate.timer = null;
  3095. config.bitrate.bsnow = null;
  3096. config.bitrate.bsbefore = null;
  3097. config.bitrate.tsnow = null;
  3098. config.bitrate.tsbefore = null;
  3099. config.bitrate.value = null;
  3100. try {
  3101. // Try a MediaStreamTrack.stop() for each track
  3102. if(!config.streamExternal && config.myStream !== null && config.myStream !== undefined) {
  3103. Janus.log("Stopping local stream tracks");
  3104. var tracks = config.myStream.getTracks();
  3105. for(var i in tracks) {
  3106. var mst = tracks[i];
  3107. Janus.log(mst);
  3108. if(mst !== null && mst !== undefined)
  3109. mst.stop();
  3110. }
  3111. }
  3112. } catch(e) {
  3113. // Do nothing if this fails
  3114. }
  3115. config.streamExternal = false;
  3116. config.myStream = null;
  3117. // Close PeerConnection
  3118. try {
  3119. config.pc.close();
  3120. } catch(e) {
  3121. // Do nothing
  3122. }
  3123. config.pc = null;
  3124. config.candidates = null;
  3125. config.mySdp = null;
  3126. config.remoteSdp = null;
  3127. config.iceDone = false;
  3128. config.dataChannel = {};
  3129. config.dtmfSender = null;
  3130. }
  3131. pluginHandle.oncleanup();
  3132. }
  3133. // Helper method to munge an SDP to enable simulcasting (Chrome only)
  3134. function mungeSdpForSimulcasting(sdp) {
  3135. // Let's munge the SDP to add the attributes for enabling simulcasting
  3136. // (based on https://gist.github.com/ggarber/a19b4c33510028b9c657)
  3137. var lines = sdp.split("\r\n");
  3138. var video = false;
  3139. var ssrc = [ -1 ], ssrc_fid = [ -1 ];
  3140. var cname = null, msid = null, mslabel = null, label = null;
  3141. var insertAt = -1;
  3142. for(var i=0; i<lines.length; i++) {
  3143. var mline = lines[i].match(/m=(\w+) */);
  3144. if(mline) {
  3145. var medium = mline[1];
  3146. if(medium === "video") {
  3147. // New video m-line: make sure it's the first one
  3148. if(ssrc[0] < 0) {
  3149. video = true;
  3150. } else {
  3151. // We're done, let's add the new attributes here
  3152. insertAt = i;
  3153. break;
  3154. }
  3155. } else {
  3156. // New non-video m-line: do we have what we were looking for?
  3157. if(ssrc[0] > -1) {
  3158. // We're done, let's add the new attributes here
  3159. insertAt = i;
  3160. break;
  3161. }
  3162. }
  3163. continue;
  3164. }
  3165. if(!video)
  3166. continue;
  3167. var fid = lines[i].match(/a=ssrc-group:FID (\d+) (\d+)/);
  3168. if(fid) {
  3169. ssrc[0] = fid[1];
  3170. ssrc_fid[0] = fid[2];
  3171. lines.splice(i, 1); i--;
  3172. continue;
  3173. }
  3174. if(ssrc[0]) {
  3175. var match = lines[i].match('a=ssrc:' + ssrc[0] + ' cname:(.+)')
  3176. if(match) {
  3177. cname = match[1];
  3178. }
  3179. match = lines[i].match('a=ssrc:' + ssrc[0] + ' msid:(.+)')
  3180. if(match) {
  3181. msid = match[1];
  3182. }
  3183. match = lines[i].match('a=ssrc:' + ssrc[0] + ' mslabel:(.+)')
  3184. if(match) {
  3185. mslabel = match[1];
  3186. }
  3187. match = lines[i].match('a=ssrc:' + ssrc[0] + ' label:(.+)')
  3188. if(match) {
  3189. label = match[1];
  3190. }
  3191. if(lines[i].indexOf('a=ssrc:' + ssrc_fid[0]) === 0) {
  3192. lines.splice(i, 1); i--;
  3193. continue;
  3194. }
  3195. if(lines[i].indexOf('a=ssrc:' + ssrc[0]) === 0) {
  3196. lines.splice(i, 1); i--;
  3197. continue;
  3198. }
  3199. }
  3200. if(lines[i].length == 0) {
  3201. lines.splice(i, 1); i--;
  3202. continue;
  3203. }
  3204. }
  3205. if(ssrc[0] < 0) {
  3206. // Couldn't find a FID attribute, let's just take the first video SSRC we find
  3207. insertAt = -1;
  3208. video = false;
  3209. for(var i=0; i<lines.length; i++) {
  3210. var mline = lines[i].match(/m=(\w+) */);
  3211. if(mline) {
  3212. var medium = mline[1];
  3213. if(medium === "video") {
  3214. // New video m-line: make sure it's the first one
  3215. if(ssrc[0] < 0) {
  3216. video = true;
  3217. } else {
  3218. // We're done, let's add the new attributes here
  3219. insertAt = i;
  3220. break;
  3221. }
  3222. } else {
  3223. // New non-video m-line: do we have what we were looking for?
  3224. if(ssrc[0] > -1) {
  3225. // We're done, let's add the new attributes here
  3226. insertAt = i;
  3227. break;
  3228. }
  3229. }
  3230. continue;
  3231. }
  3232. if(!video)
  3233. continue;
  3234. if(ssrc[0] < 0) {
  3235. var value = lines[i].match(/a=ssrc:(\d+)/);
  3236. if(value) {
  3237. ssrc[0] = value[1];
  3238. lines.splice(i, 1); i--;
  3239. continue;
  3240. }
  3241. } else {
  3242. var match = lines[i].match('a=ssrc:' + ssrc[0] + ' cname:(.+)')
  3243. if(match) {
  3244. cname = match[1];
  3245. }
  3246. match = lines[i].match('a=ssrc:' + ssrc[0] + ' msid:(.+)')
  3247. if(match) {
  3248. msid = match[1];
  3249. }
  3250. match = lines[i].match('a=ssrc:' + ssrc[0] + ' mslabel:(.+)')
  3251. if(match) {
  3252. mslabel = match[1];
  3253. }
  3254. match = lines[i].match('a=ssrc:' + ssrc[0] + ' label:(.+)')
  3255. if(match) {
  3256. label = match[1];
  3257. }
  3258. if(lines[i].indexOf('a=ssrc:' + ssrc_fid[0]) === 0) {
  3259. lines.splice(i, 1); i--;
  3260. continue;
  3261. }
  3262. if(lines[i].indexOf('a=ssrc:' + ssrc[0]) === 0) {
  3263. lines.splice(i, 1); i--;
  3264. continue;
  3265. }
  3266. }
  3267. if(lines[i].length == 0) {
  3268. lines.splice(i, 1); i--;
  3269. continue;
  3270. }
  3271. }
  3272. }
  3273. if(ssrc[0] < 0) {
  3274. // Still nothing, let's just return the SDP we were asked to munge
  3275. Janus.warn("Couldn't find the video SSRC, simulcasting NOT enabled");
  3276. return sdp;
  3277. }
  3278. if(insertAt < 0) {
  3279. // Append at the end
  3280. insertAt = lines.length;
  3281. }
  3282. // Generate a couple of SSRCs (for retransmissions too)
  3283. // Note: should we check if there are conflicts, here?
  3284. ssrc[1] = Math.floor(Math.random()*0xFFFFFFFF);
  3285. ssrc[2] = Math.floor(Math.random()*0xFFFFFFFF);
  3286. ssrc_fid[1] = Math.floor(Math.random()*0xFFFFFFFF);
  3287. ssrc_fid[2] = Math.floor(Math.random()*0xFFFFFFFF);
  3288. // Add attributes to the SDP
  3289. for(var i=0; i<ssrc.length; i++) {
  3290. if(cname) {
  3291. lines.splice(insertAt, 0, 'a=ssrc:' + ssrc[i] + ' cname:' + cname);
  3292. insertAt++;
  3293. }
  3294. if(msid) {
  3295. lines.splice(insertAt, 0, 'a=ssrc:' + ssrc[i] + ' msid:' + msid);
  3296. insertAt++;
  3297. }
  3298. if(mslabel) {
  3299. lines.splice(insertAt, 0, 'a=ssrc:' + ssrc[i] + ' mslabel:' + mslabel);
  3300. insertAt++;
  3301. }
  3302. if(label) {
  3303. lines.splice(insertAt, 0, 'a=ssrc:' + ssrc[i] + ' label:' + label);
  3304. insertAt++;
  3305. }
  3306. // Add the same info for the retransmission SSRC
  3307. if(cname) {
  3308. lines.splice(insertAt, 0, 'a=ssrc:' + ssrc_fid[i] + ' cname:' + cname);
  3309. insertAt++;
  3310. }
  3311. if(msid) {
  3312. lines.splice(insertAt, 0, 'a=ssrc:' + ssrc_fid[i] + ' msid:' + msid);
  3313. insertAt++;
  3314. }
  3315. if(mslabel) {
  3316. lines.splice(insertAt, 0, 'a=ssrc:' + ssrc_fid[i] + ' mslabel:' + mslabel);
  3317. insertAt++;
  3318. }
  3319. if(label) {
  3320. lines.splice(insertAt, 0, 'a=ssrc:' + ssrc_fid[i] + ' label:' + label);
  3321. insertAt++;
  3322. }
  3323. }
  3324. lines.splice(insertAt, 0, 'a=ssrc-group:FID ' + ssrc[2] + ' ' + ssrc_fid[2]);
  3325. lines.splice(insertAt, 0, 'a=ssrc-group:FID ' + ssrc[1] + ' ' + ssrc_fid[1]);
  3326. lines.splice(insertAt, 0, 'a=ssrc-group:FID ' + ssrc[0] + ' ' + ssrc_fid[0]);
  3327. lines.splice(insertAt, 0, 'a=ssrc-group:SIM ' + ssrc[0] + ' ' + ssrc[1] + ' ' + ssrc[2]);
  3328. sdp = lines.join("\r\n");
  3329. if(!sdp.endsWith("\r\n"))
  3330. sdp += "\r\n";
  3331. return sdp;
  3332. }
  3333. // Helper methods to parse a media object
  3334. function isAudioSendEnabled(media) {
  3335. Janus.debug("isAudioSendEnabled:", media);
  3336. if(media === undefined || media === null)
  3337. return true; // Default
  3338. if(media.audio === false)
  3339. return false; // Generic audio has precedence
  3340. if(media.audioSend === undefined || media.audioSend === null)
  3341. return true; // Default
  3342. return (media.audioSend === true);
  3343. }
  3344. function isAudioSendRequired(media) {
  3345. Janus.debug("isAudioSendRequired:", media);
  3346. if(media === undefined || media === null)
  3347. return false; // Default
  3348. if(media.audio === false || media.audioSend === false)
  3349. return false; // If we're not asking to capture audio, it's not required
  3350. if(media.failIfNoAudio === undefined || media.failIfNoAudio === null)
  3351. return false; // Default
  3352. return (media.failIfNoAudio === true);
  3353. }
  3354. function isAudioRecvEnabled(media) {
  3355. Janus.debug("isAudioRecvEnabled:", media);
  3356. if(media === undefined || media === null)
  3357. return true; // Default
  3358. if(media.audio === false)
  3359. return false; // Generic audio has precedence
  3360. if(media.audioRecv === undefined || media.audioRecv === null)
  3361. return true; // Default
  3362. return (media.audioRecv === true);
  3363. }
  3364. function isVideoSendEnabled(media) {
  3365. Janus.debug("isVideoSendEnabled:", media);
  3366. if(media === undefined || media === null)
  3367. return true; // Default
  3368. if(media.video === false)
  3369. return false; // Generic video has precedence
  3370. if(media.videoSend === undefined || media.videoSend === null)
  3371. return true; // Default
  3372. return (media.videoSend === true);
  3373. }
  3374. function isVideoSendRequired(media) {
  3375. Janus.debug("isVideoSendRequired:", media);
  3376. if(media === undefined || media === null)
  3377. return false; // Default
  3378. if(media.video === false || media.videoSend === false)
  3379. return false; // If we're not asking to capture video, it's not required
  3380. if(media.failIfNoVideo === undefined || media.failIfNoVideo === null)
  3381. return false; // Default
  3382. return (media.failIfNoVideo === true);
  3383. }
  3384. function isVideoRecvEnabled(media) {
  3385. Janus.debug("isVideoRecvEnabled:", media);
  3386. if(media === undefined || media === null)
  3387. return true; // Default
  3388. if(media.video === false)
  3389. return false; // Generic video has precedence
  3390. if(media.videoRecv === undefined || media.videoRecv === null)
  3391. return true; // Default
  3392. return (media.videoRecv === true);
  3393. }
  3394. function isScreenSendEnabled(media) {
  3395. Janus.debug("isScreenSendEnabled:", media);
  3396. if (media === undefined || media === null)
  3397. return false;
  3398. if (typeof media.video !== 'object' || typeof media.video.mandatory !== 'object')
  3399. return false;
  3400. var constraints = media.video.mandatory;
  3401. if (constraints.chromeMediaSource)
  3402. return constraints.chromeMediaSource === 'desktop' || constraints.chromeMediaSource === 'screen';
  3403. else if (constraints.mozMediaSource)
  3404. return constraints.mozMediaSource === 'window' || constraints.mozMediaSource === 'screen';
  3405. else if (constraints.mediaSource)
  3406. return constraints.mediaSource === 'window' || constraints.mediaSource === 'screen';
  3407. return false;
  3408. }
  3409. function isDataEnabled(media) {
  3410. Janus.debug("isDataEnabled:", media);
  3411. if(Janus.webRTCAdapter.browserDetails.browser == "edge") {
  3412. Janus.warn("Edge doesn't support data channels yet");
  3413. return false;
  3414. }
  3415. if(media === undefined || media === null)
  3416. return false; // Default
  3417. return (media.data === true);
  3418. }
  3419. function isTrickleEnabled(trickle) {
  3420. Janus.debug("isTrickleEnabled:", trickle);
  3421. if(trickle === undefined || trickle === null)
  3422. return true; // Default is true
  3423. return (trickle === true);
  3424. }
  3425. };