janus.js 125 KB

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