janus.js 124 KB

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