adapter-latest.js 181 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.adapter = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. /*
  3. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  4. *
  5. * Use of this source code is governed by a BSD-style license
  6. * that can be found in the LICENSE file in the root of the source
  7. * tree.
  8. */
  9. /* eslint-env node */
  10. 'use strict';
  11. var _adapter_factory = require('./adapter_factory.js');
  12. var adapter = (0, _adapter_factory.adapterFactory)({ window: window });
  13. module.exports = adapter; // this is the difference from adapter_core.
  14. },{"./adapter_factory.js":2}],2:[function(require,module,exports){
  15. 'use strict';
  16. Object.defineProperty(exports, "__esModule", {
  17. value: true
  18. });
  19. exports.adapterFactory = adapterFactory;
  20. var _utils = require('./utils');
  21. var utils = _interopRequireWildcard(_utils);
  22. var _chrome_shim = require('./chrome/chrome_shim');
  23. var chromeShim = _interopRequireWildcard(_chrome_shim);
  24. var _edge_shim = require('./edge/edge_shim');
  25. var edgeShim = _interopRequireWildcard(_edge_shim);
  26. var _firefox_shim = require('./firefox/firefox_shim');
  27. var firefoxShim = _interopRequireWildcard(_firefox_shim);
  28. var _safari_shim = require('./safari/safari_shim');
  29. var safariShim = _interopRequireWildcard(_safari_shim);
  30. var _common_shim = require('./common_shim');
  31. var commonShim = _interopRequireWildcard(_common_shim);
  32. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  33. // Shimming starts here.
  34. /*
  35. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  36. *
  37. * Use of this source code is governed by a BSD-style license
  38. * that can be found in the LICENSE file in the root of the source
  39. * tree.
  40. */
  41. function adapterFactory() {
  42. var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
  43. window = _ref.window;
  44. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
  45. shimChrome: true,
  46. shimFirefox: true,
  47. shimEdge: true,
  48. shimSafari: true
  49. };
  50. // Utils.
  51. var logging = utils.log;
  52. var browserDetails = utils.detectBrowser(window);
  53. var adapter = {
  54. browserDetails: browserDetails,
  55. commonShim: commonShim,
  56. extractVersion: utils.extractVersion,
  57. disableLog: utils.disableLog,
  58. disableWarnings: utils.disableWarnings
  59. };
  60. // Shim browser if found.
  61. switch (browserDetails.browser) {
  62. case 'chrome':
  63. if (!chromeShim || !chromeShim.shimPeerConnection || !options.shimChrome) {
  64. logging('Chrome shim is not included in this adapter release.');
  65. return adapter;
  66. }
  67. logging('adapter.js shimming chrome.');
  68. // Export to the adapter global object visible in the browser.
  69. adapter.browserShim = chromeShim;
  70. chromeShim.shimGetUserMedia(window);
  71. chromeShim.shimMediaStream(window);
  72. chromeShim.shimPeerConnection(window);
  73. chromeShim.shimOnTrack(window);
  74. chromeShim.shimAddTrackRemoveTrack(window);
  75. chromeShim.shimGetSendersWithDtmf(window);
  76. chromeShim.shimGetStats(window);
  77. chromeShim.shimSenderReceiverGetStats(window);
  78. chromeShim.fixNegotiationNeeded(window);
  79. commonShim.shimRTCIceCandidate(window);
  80. commonShim.shimConnectionState(window);
  81. commonShim.shimMaxMessageSize(window);
  82. commonShim.shimSendThrowTypeError(window);
  83. commonShim.removeAllowExtmapMixed(window);
  84. break;
  85. case 'firefox':
  86. if (!firefoxShim || !firefoxShim.shimPeerConnection || !options.shimFirefox) {
  87. logging('Firefox shim is not included in this adapter release.');
  88. return adapter;
  89. }
  90. logging('adapter.js shimming firefox.');
  91. // Export to the adapter global object visible in the browser.
  92. adapter.browserShim = firefoxShim;
  93. firefoxShim.shimGetUserMedia(window);
  94. firefoxShim.shimPeerConnection(window);
  95. firefoxShim.shimOnTrack(window);
  96. firefoxShim.shimRemoveStream(window);
  97. firefoxShim.shimSenderGetStats(window);
  98. firefoxShim.shimReceiverGetStats(window);
  99. firefoxShim.shimRTCDataChannel(window);
  100. commonShim.shimRTCIceCandidate(window);
  101. commonShim.shimConnectionState(window);
  102. commonShim.shimMaxMessageSize(window);
  103. commonShim.shimSendThrowTypeError(window);
  104. break;
  105. case 'edge':
  106. if (!edgeShim || !edgeShim.shimPeerConnection || !options.shimEdge) {
  107. logging('MS edge shim is not included in this adapter release.');
  108. return adapter;
  109. }
  110. logging('adapter.js shimming edge.');
  111. // Export to the adapter global object visible in the browser.
  112. adapter.browserShim = edgeShim;
  113. edgeShim.shimGetUserMedia(window);
  114. edgeShim.shimGetDisplayMedia(window);
  115. edgeShim.shimPeerConnection(window);
  116. edgeShim.shimReplaceTrack(window);
  117. // the edge shim implements the full RTCIceCandidate object.
  118. commonShim.shimMaxMessageSize(window);
  119. commonShim.shimSendThrowTypeError(window);
  120. break;
  121. case 'safari':
  122. if (!safariShim || !options.shimSafari) {
  123. logging('Safari shim is not included in this adapter release.');
  124. return adapter;
  125. }
  126. logging('adapter.js shimming safari.');
  127. // Export to the adapter global object visible in the browser.
  128. adapter.browserShim = safariShim;
  129. safariShim.shimRTCIceServerUrls(window);
  130. safariShim.shimCreateOfferLegacy(window);
  131. safariShim.shimCallbacksAPI(window);
  132. safariShim.shimLocalStreamsAPI(window);
  133. safariShim.shimRemoteStreamsAPI(window);
  134. safariShim.shimTrackEventTransceiver(window);
  135. safariShim.shimGetUserMedia(window);
  136. commonShim.shimRTCIceCandidate(window);
  137. commonShim.shimMaxMessageSize(window);
  138. commonShim.shimSendThrowTypeError(window);
  139. commonShim.removeAllowExtmapMixed(window);
  140. break;
  141. default:
  142. logging('Unsupported browser!');
  143. break;
  144. }
  145. return adapter;
  146. }
  147. // Browser shims.
  148. },{"./chrome/chrome_shim":3,"./common_shim":6,"./edge/edge_shim":7,"./firefox/firefox_shim":11,"./safari/safari_shim":14,"./utils":15}],3:[function(require,module,exports){
  149. /*
  150. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  151. *
  152. * Use of this source code is governed by a BSD-style license
  153. * that can be found in the LICENSE file in the root of the source
  154. * tree.
  155. */
  156. /* eslint-env node */
  157. 'use strict';
  158. Object.defineProperty(exports, "__esModule", {
  159. value: true
  160. });
  161. exports.shimGetDisplayMedia = exports.shimGetUserMedia = undefined;
  162. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  163. var _getusermedia = require('./getusermedia');
  164. Object.defineProperty(exports, 'shimGetUserMedia', {
  165. enumerable: true,
  166. get: function get() {
  167. return _getusermedia.shimGetUserMedia;
  168. }
  169. });
  170. var _getdisplaymedia = require('./getdisplaymedia');
  171. Object.defineProperty(exports, 'shimGetDisplayMedia', {
  172. enumerable: true,
  173. get: function get() {
  174. return _getdisplaymedia.shimGetDisplayMedia;
  175. }
  176. });
  177. exports.shimMediaStream = shimMediaStream;
  178. exports.shimOnTrack = shimOnTrack;
  179. exports.shimGetSendersWithDtmf = shimGetSendersWithDtmf;
  180. exports.shimGetStats = shimGetStats;
  181. exports.shimSenderReceiverGetStats = shimSenderReceiverGetStats;
  182. exports.shimAddTrackRemoveTrackWithNative = shimAddTrackRemoveTrackWithNative;
  183. exports.shimAddTrackRemoveTrack = shimAddTrackRemoveTrack;
  184. exports.shimPeerConnection = shimPeerConnection;
  185. exports.fixNegotiationNeeded = fixNegotiationNeeded;
  186. var _utils = require('../utils.js');
  187. var utils = _interopRequireWildcard(_utils);
  188. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  189. function shimMediaStream(window) {
  190. window.MediaStream = window.MediaStream || window.webkitMediaStream;
  191. }
  192. function shimOnTrack(window) {
  193. if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection && !('ontrack' in window.RTCPeerConnection.prototype)) {
  194. Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
  195. get: function get() {
  196. return this._ontrack;
  197. },
  198. set: function set(f) {
  199. if (this._ontrack) {
  200. this.removeEventListener('track', this._ontrack);
  201. }
  202. this.addEventListener('track', this._ontrack = f);
  203. },
  204. enumerable: true,
  205. configurable: true
  206. });
  207. var origSetRemoteDescription = window.RTCPeerConnection.prototype.setRemoteDescription;
  208. window.RTCPeerConnection.prototype.setRemoteDescription = function () {
  209. var _this = this;
  210. if (!this._ontrackpoly) {
  211. this._ontrackpoly = function (e) {
  212. // onaddstream does not fire when a track is added to an existing
  213. // stream. But stream.onaddtrack is implemented so we use that.
  214. e.stream.addEventListener('addtrack', function (te) {
  215. var receiver = void 0;
  216. if (window.RTCPeerConnection.prototype.getReceivers) {
  217. receiver = _this.getReceivers().find(function (r) {
  218. return r.track && r.track.id === te.track.id;
  219. });
  220. } else {
  221. receiver = { track: te.track };
  222. }
  223. var event = new Event('track');
  224. event.track = te.track;
  225. event.receiver = receiver;
  226. event.transceiver = { receiver: receiver };
  227. event.streams = [e.stream];
  228. _this.dispatchEvent(event);
  229. });
  230. e.stream.getTracks().forEach(function (track) {
  231. var receiver = void 0;
  232. if (window.RTCPeerConnection.prototype.getReceivers) {
  233. receiver = _this.getReceivers().find(function (r) {
  234. return r.track && r.track.id === track.id;
  235. });
  236. } else {
  237. receiver = { track: track };
  238. }
  239. var event = new Event('track');
  240. event.track = track;
  241. event.receiver = receiver;
  242. event.transceiver = { receiver: receiver };
  243. event.streams = [e.stream];
  244. _this.dispatchEvent(event);
  245. });
  246. };
  247. this.addEventListener('addstream', this._ontrackpoly);
  248. }
  249. return origSetRemoteDescription.apply(this, arguments);
  250. };
  251. } else {
  252. // even if RTCRtpTransceiver is in window, it is only used and
  253. // emitted in unified-plan. Unfortunately this means we need
  254. // to unconditionally wrap the event.
  255. utils.wrapPeerConnectionEvent(window, 'track', function (e) {
  256. if (!e.transceiver) {
  257. Object.defineProperty(e, 'transceiver', { value: { receiver: e.receiver } });
  258. }
  259. return e;
  260. });
  261. }
  262. }
  263. function shimGetSendersWithDtmf(window) {
  264. // Overrides addTrack/removeTrack, depends on shimAddTrackRemoveTrack.
  265. if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection && !('getSenders' in window.RTCPeerConnection.prototype) && 'createDTMFSender' in window.RTCPeerConnection.prototype) {
  266. var shimSenderWithDtmf = function shimSenderWithDtmf(pc, track) {
  267. return {
  268. track: track,
  269. get dtmf() {
  270. if (this._dtmf === undefined) {
  271. if (track.kind === 'audio') {
  272. this._dtmf = pc.createDTMFSender(track);
  273. } else {
  274. this._dtmf = null;
  275. }
  276. }
  277. return this._dtmf;
  278. },
  279. _pc: pc
  280. };
  281. };
  282. // augment addTrack when getSenders is not available.
  283. if (!window.RTCPeerConnection.prototype.getSenders) {
  284. window.RTCPeerConnection.prototype.getSenders = function () {
  285. this._senders = this._senders || [];
  286. return this._senders.slice(); // return a copy of the internal state.
  287. };
  288. var origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  289. window.RTCPeerConnection.prototype.addTrack = function (track, stream) {
  290. var sender = origAddTrack.apply(this, arguments);
  291. if (!sender) {
  292. sender = shimSenderWithDtmf(this, track);
  293. this._senders.push(sender);
  294. }
  295. return sender;
  296. };
  297. var origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;
  298. window.RTCPeerConnection.prototype.removeTrack = function (sender) {
  299. origRemoveTrack.apply(this, arguments);
  300. var idx = this._senders.indexOf(sender);
  301. if (idx !== -1) {
  302. this._senders.splice(idx, 1);
  303. }
  304. };
  305. }
  306. var origAddStream = window.RTCPeerConnection.prototype.addStream;
  307. window.RTCPeerConnection.prototype.addStream = function (stream) {
  308. var _this2 = this;
  309. this._senders = this._senders || [];
  310. origAddStream.apply(this, [stream]);
  311. stream.getTracks().forEach(function (track) {
  312. _this2._senders.push(shimSenderWithDtmf(_this2, track));
  313. });
  314. };
  315. var origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
  316. window.RTCPeerConnection.prototype.removeStream = function (stream) {
  317. var _this3 = this;
  318. this._senders = this._senders || [];
  319. origRemoveStream.apply(this, [stream]);
  320. stream.getTracks().forEach(function (track) {
  321. var sender = _this3._senders.find(function (s) {
  322. return s.track === track;
  323. });
  324. if (sender) {
  325. // remove sender
  326. _this3._senders.splice(_this3._senders.indexOf(sender), 1);
  327. }
  328. });
  329. };
  330. } else if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection && 'getSenders' in window.RTCPeerConnection.prototype && 'createDTMFSender' in window.RTCPeerConnection.prototype && window.RTCRtpSender && !('dtmf' in window.RTCRtpSender.prototype)) {
  331. var origGetSenders = window.RTCPeerConnection.prototype.getSenders;
  332. window.RTCPeerConnection.prototype.getSenders = function () {
  333. var _this4 = this;
  334. var senders = origGetSenders.apply(this, []);
  335. senders.forEach(function (sender) {
  336. return sender._pc = _this4;
  337. });
  338. return senders;
  339. };
  340. Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', {
  341. get: function get() {
  342. if (this._dtmf === undefined) {
  343. if (this.track.kind === 'audio') {
  344. this._dtmf = this._pc.createDTMFSender(this.track);
  345. } else {
  346. this._dtmf = null;
  347. }
  348. }
  349. return this._dtmf;
  350. }
  351. });
  352. }
  353. }
  354. function shimGetStats(window) {
  355. if (!window.RTCPeerConnection) {
  356. return;
  357. }
  358. var origGetStats = window.RTCPeerConnection.prototype.getStats;
  359. window.RTCPeerConnection.prototype.getStats = function (selector, successCallback, errorCallback) {
  360. var _this5 = this;
  361. var args = arguments;
  362. // If selector is a function then we are in the old style stats so just
  363. // pass back the original getStats format to avoid breaking old users.
  364. if (arguments.length > 0 && typeof selector === 'function') {
  365. return origGetStats.apply(this, arguments);
  366. }
  367. // When spec-style getStats is supported, return those when called with
  368. // either no arguments or the selector argument is null.
  369. if (origGetStats.length === 0 && (arguments.length === 0 || typeof arguments[0] !== 'function')) {
  370. return origGetStats.apply(this, []);
  371. }
  372. var fixChromeStats_ = function fixChromeStats_(response) {
  373. var standardReport = {};
  374. var reports = response.result();
  375. reports.forEach(function (report) {
  376. var standardStats = {
  377. id: report.id,
  378. timestamp: report.timestamp,
  379. type: {
  380. localcandidate: 'local-candidate',
  381. remotecandidate: 'remote-candidate'
  382. }[report.type] || report.type
  383. };
  384. report.names().forEach(function (name) {
  385. standardStats[name] = report.stat(name);
  386. });
  387. standardReport[standardStats.id] = standardStats;
  388. });
  389. return standardReport;
  390. };
  391. // shim getStats with maplike support
  392. var makeMapStats = function makeMapStats(stats) {
  393. return new Map(Object.keys(stats).map(function (key) {
  394. return [key, stats[key]];
  395. }));
  396. };
  397. if (arguments.length >= 2) {
  398. var successCallbackWrapper_ = function successCallbackWrapper_(response) {
  399. args[1](makeMapStats(fixChromeStats_(response)));
  400. };
  401. return origGetStats.apply(this, [successCallbackWrapper_, arguments[0]]);
  402. }
  403. // promise-support
  404. return new Promise(function (resolve, reject) {
  405. origGetStats.apply(_this5, [function (response) {
  406. resolve(makeMapStats(fixChromeStats_(response)));
  407. }, reject]);
  408. }).then(successCallback, errorCallback);
  409. };
  410. }
  411. function shimSenderReceiverGetStats(window) {
  412. if (!((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection && window.RTCRtpSender && window.RTCRtpReceiver)) {
  413. return;
  414. }
  415. // shim sender stats.
  416. if (!('getStats' in window.RTCRtpSender.prototype)) {
  417. var origGetSenders = window.RTCPeerConnection.prototype.getSenders;
  418. if (origGetSenders) {
  419. window.RTCPeerConnection.prototype.getSenders = function () {
  420. var _this6 = this;
  421. var senders = origGetSenders.apply(this, []);
  422. senders.forEach(function (sender) {
  423. return sender._pc = _this6;
  424. });
  425. return senders;
  426. };
  427. }
  428. var origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  429. if (origAddTrack) {
  430. window.RTCPeerConnection.prototype.addTrack = function () {
  431. var sender = origAddTrack.apply(this, arguments);
  432. sender._pc = this;
  433. return sender;
  434. };
  435. }
  436. window.RTCRtpSender.prototype.getStats = function () {
  437. var sender = this;
  438. return this._pc.getStats().then(function (result) {
  439. return (
  440. /* Note: this will include stats of all senders that
  441. * send a track with the same id as sender.track as
  442. * it is not possible to identify the RTCRtpSender.
  443. */
  444. utils.filterStats(result, sender.track, true)
  445. );
  446. });
  447. };
  448. }
  449. // shim receiver stats.
  450. if (!('getStats' in window.RTCRtpReceiver.prototype)) {
  451. var origGetReceivers = window.RTCPeerConnection.prototype.getReceivers;
  452. if (origGetReceivers) {
  453. window.RTCPeerConnection.prototype.getReceivers = function () {
  454. var _this7 = this;
  455. var receivers = origGetReceivers.apply(this, []);
  456. receivers.forEach(function (receiver) {
  457. return receiver._pc = _this7;
  458. });
  459. return receivers;
  460. };
  461. }
  462. utils.wrapPeerConnectionEvent(window, 'track', function (e) {
  463. e.receiver._pc = e.srcElement;
  464. return e;
  465. });
  466. window.RTCRtpReceiver.prototype.getStats = function () {
  467. var receiver = this;
  468. return this._pc.getStats().then(function (result) {
  469. return utils.filterStats(result, receiver.track, false);
  470. });
  471. };
  472. }
  473. if (!('getStats' in window.RTCRtpSender.prototype && 'getStats' in window.RTCRtpReceiver.prototype)) {
  474. return;
  475. }
  476. // shim RTCPeerConnection.getStats(track).
  477. var origGetStats = window.RTCPeerConnection.prototype.getStats;
  478. window.RTCPeerConnection.prototype.getStats = function () {
  479. if (arguments.length > 0 && arguments[0] instanceof window.MediaStreamTrack) {
  480. var track = arguments[0];
  481. var sender = void 0;
  482. var receiver = void 0;
  483. var err = void 0;
  484. this.getSenders().forEach(function (s) {
  485. if (s.track === track) {
  486. if (sender) {
  487. err = true;
  488. } else {
  489. sender = s;
  490. }
  491. }
  492. });
  493. this.getReceivers().forEach(function (r) {
  494. if (r.track === track) {
  495. if (receiver) {
  496. err = true;
  497. } else {
  498. receiver = r;
  499. }
  500. }
  501. return r.track === track;
  502. });
  503. if (err || sender && receiver) {
  504. return Promise.reject(new DOMException('There are more than one sender or receiver for the track.', 'InvalidAccessError'));
  505. } else if (sender) {
  506. return sender.getStats();
  507. } else if (receiver) {
  508. return receiver.getStats();
  509. }
  510. return Promise.reject(new DOMException('There is no sender or receiver for the track.', 'InvalidAccessError'));
  511. }
  512. return origGetStats.apply(this, arguments);
  513. };
  514. }
  515. function shimAddTrackRemoveTrackWithNative(window) {
  516. // shim addTrack/removeTrack with native variants in order to make
  517. // the interactions with legacy getLocalStreams behave as in other browsers.
  518. // Keeps a mapping stream.id => [stream, rtpsenders...]
  519. window.RTCPeerConnection.prototype.getLocalStreams = function () {
  520. var _this8 = this;
  521. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  522. return Object.keys(this._shimmedLocalStreams).map(function (streamId) {
  523. return _this8._shimmedLocalStreams[streamId][0];
  524. });
  525. };
  526. var origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  527. window.RTCPeerConnection.prototype.addTrack = function (track, stream) {
  528. if (!stream) {
  529. return origAddTrack.apply(this, arguments);
  530. }
  531. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  532. var sender = origAddTrack.apply(this, arguments);
  533. if (!this._shimmedLocalStreams[stream.id]) {
  534. this._shimmedLocalStreams[stream.id] = [stream, sender];
  535. } else if (this._shimmedLocalStreams[stream.id].indexOf(sender) === -1) {
  536. this._shimmedLocalStreams[stream.id].push(sender);
  537. }
  538. return sender;
  539. };
  540. var origAddStream = window.RTCPeerConnection.prototype.addStream;
  541. window.RTCPeerConnection.prototype.addStream = function (stream) {
  542. var _this9 = this;
  543. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  544. stream.getTracks().forEach(function (track) {
  545. var alreadyExists = _this9.getSenders().find(function (s) {
  546. return s.track === track;
  547. });
  548. if (alreadyExists) {
  549. throw new DOMException('Track already exists.', 'InvalidAccessError');
  550. }
  551. });
  552. var existingSenders = this.getSenders();
  553. origAddStream.apply(this, arguments);
  554. var newSenders = this.getSenders().filter(function (newSender) {
  555. return existingSenders.indexOf(newSender) === -1;
  556. });
  557. this._shimmedLocalStreams[stream.id] = [stream].concat(newSenders);
  558. };
  559. var origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
  560. window.RTCPeerConnection.prototype.removeStream = function (stream) {
  561. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  562. delete this._shimmedLocalStreams[stream.id];
  563. return origRemoveStream.apply(this, arguments);
  564. };
  565. var origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;
  566. window.RTCPeerConnection.prototype.removeTrack = function (sender) {
  567. var _this10 = this;
  568. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  569. if (sender) {
  570. Object.keys(this._shimmedLocalStreams).forEach(function (streamId) {
  571. var idx = _this10._shimmedLocalStreams[streamId].indexOf(sender);
  572. if (idx !== -1) {
  573. _this10._shimmedLocalStreams[streamId].splice(idx, 1);
  574. }
  575. if (_this10._shimmedLocalStreams[streamId].length === 1) {
  576. delete _this10._shimmedLocalStreams[streamId];
  577. }
  578. });
  579. }
  580. return origRemoveTrack.apply(this, arguments);
  581. };
  582. }
  583. function shimAddTrackRemoveTrack(window) {
  584. if (!window.RTCPeerConnection) {
  585. return;
  586. }
  587. var browserDetails = utils.detectBrowser(window);
  588. // shim addTrack and removeTrack.
  589. if (window.RTCPeerConnection.prototype.addTrack && browserDetails.version >= 65) {
  590. return shimAddTrackRemoveTrackWithNative(window);
  591. }
  592. // also shim pc.getLocalStreams when addTrack is shimmed
  593. // to return the original streams.
  594. var origGetLocalStreams = window.RTCPeerConnection.prototype.getLocalStreams;
  595. window.RTCPeerConnection.prototype.getLocalStreams = function () {
  596. var _this11 = this;
  597. var nativeStreams = origGetLocalStreams.apply(this);
  598. this._reverseStreams = this._reverseStreams || {};
  599. return nativeStreams.map(function (stream) {
  600. return _this11._reverseStreams[stream.id];
  601. });
  602. };
  603. var origAddStream = window.RTCPeerConnection.prototype.addStream;
  604. window.RTCPeerConnection.prototype.addStream = function (stream) {
  605. var _this12 = this;
  606. this._streams = this._streams || {};
  607. this._reverseStreams = this._reverseStreams || {};
  608. stream.getTracks().forEach(function (track) {
  609. var alreadyExists = _this12.getSenders().find(function (s) {
  610. return s.track === track;
  611. });
  612. if (alreadyExists) {
  613. throw new DOMException('Track already exists.', 'InvalidAccessError');
  614. }
  615. });
  616. // Add identity mapping for consistency with addTrack.
  617. // Unless this is being used with a stream from addTrack.
  618. if (!this._reverseStreams[stream.id]) {
  619. var newStream = new window.MediaStream(stream.getTracks());
  620. this._streams[stream.id] = newStream;
  621. this._reverseStreams[newStream.id] = stream;
  622. stream = newStream;
  623. }
  624. origAddStream.apply(this, [stream]);
  625. };
  626. var origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
  627. window.RTCPeerConnection.prototype.removeStream = function (stream) {
  628. this._streams = this._streams || {};
  629. this._reverseStreams = this._reverseStreams || {};
  630. origRemoveStream.apply(this, [this._streams[stream.id] || stream]);
  631. delete this._reverseStreams[this._streams[stream.id] ? this._streams[stream.id].id : stream.id];
  632. delete this._streams[stream.id];
  633. };
  634. window.RTCPeerConnection.prototype.addTrack = function (track, stream) {
  635. var _this13 = this;
  636. if (this.signalingState === 'closed') {
  637. throw new DOMException('The RTCPeerConnection\'s signalingState is \'closed\'.', 'InvalidStateError');
  638. }
  639. var streams = [].slice.call(arguments, 1);
  640. if (streams.length !== 1 || !streams[0].getTracks().find(function (t) {
  641. return t === track;
  642. })) {
  643. // this is not fully correct but all we can manage without
  644. // [[associated MediaStreams]] internal slot.
  645. throw new DOMException('The adapter.js addTrack polyfill only supports a single ' + ' stream which is associated with the specified track.', 'NotSupportedError');
  646. }
  647. var alreadyExists = this.getSenders().find(function (s) {
  648. return s.track === track;
  649. });
  650. if (alreadyExists) {
  651. throw new DOMException('Track already exists.', 'InvalidAccessError');
  652. }
  653. this._streams = this._streams || {};
  654. this._reverseStreams = this._reverseStreams || {};
  655. var oldStream = this._streams[stream.id];
  656. if (oldStream) {
  657. // this is using odd Chrome behaviour, use with caution:
  658. // https://bugs.chromium.org/p/webrtc/issues/detail?id=7815
  659. // Note: we rely on the high-level addTrack/dtmf shim to
  660. // create the sender with a dtmf sender.
  661. oldStream.addTrack(track);
  662. // Trigger ONN async.
  663. Promise.resolve().then(function () {
  664. _this13.dispatchEvent(new Event('negotiationneeded'));
  665. });
  666. } else {
  667. var newStream = new window.MediaStream([track]);
  668. this._streams[stream.id] = newStream;
  669. this._reverseStreams[newStream.id] = stream;
  670. this.addStream(newStream);
  671. }
  672. return this.getSenders().find(function (s) {
  673. return s.track === track;
  674. });
  675. };
  676. // replace the internal stream id with the external one and
  677. // vice versa.
  678. function replaceInternalStreamId(pc, description) {
  679. var sdp = description.sdp;
  680. Object.keys(pc._reverseStreams || []).forEach(function (internalId) {
  681. var externalStream = pc._reverseStreams[internalId];
  682. var internalStream = pc._streams[externalStream.id];
  683. sdp = sdp.replace(new RegExp(internalStream.id, 'g'), externalStream.id);
  684. });
  685. return new RTCSessionDescription({
  686. type: description.type,
  687. sdp: sdp
  688. });
  689. }
  690. function replaceExternalStreamId(pc, description) {
  691. var sdp = description.sdp;
  692. Object.keys(pc._reverseStreams || []).forEach(function (internalId) {
  693. var externalStream = pc._reverseStreams[internalId];
  694. var internalStream = pc._streams[externalStream.id];
  695. sdp = sdp.replace(new RegExp(externalStream.id, 'g'), internalStream.id);
  696. });
  697. return new RTCSessionDescription({
  698. type: description.type,
  699. sdp: sdp
  700. });
  701. }
  702. ['createOffer', 'createAnswer'].forEach(function (method) {
  703. var nativeMethod = window.RTCPeerConnection.prototype[method];
  704. window.RTCPeerConnection.prototype[method] = function () {
  705. var _this14 = this;
  706. var args = arguments;
  707. var isLegacyCall = arguments.length && typeof arguments[0] === 'function';
  708. if (isLegacyCall) {
  709. return nativeMethod.apply(this, [function (description) {
  710. var desc = replaceInternalStreamId(_this14, description);
  711. args[0].apply(null, [desc]);
  712. }, function (err) {
  713. if (args[1]) {
  714. args[1].apply(null, err);
  715. }
  716. }, arguments[2]]);
  717. }
  718. return nativeMethod.apply(this, arguments).then(function (description) {
  719. return replaceInternalStreamId(_this14, description);
  720. });
  721. };
  722. });
  723. var origSetLocalDescription = window.RTCPeerConnection.prototype.setLocalDescription;
  724. window.RTCPeerConnection.prototype.setLocalDescription = function () {
  725. if (!arguments.length || !arguments[0].type) {
  726. return origSetLocalDescription.apply(this, arguments);
  727. }
  728. arguments[0] = replaceExternalStreamId(this, arguments[0]);
  729. return origSetLocalDescription.apply(this, arguments);
  730. };
  731. // TODO: mangle getStats: https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamstats-streamidentifier
  732. var origLocalDescription = Object.getOwnPropertyDescriptor(window.RTCPeerConnection.prototype, 'localDescription');
  733. Object.defineProperty(window.RTCPeerConnection.prototype, 'localDescription', {
  734. get: function get() {
  735. var description = origLocalDescription.get.apply(this);
  736. if (description.type === '') {
  737. return description;
  738. }
  739. return replaceInternalStreamId(this, description);
  740. }
  741. });
  742. window.RTCPeerConnection.prototype.removeTrack = function (sender) {
  743. var _this15 = this;
  744. if (this.signalingState === 'closed') {
  745. throw new DOMException('The RTCPeerConnection\'s signalingState is \'closed\'.', 'InvalidStateError');
  746. }
  747. // We can not yet check for sender instanceof RTCRtpSender
  748. // since we shim RTPSender. So we check if sender._pc is set.
  749. if (!sender._pc) {
  750. throw new DOMException('Argument 1 of RTCPeerConnection.removeTrack ' + 'does not implement interface RTCRtpSender.', 'TypeError');
  751. }
  752. var isLocal = sender._pc === this;
  753. if (!isLocal) {
  754. throw new DOMException('Sender was not created by this connection.', 'InvalidAccessError');
  755. }
  756. // Search for the native stream the senders track belongs to.
  757. this._streams = this._streams || {};
  758. var stream = void 0;
  759. Object.keys(this._streams).forEach(function (streamid) {
  760. var hasTrack = _this15._streams[streamid].getTracks().find(function (track) {
  761. return sender.track === track;
  762. });
  763. if (hasTrack) {
  764. stream = _this15._streams[streamid];
  765. }
  766. });
  767. if (stream) {
  768. if (stream.getTracks().length === 1) {
  769. // if this is the last track of the stream, remove the stream. This
  770. // takes care of any shimmed _senders.
  771. this.removeStream(this._reverseStreams[stream.id]);
  772. } else {
  773. // relying on the same odd chrome behaviour as above.
  774. stream.removeTrack(sender.track);
  775. }
  776. this.dispatchEvent(new Event('negotiationneeded'));
  777. }
  778. };
  779. }
  780. function shimPeerConnection(window) {
  781. if (!window.RTCPeerConnection && window.webkitRTCPeerConnection) {
  782. // very basic support for old versions.
  783. window.RTCPeerConnection = window.webkitRTCPeerConnection;
  784. }
  785. if (!window.RTCPeerConnection) {
  786. return;
  787. }
  788. // shim implicit creation of RTCSessionDescription/RTCIceCandidate
  789. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'].forEach(function (method) {
  790. var nativeMethod = window.RTCPeerConnection.prototype[method];
  791. window.RTCPeerConnection.prototype[method] = function () {
  792. arguments[0] = new (method === 'addIceCandidate' ? window.RTCIceCandidate : window.RTCSessionDescription)(arguments[0]);
  793. return nativeMethod.apply(this, arguments);
  794. };
  795. });
  796. // support for addIceCandidate(null or undefined)
  797. var nativeAddIceCandidate = window.RTCPeerConnection.prototype.addIceCandidate;
  798. window.RTCPeerConnection.prototype.addIceCandidate = function () {
  799. if (!arguments[0]) {
  800. if (arguments[1]) {
  801. arguments[1].apply(null);
  802. }
  803. return Promise.resolve();
  804. }
  805. return nativeAddIceCandidate.apply(this, arguments);
  806. };
  807. }
  808. function fixNegotiationNeeded(window) {
  809. utils.wrapPeerConnectionEvent(window, 'negotiationneeded', function (e) {
  810. var pc = e.target;
  811. if (pc.signalingState !== 'stable') {
  812. return;
  813. }
  814. return e;
  815. });
  816. }
  817. },{"../utils.js":15,"./getdisplaymedia":4,"./getusermedia":5}],4:[function(require,module,exports){
  818. /*
  819. * Copyright (c) 2018 The adapter.js project authors. All Rights Reserved.
  820. *
  821. * Use of this source code is governed by a BSD-style license
  822. * that can be found in the LICENSE file in the root of the source
  823. * tree.
  824. */
  825. /* eslint-env node */
  826. 'use strict';
  827. Object.defineProperty(exports, "__esModule", {
  828. value: true
  829. });
  830. exports.shimGetDisplayMedia = shimGetDisplayMedia;
  831. function shimGetDisplayMedia(window, getSourceId) {
  832. if (window.navigator.mediaDevices && 'getDisplayMedia' in window.navigator.mediaDevices) {
  833. return;
  834. }
  835. if (!window.navigator.mediaDevices) {
  836. return;
  837. }
  838. // getSourceId is a function that returns a promise resolving with
  839. // the sourceId of the screen/window/tab to be shared.
  840. if (typeof getSourceId !== 'function') {
  841. console.error('shimGetDisplayMedia: getSourceId argument is not ' + 'a function');
  842. return;
  843. }
  844. window.navigator.mediaDevices.getDisplayMedia = function (constraints) {
  845. return getSourceId(constraints).then(function (sourceId) {
  846. var widthSpecified = constraints.video && constraints.video.width;
  847. var heightSpecified = constraints.video && constraints.video.height;
  848. var frameRateSpecified = constraints.video && constraints.video.frameRate;
  849. constraints.video = {
  850. mandatory: {
  851. chromeMediaSource: 'desktop',
  852. chromeMediaSourceId: sourceId,
  853. maxFrameRate: frameRateSpecified || 3
  854. }
  855. };
  856. if (widthSpecified) {
  857. constraints.video.mandatory.maxWidth = widthSpecified;
  858. }
  859. if (heightSpecified) {
  860. constraints.video.mandatory.maxHeight = heightSpecified;
  861. }
  862. return window.navigator.mediaDevices.getUserMedia(constraints);
  863. });
  864. };
  865. }
  866. },{}],5:[function(require,module,exports){
  867. /*
  868. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  869. *
  870. * Use of this source code is governed by a BSD-style license
  871. * that can be found in the LICENSE file in the root of the source
  872. * tree.
  873. */
  874. /* eslint-env node */
  875. 'use strict';
  876. Object.defineProperty(exports, "__esModule", {
  877. value: true
  878. });
  879. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  880. exports.shimGetUserMedia = shimGetUserMedia;
  881. var _utils = require('../utils.js');
  882. var utils = _interopRequireWildcard(_utils);
  883. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  884. var logging = utils.log;
  885. function shimGetUserMedia(window) {
  886. var navigator = window && window.navigator;
  887. if (!navigator.mediaDevices) {
  888. return;
  889. }
  890. var browserDetails = utils.detectBrowser(window);
  891. var constraintsToChrome_ = function constraintsToChrome_(c) {
  892. if ((typeof c === 'undefined' ? 'undefined' : _typeof(c)) !== 'object' || c.mandatory || c.optional) {
  893. return c;
  894. }
  895. var cc = {};
  896. Object.keys(c).forEach(function (key) {
  897. if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
  898. return;
  899. }
  900. var r = _typeof(c[key]) === 'object' ? c[key] : { ideal: c[key] };
  901. if (r.exact !== undefined && typeof r.exact === 'number') {
  902. r.min = r.max = r.exact;
  903. }
  904. var oldname_ = function oldname_(prefix, name) {
  905. if (prefix) {
  906. return prefix + name.charAt(0).toUpperCase() + name.slice(1);
  907. }
  908. return name === 'deviceId' ? 'sourceId' : name;
  909. };
  910. if (r.ideal !== undefined) {
  911. cc.optional = cc.optional || [];
  912. var oc = {};
  913. if (typeof r.ideal === 'number') {
  914. oc[oldname_('min', key)] = r.ideal;
  915. cc.optional.push(oc);
  916. oc = {};
  917. oc[oldname_('max', key)] = r.ideal;
  918. cc.optional.push(oc);
  919. } else {
  920. oc[oldname_('', key)] = r.ideal;
  921. cc.optional.push(oc);
  922. }
  923. }
  924. if (r.exact !== undefined && typeof r.exact !== 'number') {
  925. cc.mandatory = cc.mandatory || {};
  926. cc.mandatory[oldname_('', key)] = r.exact;
  927. } else {
  928. ['min', 'max'].forEach(function (mix) {
  929. if (r[mix] !== undefined) {
  930. cc.mandatory = cc.mandatory || {};
  931. cc.mandatory[oldname_(mix, key)] = r[mix];
  932. }
  933. });
  934. }
  935. });
  936. if (c.advanced) {
  937. cc.optional = (cc.optional || []).concat(c.advanced);
  938. }
  939. return cc;
  940. };
  941. var shimConstraints_ = function shimConstraints_(constraints, func) {
  942. if (browserDetails.version >= 61) {
  943. return func(constraints);
  944. }
  945. constraints = JSON.parse(JSON.stringify(constraints));
  946. if (constraints && _typeof(constraints.audio) === 'object') {
  947. var remap = function remap(obj, a, b) {
  948. if (a in obj && !(b in obj)) {
  949. obj[b] = obj[a];
  950. delete obj[a];
  951. }
  952. };
  953. constraints = JSON.parse(JSON.stringify(constraints));
  954. remap(constraints.audio, 'autoGainControl', 'googAutoGainControl');
  955. remap(constraints.audio, 'noiseSuppression', 'googNoiseSuppression');
  956. constraints.audio = constraintsToChrome_(constraints.audio);
  957. }
  958. if (constraints && _typeof(constraints.video) === 'object') {
  959. // Shim facingMode for mobile & surface pro.
  960. var face = constraints.video.facingMode;
  961. face = face && ((typeof face === 'undefined' ? 'undefined' : _typeof(face)) === 'object' ? face : { ideal: face });
  962. var getSupportedFacingModeLies = browserDetails.version < 66;
  963. if (face && (face.exact === 'user' || face.exact === 'environment' || face.ideal === 'user' || face.ideal === 'environment') && !(navigator.mediaDevices.getSupportedConstraints && navigator.mediaDevices.getSupportedConstraints().facingMode && !getSupportedFacingModeLies)) {
  964. delete constraints.video.facingMode;
  965. var matches = void 0;
  966. if (face.exact === 'environment' || face.ideal === 'environment') {
  967. matches = ['back', 'rear'];
  968. } else if (face.exact === 'user' || face.ideal === 'user') {
  969. matches = ['front'];
  970. }
  971. if (matches) {
  972. // Look for matches in label, or use last cam for back (typical).
  973. return navigator.mediaDevices.enumerateDevices().then(function (devices) {
  974. devices = devices.filter(function (d) {
  975. return d.kind === 'videoinput';
  976. });
  977. var dev = devices.find(function (d) {
  978. return matches.some(function (match) {
  979. return d.label.toLowerCase().includes(match);
  980. });
  981. });
  982. if (!dev && devices.length && matches.includes('back')) {
  983. dev = devices[devices.length - 1]; // more likely the back cam
  984. }
  985. if (dev) {
  986. constraints.video.deviceId = face.exact ? { exact: dev.deviceId } : { ideal: dev.deviceId };
  987. }
  988. constraints.video = constraintsToChrome_(constraints.video);
  989. logging('chrome: ' + JSON.stringify(constraints));
  990. return func(constraints);
  991. });
  992. }
  993. }
  994. constraints.video = constraintsToChrome_(constraints.video);
  995. }
  996. logging('chrome: ' + JSON.stringify(constraints));
  997. return func(constraints);
  998. };
  999. var shimError_ = function shimError_(e) {
  1000. if (browserDetails.version >= 64) {
  1001. return e;
  1002. }
  1003. return {
  1004. name: {
  1005. PermissionDeniedError: 'NotAllowedError',
  1006. PermissionDismissedError: 'NotAllowedError',
  1007. InvalidStateError: 'NotAllowedError',
  1008. DevicesNotFoundError: 'NotFoundError',
  1009. ConstraintNotSatisfiedError: 'OverconstrainedError',
  1010. TrackStartError: 'NotReadableError',
  1011. MediaDeviceFailedDueToShutdown: 'NotAllowedError',
  1012. MediaDeviceKillSwitchOn: 'NotAllowedError',
  1013. TabCaptureError: 'AbortError',
  1014. ScreenCaptureError: 'AbortError',
  1015. DeviceCaptureError: 'AbortError'
  1016. }[e.name] || e.name,
  1017. message: e.message,
  1018. constraint: e.constraint || e.constraintName,
  1019. toString: function toString() {
  1020. return this.name + (this.message && ': ') + this.message;
  1021. }
  1022. };
  1023. };
  1024. var getUserMedia_ = function getUserMedia_(constraints, onSuccess, onError) {
  1025. shimConstraints_(constraints, function (c) {
  1026. navigator.webkitGetUserMedia(c, onSuccess, function (e) {
  1027. if (onError) {
  1028. onError(shimError_(e));
  1029. }
  1030. });
  1031. });
  1032. };
  1033. navigator.getUserMedia = getUserMedia_.bind(navigator);
  1034. // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia
  1035. // function which returns a Promise, it does not accept spec-style
  1036. // constraints.
  1037. if (navigator.mediaDevices.getUserMedia) {
  1038. var origGetUserMedia = navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);
  1039. navigator.mediaDevices.getUserMedia = function (cs) {
  1040. return shimConstraints_(cs, function (c) {
  1041. return origGetUserMedia(c).then(function (stream) {
  1042. if (c.audio && !stream.getAudioTracks().length || c.video && !stream.getVideoTracks().length) {
  1043. stream.getTracks().forEach(function (track) {
  1044. track.stop();
  1045. });
  1046. throw new DOMException('', 'NotFoundError');
  1047. }
  1048. return stream;
  1049. }, function (e) {
  1050. return Promise.reject(shimError_(e));
  1051. });
  1052. });
  1053. };
  1054. }
  1055. }
  1056. },{"../utils.js":15}],6:[function(require,module,exports){
  1057. /*
  1058. * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
  1059. *
  1060. * Use of this source code is governed by a BSD-style license
  1061. * that can be found in the LICENSE file in the root of the source
  1062. * tree.
  1063. */
  1064. /* eslint-env node */
  1065. 'use strict';
  1066. Object.defineProperty(exports, "__esModule", {
  1067. value: true
  1068. });
  1069. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  1070. exports.shimRTCIceCandidate = shimRTCIceCandidate;
  1071. exports.shimMaxMessageSize = shimMaxMessageSize;
  1072. exports.shimSendThrowTypeError = shimSendThrowTypeError;
  1073. exports.shimConnectionState = shimConnectionState;
  1074. exports.removeAllowExtmapMixed = removeAllowExtmapMixed;
  1075. var _sdp = require('sdp');
  1076. var _sdp2 = _interopRequireDefault(_sdp);
  1077. var _utils = require('./utils');
  1078. var utils = _interopRequireWildcard(_utils);
  1079. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  1080. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1081. function shimRTCIceCandidate(window) {
  1082. // foundation is arbitrarily chosen as an indicator for full support for
  1083. // https://w3c.github.io/webrtc-pc/#rtcicecandidate-interface
  1084. if (!window.RTCIceCandidate || window.RTCIceCandidate && 'foundation' in window.RTCIceCandidate.prototype) {
  1085. return;
  1086. }
  1087. var NativeRTCIceCandidate = window.RTCIceCandidate;
  1088. window.RTCIceCandidate = function (args) {
  1089. // Remove the a= which shouldn't be part of the candidate string.
  1090. if ((typeof args === 'undefined' ? 'undefined' : _typeof(args)) === 'object' && args.candidate && args.candidate.indexOf('a=') === 0) {
  1091. args = JSON.parse(JSON.stringify(args));
  1092. args.candidate = args.candidate.substr(2);
  1093. }
  1094. if (args.candidate && args.candidate.length) {
  1095. // Augment the native candidate with the parsed fields.
  1096. var nativeCandidate = new NativeRTCIceCandidate(args);
  1097. var parsedCandidate = _sdp2.default.parseCandidate(args.candidate);
  1098. var augmentedCandidate = Object.assign(nativeCandidate, parsedCandidate);
  1099. // Add a serializer that does not serialize the extra attributes.
  1100. augmentedCandidate.toJSON = function () {
  1101. return {
  1102. candidate: augmentedCandidate.candidate,
  1103. sdpMid: augmentedCandidate.sdpMid,
  1104. sdpMLineIndex: augmentedCandidate.sdpMLineIndex,
  1105. usernameFragment: augmentedCandidate.usernameFragment
  1106. };
  1107. };
  1108. return augmentedCandidate;
  1109. }
  1110. return new NativeRTCIceCandidate(args);
  1111. };
  1112. window.RTCIceCandidate.prototype = NativeRTCIceCandidate.prototype;
  1113. // Hook up the augmented candidate in onicecandidate and
  1114. // addEventListener('icecandidate', ...)
  1115. utils.wrapPeerConnectionEvent(window, 'icecandidate', function (e) {
  1116. if (e.candidate) {
  1117. Object.defineProperty(e, 'candidate', {
  1118. value: new window.RTCIceCandidate(e.candidate),
  1119. writable: 'false'
  1120. });
  1121. }
  1122. return e;
  1123. });
  1124. }
  1125. function shimMaxMessageSize(window) {
  1126. if (window.RTCSctpTransport || !window.RTCPeerConnection) {
  1127. return;
  1128. }
  1129. var browserDetails = utils.detectBrowser(window);
  1130. if (!('sctp' in window.RTCPeerConnection.prototype)) {
  1131. Object.defineProperty(window.RTCPeerConnection.prototype, 'sctp', {
  1132. get: function get() {
  1133. return typeof this._sctp === 'undefined' ? null : this._sctp;
  1134. }
  1135. });
  1136. }
  1137. var sctpInDescription = function sctpInDescription(description) {
  1138. if (!description || !description.sdp) {
  1139. return false;
  1140. }
  1141. var sections = _sdp2.default.splitSections(description.sdp);
  1142. sections.shift();
  1143. return sections.some(function (mediaSection) {
  1144. var mLine = _sdp2.default.parseMLine(mediaSection);
  1145. return mLine && mLine.kind === 'application' && mLine.protocol.indexOf('SCTP') !== -1;
  1146. });
  1147. };
  1148. var getRemoteFirefoxVersion = function getRemoteFirefoxVersion(description) {
  1149. // TODO: Is there a better solution for detecting Firefox?
  1150. var match = description.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);
  1151. if (match === null || match.length < 2) {
  1152. return -1;
  1153. }
  1154. var version = parseInt(match[1], 10);
  1155. // Test for NaN (yes, this is ugly)
  1156. return version !== version ? -1 : version;
  1157. };
  1158. var getCanSendMaxMessageSize = function getCanSendMaxMessageSize(remoteIsFirefox) {
  1159. // Every implementation we know can send at least 64 KiB.
  1160. // Note: Although Chrome is technically able to send up to 256 KiB, the
  1161. // data does not reach the other peer reliably.
  1162. // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=8419
  1163. var canSendMaxMessageSize = 65536;
  1164. if (browserDetails.browser === 'firefox') {
  1165. if (browserDetails.version < 57) {
  1166. if (remoteIsFirefox === -1) {
  1167. // FF < 57 will send in 16 KiB chunks using the deprecated PPID
  1168. // fragmentation.
  1169. canSendMaxMessageSize = 16384;
  1170. } else {
  1171. // However, other FF (and RAWRTC) can reassemble PPID-fragmented
  1172. // messages. Thus, supporting ~2 GiB when sending.
  1173. canSendMaxMessageSize = 2147483637;
  1174. }
  1175. } else if (browserDetails.version < 60) {
  1176. // Currently, all FF >= 57 will reset the remote maximum message size
  1177. // to the default value when a data channel is created at a later
  1178. // stage. :(
  1179. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831
  1180. canSendMaxMessageSize = browserDetails.version === 57 ? 65535 : 65536;
  1181. } else {
  1182. // FF >= 60 supports sending ~2 GiB
  1183. canSendMaxMessageSize = 2147483637;
  1184. }
  1185. }
  1186. return canSendMaxMessageSize;
  1187. };
  1188. var getMaxMessageSize = function getMaxMessageSize(description, remoteIsFirefox) {
  1189. // Note: 65536 bytes is the default value from the SDP spec. Also,
  1190. // every implementation we know supports receiving 65536 bytes.
  1191. var maxMessageSize = 65536;
  1192. // FF 57 has a slightly incorrect default remote max message size, so
  1193. // we need to adjust it here to avoid a failure when sending.
  1194. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1425697
  1195. if (browserDetails.browser === 'firefox' && browserDetails.version === 57) {
  1196. maxMessageSize = 65535;
  1197. }
  1198. var match = _sdp2.default.matchPrefix(description.sdp, 'a=max-message-size:');
  1199. if (match.length > 0) {
  1200. maxMessageSize = parseInt(match[0].substr(19), 10);
  1201. } else if (browserDetails.browser === 'firefox' && remoteIsFirefox !== -1) {
  1202. // If the maximum message size is not present in the remote SDP and
  1203. // both local and remote are Firefox, the remote peer can receive
  1204. // ~2 GiB.
  1205. maxMessageSize = 2147483637;
  1206. }
  1207. return maxMessageSize;
  1208. };
  1209. var origSetRemoteDescription = window.RTCPeerConnection.prototype.setRemoteDescription;
  1210. window.RTCPeerConnection.prototype.setRemoteDescription = function () {
  1211. this._sctp = null;
  1212. if (sctpInDescription(arguments[0])) {
  1213. // Check if the remote is FF.
  1214. var isFirefox = getRemoteFirefoxVersion(arguments[0]);
  1215. // Get the maximum message size the local peer is capable of sending
  1216. var canSendMMS = getCanSendMaxMessageSize(isFirefox);
  1217. // Get the maximum message size of the remote peer.
  1218. var remoteMMS = getMaxMessageSize(arguments[0], isFirefox);
  1219. // Determine final maximum message size
  1220. var maxMessageSize = void 0;
  1221. if (canSendMMS === 0 && remoteMMS === 0) {
  1222. maxMessageSize = Number.POSITIVE_INFINITY;
  1223. } else if (canSendMMS === 0 || remoteMMS === 0) {
  1224. maxMessageSize = Math.max(canSendMMS, remoteMMS);
  1225. } else {
  1226. maxMessageSize = Math.min(canSendMMS, remoteMMS);
  1227. }
  1228. // Create a dummy RTCSctpTransport object and the 'maxMessageSize'
  1229. // attribute.
  1230. var sctp = {};
  1231. Object.defineProperty(sctp, 'maxMessageSize', {
  1232. get: function get() {
  1233. return maxMessageSize;
  1234. }
  1235. });
  1236. this._sctp = sctp;
  1237. }
  1238. return origSetRemoteDescription.apply(this, arguments);
  1239. };
  1240. }
  1241. function shimSendThrowTypeError(window) {
  1242. if (!(window.RTCPeerConnection && 'createDataChannel' in window.RTCPeerConnection.prototype)) {
  1243. return;
  1244. }
  1245. // Note: Although Firefox >= 57 has a native implementation, the maximum
  1246. // message size can be reset for all data channels at a later stage.
  1247. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831
  1248. function wrapDcSend(dc, pc) {
  1249. var origDataChannelSend = dc.send;
  1250. dc.send = function () {
  1251. var data = arguments[0];
  1252. var length = data.length || data.size || data.byteLength;
  1253. if (dc.readyState === 'open' && pc.sctp && length > pc.sctp.maxMessageSize) {
  1254. throw new TypeError('Message too large (can send a maximum of ' + pc.sctp.maxMessageSize + ' bytes)');
  1255. }
  1256. return origDataChannelSend.apply(dc, arguments);
  1257. };
  1258. }
  1259. var origCreateDataChannel = window.RTCPeerConnection.prototype.createDataChannel;
  1260. window.RTCPeerConnection.prototype.createDataChannel = function () {
  1261. var dataChannel = origCreateDataChannel.apply(this, arguments);
  1262. wrapDcSend(dataChannel, this);
  1263. return dataChannel;
  1264. };
  1265. utils.wrapPeerConnectionEvent(window, 'datachannel', function (e) {
  1266. wrapDcSend(e.channel, e.target);
  1267. return e;
  1268. });
  1269. }
  1270. /* shims RTCConnectionState by pretending it is the same as iceConnectionState.
  1271. * See https://bugs.chromium.org/p/webrtc/issues/detail?id=6145#c12
  1272. * for why this is a valid hack in Chrome. In Firefox it is slightly incorrect
  1273. * since DTLS failures would be hidden. See
  1274. * https://bugzilla.mozilla.org/show_bug.cgi?id=1265827
  1275. * for the Firefox tracking bug.
  1276. */
  1277. function shimConnectionState(window) {
  1278. if (!window.RTCPeerConnection || 'connectionState' in window.RTCPeerConnection.prototype) {
  1279. return;
  1280. }
  1281. var proto = window.RTCPeerConnection.prototype;
  1282. Object.defineProperty(proto, 'connectionState', {
  1283. get: function get() {
  1284. return {
  1285. completed: 'connected',
  1286. checking: 'connecting'
  1287. }[this.iceConnectionState] || this.iceConnectionState;
  1288. },
  1289. enumerable: true,
  1290. configurable: true
  1291. });
  1292. Object.defineProperty(proto, 'onconnectionstatechange', {
  1293. get: function get() {
  1294. return this._onconnectionstatechange || null;
  1295. },
  1296. set: function set(cb) {
  1297. if (this._onconnectionstatechange) {
  1298. this.removeEventListener('connectionstatechange', this._onconnectionstatechange);
  1299. delete this._onconnectionstatechange;
  1300. }
  1301. if (cb) {
  1302. this.addEventListener('connectionstatechange', this._onconnectionstatechange = cb);
  1303. }
  1304. },
  1305. enumerable: true,
  1306. configurable: true
  1307. });
  1308. ['setLocalDescription', 'setRemoteDescription'].forEach(function (method) {
  1309. var origMethod = proto[method];
  1310. proto[method] = function () {
  1311. if (!this._connectionstatechangepoly) {
  1312. this._connectionstatechangepoly = function (e) {
  1313. var pc = e.target;
  1314. if (pc._lastConnectionState !== pc.connectionState) {
  1315. pc._lastConnectionState = pc.connectionState;
  1316. var newEvent = new Event('connectionstatechange', e);
  1317. pc.dispatchEvent(newEvent);
  1318. }
  1319. return e;
  1320. };
  1321. this.addEventListener('iceconnectionstatechange', this._connectionstatechangepoly);
  1322. }
  1323. return origMethod.apply(this, arguments);
  1324. };
  1325. });
  1326. }
  1327. function removeAllowExtmapMixed(window) {
  1328. /* remove a=extmap-allow-mixed for Chrome < M71 */
  1329. if (!window.RTCPeerConnection) {
  1330. return;
  1331. }
  1332. var browserDetails = utils.detectBrowser(window);
  1333. if (browserDetails.browser === 'chrome' && browserDetails.version >= 71) {
  1334. return;
  1335. }
  1336. var nativeSRD = window.RTCPeerConnection.prototype.setRemoteDescription;
  1337. window.RTCPeerConnection.prototype.setRemoteDescription = function (desc) {
  1338. if (desc && desc.sdp && desc.sdp.indexOf('\na=extmap-allow-mixed') !== -1) {
  1339. desc.sdp = desc.sdp.split('\n').filter(function (line) {
  1340. return line.trim() !== 'a=extmap-allow-mixed';
  1341. }).join('\n');
  1342. }
  1343. return nativeSRD.apply(this, arguments);
  1344. };
  1345. }
  1346. },{"./utils":15,"sdp":17}],7:[function(require,module,exports){
  1347. /*
  1348. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  1349. *
  1350. * Use of this source code is governed by a BSD-style license
  1351. * that can be found in the LICENSE file in the root of the source
  1352. * tree.
  1353. */
  1354. /* eslint-env node */
  1355. 'use strict';
  1356. Object.defineProperty(exports, "__esModule", {
  1357. value: true
  1358. });
  1359. exports.shimGetDisplayMedia = exports.shimGetUserMedia = undefined;
  1360. var _getusermedia = require('./getusermedia');
  1361. Object.defineProperty(exports, 'shimGetUserMedia', {
  1362. enumerable: true,
  1363. get: function get() {
  1364. return _getusermedia.shimGetUserMedia;
  1365. }
  1366. });
  1367. var _getdisplaymedia = require('./getdisplaymedia');
  1368. Object.defineProperty(exports, 'shimGetDisplayMedia', {
  1369. enumerable: true,
  1370. get: function get() {
  1371. return _getdisplaymedia.shimGetDisplayMedia;
  1372. }
  1373. });
  1374. exports.shimPeerConnection = shimPeerConnection;
  1375. exports.shimReplaceTrack = shimReplaceTrack;
  1376. var _utils = require('../utils');
  1377. var utils = _interopRequireWildcard(_utils);
  1378. var _filtericeservers = require('./filtericeservers');
  1379. var _rtcpeerconnectionShim = require('rtcpeerconnection-shim');
  1380. var _rtcpeerconnectionShim2 = _interopRequireDefault(_rtcpeerconnectionShim);
  1381. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1382. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  1383. function shimPeerConnection(window) {
  1384. var browserDetails = utils.detectBrowser(window);
  1385. if (window.RTCIceGatherer) {
  1386. if (!window.RTCIceCandidate) {
  1387. window.RTCIceCandidate = function (args) {
  1388. return args;
  1389. };
  1390. }
  1391. if (!window.RTCSessionDescription) {
  1392. window.RTCSessionDescription = function (args) {
  1393. return args;
  1394. };
  1395. }
  1396. // this adds an additional event listener to MediaStrackTrack that signals
  1397. // when a tracks enabled property was changed. Workaround for a bug in
  1398. // addStream, see below. No longer required in 15025+
  1399. if (browserDetails.version < 15025) {
  1400. var origMSTEnabled = Object.getOwnPropertyDescriptor(window.MediaStreamTrack.prototype, 'enabled');
  1401. Object.defineProperty(window.MediaStreamTrack.prototype, 'enabled', {
  1402. set: function set(value) {
  1403. origMSTEnabled.set.call(this, value);
  1404. var ev = new Event('enabled');
  1405. ev.enabled = value;
  1406. this.dispatchEvent(ev);
  1407. }
  1408. });
  1409. }
  1410. }
  1411. // ORTC defines the DTMF sender a bit different.
  1412. // https://github.com/w3c/ortc/issues/714
  1413. if (window.RTCRtpSender && !('dtmf' in window.RTCRtpSender.prototype)) {
  1414. Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', {
  1415. get: function get() {
  1416. if (this._dtmf === undefined) {
  1417. if (this.track.kind === 'audio') {
  1418. this._dtmf = new window.RTCDtmfSender(this);
  1419. } else if (this.track.kind === 'video') {
  1420. this._dtmf = null;
  1421. }
  1422. }
  1423. return this._dtmf;
  1424. }
  1425. });
  1426. }
  1427. // Edge currently only implements the RTCDtmfSender, not the
  1428. // RTCDTMFSender alias. See http://draft.ortc.org/#rtcdtmfsender2*
  1429. if (window.RTCDtmfSender && !window.RTCDTMFSender) {
  1430. window.RTCDTMFSender = window.RTCDtmfSender;
  1431. }
  1432. var RTCPeerConnectionShim = (0, _rtcpeerconnectionShim2.default)(window, browserDetails.version);
  1433. window.RTCPeerConnection = function (config) {
  1434. if (config && config.iceServers) {
  1435. config.iceServers = (0, _filtericeservers.filterIceServers)(config.iceServers, browserDetails.version);
  1436. utils.log('ICE servers after filtering:', config.iceServers);
  1437. }
  1438. return new RTCPeerConnectionShim(config);
  1439. };
  1440. window.RTCPeerConnection.prototype = RTCPeerConnectionShim.prototype;
  1441. }
  1442. function shimReplaceTrack(window) {
  1443. // ORTC has replaceTrack -- https://github.com/w3c/ortc/issues/614
  1444. if (window.RTCRtpSender && !('replaceTrack' in window.RTCRtpSender.prototype)) {
  1445. window.RTCRtpSender.prototype.replaceTrack = window.RTCRtpSender.prototype.setTrack;
  1446. }
  1447. }
  1448. },{"../utils":15,"./filtericeservers":8,"./getdisplaymedia":9,"./getusermedia":10,"rtcpeerconnection-shim":16}],8:[function(require,module,exports){
  1449. /*
  1450. * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
  1451. *
  1452. * Use of this source code is governed by a BSD-style license
  1453. * that can be found in the LICENSE file in the root of the source
  1454. * tree.
  1455. */
  1456. /* eslint-env node */
  1457. 'use strict';
  1458. Object.defineProperty(exports, "__esModule", {
  1459. value: true
  1460. });
  1461. exports.filterIceServers = filterIceServers;
  1462. var _utils = require('../utils');
  1463. var utils = _interopRequireWildcard(_utils);
  1464. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  1465. // Edge does not like
  1466. // 1) stun: filtered after 14393 unless ?transport=udp is present
  1467. // 2) turn: that does not have all of turn:host:port?transport=udp
  1468. // 3) turn: with ipv6 addresses
  1469. // 4) turn: occurring muliple times
  1470. function filterIceServers(iceServers, edgeVersion) {
  1471. var hasTurn = false;
  1472. iceServers = JSON.parse(JSON.stringify(iceServers));
  1473. return iceServers.filter(function (server) {
  1474. if (server && (server.urls || server.url)) {
  1475. var urls = server.urls || server.url;
  1476. if (server.url && !server.urls) {
  1477. utils.deprecated('RTCIceServer.url', 'RTCIceServer.urls');
  1478. }
  1479. var isString = typeof urls === 'string';
  1480. if (isString) {
  1481. urls = [urls];
  1482. }
  1483. urls = urls.filter(function (url) {
  1484. // filter STUN unconditionally.
  1485. if (url.indexOf('stun:') === 0) {
  1486. return false;
  1487. }
  1488. var validTurn = url.startsWith('turn') && !url.startsWith('turn:[') && url.includes('transport=udp');
  1489. if (validTurn && !hasTurn) {
  1490. hasTurn = true;
  1491. return true;
  1492. }
  1493. return validTurn && !hasTurn;
  1494. });
  1495. delete server.url;
  1496. server.urls = isString ? urls[0] : urls;
  1497. return !!urls.length;
  1498. }
  1499. });
  1500. }
  1501. },{"../utils":15}],9:[function(require,module,exports){
  1502. /*
  1503. * Copyright (c) 2018 The adapter.js project authors. All Rights Reserved.
  1504. *
  1505. * Use of this source code is governed by a BSD-style license
  1506. * that can be found in the LICENSE file in the root of the source
  1507. * tree.
  1508. */
  1509. /* eslint-env node */
  1510. 'use strict';
  1511. Object.defineProperty(exports, "__esModule", {
  1512. value: true
  1513. });
  1514. exports.shimGetDisplayMedia = shimGetDisplayMedia;
  1515. function shimGetDisplayMedia(window) {
  1516. if (!('getDisplayMedia' in window.navigator)) {
  1517. return;
  1518. }
  1519. if (!window.navigator.mediaDevices) {
  1520. return;
  1521. }
  1522. if (window.navigator.mediaDevices && 'getDisplayMedia' in window.navigator.mediaDevices) {
  1523. return;
  1524. }
  1525. window.navigator.mediaDevices.getDisplayMedia = window.navigator.getDisplayMedia.bind(window.navigator);
  1526. }
  1527. },{}],10:[function(require,module,exports){
  1528. /*
  1529. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  1530. *
  1531. * Use of this source code is governed by a BSD-style license
  1532. * that can be found in the LICENSE file in the root of the source
  1533. * tree.
  1534. */
  1535. /* eslint-env node */
  1536. 'use strict';
  1537. Object.defineProperty(exports, "__esModule", {
  1538. value: true
  1539. });
  1540. exports.shimGetUserMedia = shimGetUserMedia;
  1541. function shimGetUserMedia(window) {
  1542. var navigator = window && window.navigator;
  1543. var shimError_ = function shimError_(e) {
  1544. return {
  1545. name: { PermissionDeniedError: 'NotAllowedError' }[e.name] || e.name,
  1546. message: e.message,
  1547. constraint: e.constraint,
  1548. toString: function toString() {
  1549. return this.name;
  1550. }
  1551. };
  1552. };
  1553. // getUserMedia error shim.
  1554. var origGetUserMedia = navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);
  1555. navigator.mediaDevices.getUserMedia = function (c) {
  1556. return origGetUserMedia(c).catch(function (e) {
  1557. return Promise.reject(shimError_(e));
  1558. });
  1559. };
  1560. }
  1561. },{}],11:[function(require,module,exports){
  1562. /*
  1563. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  1564. *
  1565. * Use of this source code is governed by a BSD-style license
  1566. * that can be found in the LICENSE file in the root of the source
  1567. * tree.
  1568. */
  1569. /* eslint-env node */
  1570. 'use strict';
  1571. Object.defineProperty(exports, "__esModule", {
  1572. value: true
  1573. });
  1574. exports.shimGetDisplayMedia = exports.shimGetUserMedia = undefined;
  1575. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  1576. var _getusermedia = require('./getusermedia');
  1577. Object.defineProperty(exports, 'shimGetUserMedia', {
  1578. enumerable: true,
  1579. get: function get() {
  1580. return _getusermedia.shimGetUserMedia;
  1581. }
  1582. });
  1583. var _getdisplaymedia = require('./getdisplaymedia');
  1584. Object.defineProperty(exports, 'shimGetDisplayMedia', {
  1585. enumerable: true,
  1586. get: function get() {
  1587. return _getdisplaymedia.shimGetDisplayMedia;
  1588. }
  1589. });
  1590. exports.shimOnTrack = shimOnTrack;
  1591. exports.shimPeerConnection = shimPeerConnection;
  1592. exports.shimSenderGetStats = shimSenderGetStats;
  1593. exports.shimReceiverGetStats = shimReceiverGetStats;
  1594. exports.shimRemoveStream = shimRemoveStream;
  1595. exports.shimRTCDataChannel = shimRTCDataChannel;
  1596. var _utils = require('../utils');
  1597. var utils = _interopRequireWildcard(_utils);
  1598. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  1599. function shimOnTrack(window) {
  1600. if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCTrackEvent && 'receiver' in window.RTCTrackEvent.prototype && !('transceiver' in window.RTCTrackEvent.prototype)) {
  1601. Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {
  1602. get: function get() {
  1603. return { receiver: this.receiver };
  1604. }
  1605. });
  1606. }
  1607. }
  1608. function shimPeerConnection(window) {
  1609. var browserDetails = utils.detectBrowser(window);
  1610. if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) !== 'object' || !(window.RTCPeerConnection || window.mozRTCPeerConnection)) {
  1611. return; // probably media.peerconnection.enabled=false in about:config
  1612. }
  1613. if (!window.RTCPeerConnection && window.mozRTCPeerConnection) {
  1614. // very basic support for old versions.
  1615. window.RTCPeerConnection = window.mozRTCPeerConnection;
  1616. }
  1617. // shim away need for obsolete RTCIceCandidate/RTCSessionDescription.
  1618. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'].forEach(function (method) {
  1619. var nativeMethod = window.RTCPeerConnection.prototype[method];
  1620. window.RTCPeerConnection.prototype[method] = function () {
  1621. arguments[0] = new (method === 'addIceCandidate' ? window.RTCIceCandidate : window.RTCSessionDescription)(arguments[0]);
  1622. return nativeMethod.apply(this, arguments);
  1623. };
  1624. });
  1625. // support for addIceCandidate(null or undefined)
  1626. var nativeAddIceCandidate = window.RTCPeerConnection.prototype.addIceCandidate;
  1627. window.RTCPeerConnection.prototype.addIceCandidate = function () {
  1628. if (!arguments[0]) {
  1629. if (arguments[1]) {
  1630. arguments[1].apply(null);
  1631. }
  1632. return Promise.resolve();
  1633. }
  1634. return nativeAddIceCandidate.apply(this, arguments);
  1635. };
  1636. var modernStatsTypes = {
  1637. inboundrtp: 'inbound-rtp',
  1638. outboundrtp: 'outbound-rtp',
  1639. candidatepair: 'candidate-pair',
  1640. localcandidate: 'local-candidate',
  1641. remotecandidate: 'remote-candidate'
  1642. };
  1643. var nativeGetStats = window.RTCPeerConnection.prototype.getStats;
  1644. window.RTCPeerConnection.prototype.getStats = function (selector, onSucc, onErr) {
  1645. return nativeGetStats.apply(this, [selector || null]).then(function (stats) {
  1646. if (browserDetails.version < 53 && !onSucc) {
  1647. // Shim only promise getStats with spec-hyphens in type names
  1648. // Leave callback version alone; misc old uses of forEach before Map
  1649. try {
  1650. stats.forEach(function (stat) {
  1651. stat.type = modernStatsTypes[stat.type] || stat.type;
  1652. });
  1653. } catch (e) {
  1654. if (e.name !== 'TypeError') {
  1655. throw e;
  1656. }
  1657. // Avoid TypeError: "type" is read-only, in old versions. 34-43ish
  1658. stats.forEach(function (stat, i) {
  1659. stats.set(i, Object.assign({}, stat, {
  1660. type: modernStatsTypes[stat.type] || stat.type
  1661. }));
  1662. });
  1663. }
  1664. }
  1665. return stats;
  1666. }).then(onSucc, onErr);
  1667. };
  1668. }
  1669. function shimSenderGetStats(window) {
  1670. if (!((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection && window.RTCRtpSender)) {
  1671. return;
  1672. }
  1673. if (window.RTCRtpSender && 'getStats' in window.RTCRtpSender.prototype) {
  1674. return;
  1675. }
  1676. var origGetSenders = window.RTCPeerConnection.prototype.getSenders;
  1677. if (origGetSenders) {
  1678. window.RTCPeerConnection.prototype.getSenders = function () {
  1679. var _this = this;
  1680. var senders = origGetSenders.apply(this, []);
  1681. senders.forEach(function (sender) {
  1682. return sender._pc = _this;
  1683. });
  1684. return senders;
  1685. };
  1686. }
  1687. var origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  1688. if (origAddTrack) {
  1689. window.RTCPeerConnection.prototype.addTrack = function () {
  1690. var sender = origAddTrack.apply(this, arguments);
  1691. sender._pc = this;
  1692. return sender;
  1693. };
  1694. }
  1695. window.RTCRtpSender.prototype.getStats = function () {
  1696. return this.track ? this._pc.getStats(this.track) : Promise.resolve(new Map());
  1697. };
  1698. }
  1699. function shimReceiverGetStats(window) {
  1700. if (!((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection && window.RTCRtpSender)) {
  1701. return;
  1702. }
  1703. if (window.RTCRtpSender && 'getStats' in window.RTCRtpReceiver.prototype) {
  1704. return;
  1705. }
  1706. var origGetReceivers = window.RTCPeerConnection.prototype.getReceivers;
  1707. if (origGetReceivers) {
  1708. window.RTCPeerConnection.prototype.getReceivers = function () {
  1709. var _this2 = this;
  1710. var receivers = origGetReceivers.apply(this, []);
  1711. receivers.forEach(function (receiver) {
  1712. return receiver._pc = _this2;
  1713. });
  1714. return receivers;
  1715. };
  1716. }
  1717. utils.wrapPeerConnectionEvent(window, 'track', function (e) {
  1718. e.receiver._pc = e.srcElement;
  1719. return e;
  1720. });
  1721. window.RTCRtpReceiver.prototype.getStats = function () {
  1722. return this._pc.getStats(this.track);
  1723. };
  1724. }
  1725. function shimRemoveStream(window) {
  1726. if (!window.RTCPeerConnection || 'removeStream' in window.RTCPeerConnection.prototype) {
  1727. return;
  1728. }
  1729. window.RTCPeerConnection.prototype.removeStream = function (stream) {
  1730. var _this3 = this;
  1731. utils.deprecated('removeStream', 'removeTrack');
  1732. this.getSenders().forEach(function (sender) {
  1733. if (sender.track && stream.getTracks().includes(sender.track)) {
  1734. _this3.removeTrack(sender);
  1735. }
  1736. });
  1737. };
  1738. }
  1739. function shimRTCDataChannel(window) {
  1740. // rename DataChannel to RTCDataChannel (native fix in FF60):
  1741. // https://bugzilla.mozilla.org/show_bug.cgi?id=1173851
  1742. if (window.DataChannel && !window.RTCDataChannel) {
  1743. window.RTCDataChannel = window.DataChannel;
  1744. }
  1745. }
  1746. },{"../utils":15,"./getdisplaymedia":12,"./getusermedia":13}],12:[function(require,module,exports){
  1747. /*
  1748. * Copyright (c) 2018 The adapter.js project authors. All Rights Reserved.
  1749. *
  1750. * Use of this source code is governed by a BSD-style license
  1751. * that can be found in the LICENSE file in the root of the source
  1752. * tree.
  1753. */
  1754. /* eslint-env node */
  1755. 'use strict';
  1756. Object.defineProperty(exports, "__esModule", {
  1757. value: true
  1758. });
  1759. exports.shimGetDisplayMedia = shimGetDisplayMedia;
  1760. function shimGetDisplayMedia(window, preferredMediaSource) {
  1761. if (window.navigator.mediaDevices && 'getDisplayMedia' in window.navigator.mediaDevices) {
  1762. return;
  1763. }
  1764. if (!window.navigator.mediaDevices) {
  1765. return;
  1766. }
  1767. window.navigator.mediaDevices.getDisplayMedia = function (constraints) {
  1768. if (!(constraints && constraints.video)) {
  1769. var err = new DOMException('getDisplayMedia without video ' + 'constraints is undefined');
  1770. err.name = 'NotFoundError';
  1771. // from https://heycam.github.io/webidl/#idl-DOMException-error-names
  1772. err.code = 8;
  1773. return Promise.reject(err);
  1774. }
  1775. if (constraints.video === true) {
  1776. constraints.video = { mediaSource: preferredMediaSource };
  1777. } else {
  1778. constraints.video.mediaSource = preferredMediaSource;
  1779. }
  1780. return window.navigator.mediaDevices.getUserMedia(constraints);
  1781. };
  1782. }
  1783. },{}],13:[function(require,module,exports){
  1784. /*
  1785. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  1786. *
  1787. * Use of this source code is governed by a BSD-style license
  1788. * that can be found in the LICENSE file in the root of the source
  1789. * tree.
  1790. */
  1791. /* eslint-env node */
  1792. 'use strict';
  1793. Object.defineProperty(exports, "__esModule", {
  1794. value: true
  1795. });
  1796. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  1797. exports.shimGetUserMedia = shimGetUserMedia;
  1798. var _utils = require('../utils');
  1799. var utils = _interopRequireWildcard(_utils);
  1800. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  1801. function shimGetUserMedia(window) {
  1802. var browserDetails = utils.detectBrowser(window);
  1803. var navigator = window && window.navigator;
  1804. var MediaStreamTrack = window && window.MediaStreamTrack;
  1805. navigator.getUserMedia = function (constraints, onSuccess, onError) {
  1806. // Replace Firefox 44+'s deprecation warning with unprefixed version.
  1807. utils.deprecated('navigator.getUserMedia', 'navigator.mediaDevices.getUserMedia');
  1808. navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);
  1809. };
  1810. if (!(browserDetails.version > 55 && 'autoGainControl' in navigator.mediaDevices.getSupportedConstraints())) {
  1811. var remap = function remap(obj, a, b) {
  1812. if (a in obj && !(b in obj)) {
  1813. obj[b] = obj[a];
  1814. delete obj[a];
  1815. }
  1816. };
  1817. var nativeGetUserMedia = navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);
  1818. navigator.mediaDevices.getUserMedia = function (c) {
  1819. if ((typeof c === 'undefined' ? 'undefined' : _typeof(c)) === 'object' && _typeof(c.audio) === 'object') {
  1820. c = JSON.parse(JSON.stringify(c));
  1821. remap(c.audio, 'autoGainControl', 'mozAutoGainControl');
  1822. remap(c.audio, 'noiseSuppression', 'mozNoiseSuppression');
  1823. }
  1824. return nativeGetUserMedia(c);
  1825. };
  1826. if (MediaStreamTrack && MediaStreamTrack.prototype.getSettings) {
  1827. var nativeGetSettings = MediaStreamTrack.prototype.getSettings;
  1828. MediaStreamTrack.prototype.getSettings = function () {
  1829. var obj = nativeGetSettings.apply(this, arguments);
  1830. remap(obj, 'mozAutoGainControl', 'autoGainControl');
  1831. remap(obj, 'mozNoiseSuppression', 'noiseSuppression');
  1832. return obj;
  1833. };
  1834. }
  1835. if (MediaStreamTrack && MediaStreamTrack.prototype.applyConstraints) {
  1836. var nativeApplyConstraints = MediaStreamTrack.prototype.applyConstraints;
  1837. MediaStreamTrack.prototype.applyConstraints = function (c) {
  1838. if (this.kind === 'audio' && (typeof c === 'undefined' ? 'undefined' : _typeof(c)) === 'object') {
  1839. c = JSON.parse(JSON.stringify(c));
  1840. remap(c, 'autoGainControl', 'mozAutoGainControl');
  1841. remap(c, 'noiseSuppression', 'mozNoiseSuppression');
  1842. }
  1843. return nativeApplyConstraints.apply(this, [c]);
  1844. };
  1845. }
  1846. }
  1847. }
  1848. },{"../utils":15}],14:[function(require,module,exports){
  1849. /*
  1850. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  1851. *
  1852. * Use of this source code is governed by a BSD-style license
  1853. * that can be found in the LICENSE file in the root of the source
  1854. * tree.
  1855. */
  1856. 'use strict';
  1857. Object.defineProperty(exports, "__esModule", {
  1858. value: true
  1859. });
  1860. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  1861. exports.shimLocalStreamsAPI = shimLocalStreamsAPI;
  1862. exports.shimRemoteStreamsAPI = shimRemoteStreamsAPI;
  1863. exports.shimCallbacksAPI = shimCallbacksAPI;
  1864. exports.shimGetUserMedia = shimGetUserMedia;
  1865. exports.shimConstraints = shimConstraints;
  1866. exports.shimRTCIceServerUrls = shimRTCIceServerUrls;
  1867. exports.shimTrackEventTransceiver = shimTrackEventTransceiver;
  1868. exports.shimCreateOfferLegacy = shimCreateOfferLegacy;
  1869. var _utils = require('../utils');
  1870. var utils = _interopRequireWildcard(_utils);
  1871. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
  1872. function shimLocalStreamsAPI(window) {
  1873. if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) !== 'object' || !window.RTCPeerConnection) {
  1874. return;
  1875. }
  1876. if (!('getLocalStreams' in window.RTCPeerConnection.prototype)) {
  1877. window.RTCPeerConnection.prototype.getLocalStreams = function () {
  1878. if (!this._localStreams) {
  1879. this._localStreams = [];
  1880. }
  1881. return this._localStreams;
  1882. };
  1883. }
  1884. if (!('addStream' in window.RTCPeerConnection.prototype)) {
  1885. var _addTrack = window.RTCPeerConnection.prototype.addTrack;
  1886. window.RTCPeerConnection.prototype.addStream = function (stream) {
  1887. var _this = this;
  1888. if (!this._localStreams) {
  1889. this._localStreams = [];
  1890. }
  1891. if (!this._localStreams.includes(stream)) {
  1892. this._localStreams.push(stream);
  1893. }
  1894. stream.getTracks().forEach(function (track) {
  1895. return _addTrack.call(_this, track, stream);
  1896. });
  1897. };
  1898. window.RTCPeerConnection.prototype.addTrack = function (track, stream) {
  1899. if (stream) {
  1900. if (!this._localStreams) {
  1901. this._localStreams = [stream];
  1902. } else if (!this._localStreams.includes(stream)) {
  1903. this._localStreams.push(stream);
  1904. }
  1905. }
  1906. return _addTrack.call(this, track, stream);
  1907. };
  1908. }
  1909. if (!('removeStream' in window.RTCPeerConnection.prototype)) {
  1910. window.RTCPeerConnection.prototype.removeStream = function (stream) {
  1911. var _this2 = this;
  1912. if (!this._localStreams) {
  1913. this._localStreams = [];
  1914. }
  1915. var index = this._localStreams.indexOf(stream);
  1916. if (index === -1) {
  1917. return;
  1918. }
  1919. this._localStreams.splice(index, 1);
  1920. var tracks = stream.getTracks();
  1921. this.getSenders().forEach(function (sender) {
  1922. if (tracks.includes(sender.track)) {
  1923. _this2.removeTrack(sender);
  1924. }
  1925. });
  1926. };
  1927. }
  1928. }
  1929. function shimRemoteStreamsAPI(window) {
  1930. if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) !== 'object' || !window.RTCPeerConnection) {
  1931. return;
  1932. }
  1933. if (!('getRemoteStreams' in window.RTCPeerConnection.prototype)) {
  1934. window.RTCPeerConnection.prototype.getRemoteStreams = function () {
  1935. return this._remoteStreams ? this._remoteStreams : [];
  1936. };
  1937. }
  1938. if (!('onaddstream' in window.RTCPeerConnection.prototype)) {
  1939. Object.defineProperty(window.RTCPeerConnection.prototype, 'onaddstream', {
  1940. get: function get() {
  1941. return this._onaddstream;
  1942. },
  1943. set: function set(f) {
  1944. var _this3 = this;
  1945. if (this._onaddstream) {
  1946. this.removeEventListener('addstream', this._onaddstream);
  1947. this.removeEventListener('track', this._onaddstreampoly);
  1948. }
  1949. this.addEventListener('addstream', this._onaddstream = f);
  1950. this.addEventListener('track', this._onaddstreampoly = function (e) {
  1951. e.streams.forEach(function (stream) {
  1952. if (!_this3._remoteStreams) {
  1953. _this3._remoteStreams = [];
  1954. }
  1955. if (_this3._remoteStreams.includes(stream)) {
  1956. return;
  1957. }
  1958. _this3._remoteStreams.push(stream);
  1959. var event = new Event('addstream');
  1960. event.stream = stream;
  1961. _this3.dispatchEvent(event);
  1962. });
  1963. });
  1964. }
  1965. });
  1966. var origSetRemoteDescription = window.RTCPeerConnection.prototype.setRemoteDescription;
  1967. window.RTCPeerConnection.prototype.setRemoteDescription = function () {
  1968. var pc = this;
  1969. if (!this._onaddstreampoly) {
  1970. this.addEventListener('track', this._onaddstreampoly = function (e) {
  1971. e.streams.forEach(function (stream) {
  1972. if (!pc._remoteStreams) {
  1973. pc._remoteStreams = [];
  1974. }
  1975. if (pc._remoteStreams.indexOf(stream) >= 0) {
  1976. return;
  1977. }
  1978. pc._remoteStreams.push(stream);
  1979. var event = new Event('addstream');
  1980. event.stream = stream;
  1981. pc.dispatchEvent(event);
  1982. });
  1983. });
  1984. }
  1985. return origSetRemoteDescription.apply(pc, arguments);
  1986. };
  1987. }
  1988. }
  1989. function shimCallbacksAPI(window) {
  1990. if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) !== 'object' || !window.RTCPeerConnection) {
  1991. return;
  1992. }
  1993. var prototype = window.RTCPeerConnection.prototype;
  1994. var createOffer = prototype.createOffer;
  1995. var createAnswer = prototype.createAnswer;
  1996. var setLocalDescription = prototype.setLocalDescription;
  1997. var setRemoteDescription = prototype.setRemoteDescription;
  1998. var addIceCandidate = prototype.addIceCandidate;
  1999. prototype.createOffer = function (successCallback, failureCallback) {
  2000. var options = arguments.length >= 2 ? arguments[2] : arguments[0];
  2001. var promise = createOffer.apply(this, [options]);
  2002. if (!failureCallback) {
  2003. return promise;
  2004. }
  2005. promise.then(successCallback, failureCallback);
  2006. return Promise.resolve();
  2007. };
  2008. prototype.createAnswer = function (successCallback, failureCallback) {
  2009. var options = arguments.length >= 2 ? arguments[2] : arguments[0];
  2010. var promise = createAnswer.apply(this, [options]);
  2011. if (!failureCallback) {
  2012. return promise;
  2013. }
  2014. promise.then(successCallback, failureCallback);
  2015. return Promise.resolve();
  2016. };
  2017. var withCallback = function withCallback(description, successCallback, failureCallback) {
  2018. var promise = setLocalDescription.apply(this, [description]);
  2019. if (!failureCallback) {
  2020. return promise;
  2021. }
  2022. promise.then(successCallback, failureCallback);
  2023. return Promise.resolve();
  2024. };
  2025. prototype.setLocalDescription = withCallback;
  2026. withCallback = function withCallback(description, successCallback, failureCallback) {
  2027. var promise = setRemoteDescription.apply(this, [description]);
  2028. if (!failureCallback) {
  2029. return promise;
  2030. }
  2031. promise.then(successCallback, failureCallback);
  2032. return Promise.resolve();
  2033. };
  2034. prototype.setRemoteDescription = withCallback;
  2035. withCallback = function withCallback(candidate, successCallback, failureCallback) {
  2036. var promise = addIceCandidate.apply(this, [candidate]);
  2037. if (!failureCallback) {
  2038. return promise;
  2039. }
  2040. promise.then(successCallback, failureCallback);
  2041. return Promise.resolve();
  2042. };
  2043. prototype.addIceCandidate = withCallback;
  2044. }
  2045. function shimGetUserMedia(window) {
  2046. var navigator = window && window.navigator;
  2047. if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
  2048. // shim not needed in Safari 12.1
  2049. var mediaDevices = navigator.mediaDevices;
  2050. var _getUserMedia = mediaDevices.getUserMedia.bind(mediaDevices);
  2051. navigator.mediaDevices.getUserMedia = function (constraints) {
  2052. return _getUserMedia(shimConstraints(constraints));
  2053. };
  2054. }
  2055. if (!navigator.getUserMedia && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
  2056. navigator.getUserMedia = function (constraints, cb, errcb) {
  2057. navigator.mediaDevices.getUserMedia(constraints).then(cb, errcb);
  2058. }.bind(navigator);
  2059. }
  2060. }
  2061. function shimConstraints(constraints) {
  2062. if (constraints && constraints.video !== undefined) {
  2063. return Object.assign({}, constraints, { video: utils.compactObject(constraints.video) });
  2064. }
  2065. return constraints;
  2066. }
  2067. function shimRTCIceServerUrls(window) {
  2068. // migrate from non-spec RTCIceServer.url to RTCIceServer.urls
  2069. var OrigPeerConnection = window.RTCPeerConnection;
  2070. window.RTCPeerConnection = function (pcConfig, pcConstraints) {
  2071. if (pcConfig && pcConfig.iceServers) {
  2072. var newIceServers = [];
  2073. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  2074. var server = pcConfig.iceServers[i];
  2075. if (!server.hasOwnProperty('urls') && server.hasOwnProperty('url')) {
  2076. utils.deprecated('RTCIceServer.url', 'RTCIceServer.urls');
  2077. server = JSON.parse(JSON.stringify(server));
  2078. server.urls = server.url;
  2079. delete server.url;
  2080. newIceServers.push(server);
  2081. } else {
  2082. newIceServers.push(pcConfig.iceServers[i]);
  2083. }
  2084. }
  2085. pcConfig.iceServers = newIceServers;
  2086. }
  2087. return new OrigPeerConnection(pcConfig, pcConstraints);
  2088. };
  2089. window.RTCPeerConnection.prototype = OrigPeerConnection.prototype;
  2090. // wrap static methods. Currently just generateCertificate.
  2091. if ('generateCertificate' in window.RTCPeerConnection) {
  2092. Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
  2093. get: function get() {
  2094. return OrigPeerConnection.generateCertificate;
  2095. }
  2096. });
  2097. }
  2098. }
  2099. function shimTrackEventTransceiver(window) {
  2100. // Add event.transceiver member over deprecated event.receiver
  2101. if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && window.RTCPeerConnection && 'receiver' in window.RTCTrackEvent.prototype &&
  2102. // can't check 'transceiver' in window.RTCTrackEvent.prototype, as it is
  2103. // defined for some reason even when window.RTCTransceiver is not.
  2104. !window.RTCTransceiver) {
  2105. Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {
  2106. get: function get() {
  2107. return { receiver: this.receiver };
  2108. }
  2109. });
  2110. }
  2111. }
  2112. function shimCreateOfferLegacy(window) {
  2113. var origCreateOffer = window.RTCPeerConnection.prototype.createOffer;
  2114. window.RTCPeerConnection.prototype.createOffer = function (offerOptions) {
  2115. if (offerOptions) {
  2116. if (typeof offerOptions.offerToReceiveAudio !== 'undefined') {
  2117. // support bit values
  2118. offerOptions.offerToReceiveAudio = !!offerOptions.offerToReceiveAudio;
  2119. }
  2120. var audioTransceiver = this.getTransceivers().find(function (transceiver) {
  2121. return transceiver.receiver.track.kind === 'audio';
  2122. });
  2123. if (offerOptions.offerToReceiveAudio === false && audioTransceiver) {
  2124. if (audioTransceiver.direction === 'sendrecv') {
  2125. if (audioTransceiver.setDirection) {
  2126. audioTransceiver.setDirection('sendonly');
  2127. } else {
  2128. audioTransceiver.direction = 'sendonly';
  2129. }
  2130. } else if (audioTransceiver.direction === 'recvonly') {
  2131. if (audioTransceiver.setDirection) {
  2132. audioTransceiver.setDirection('inactive');
  2133. } else {
  2134. audioTransceiver.direction = 'inactive';
  2135. }
  2136. }
  2137. } else if (offerOptions.offerToReceiveAudio === true && !audioTransceiver) {
  2138. this.addTransceiver('audio');
  2139. }
  2140. if (typeof offerOptions.offerToReceiveVideo !== 'undefined') {
  2141. // support bit values
  2142. offerOptions.offerToReceiveVideo = !!offerOptions.offerToReceiveVideo;
  2143. }
  2144. var videoTransceiver = this.getTransceivers().find(function (transceiver) {
  2145. return transceiver.receiver.track.kind === 'video';
  2146. });
  2147. if (offerOptions.offerToReceiveVideo === false && videoTransceiver) {
  2148. if (videoTransceiver.direction === 'sendrecv') {
  2149. if (videoTransceiver.setDirection) {
  2150. videoTransceiver.setDirection('sendonly');
  2151. } else {
  2152. videoTransceiver.direction = 'sendonly';
  2153. }
  2154. } else if (videoTransceiver.direction === 'recvonly') {
  2155. if (videoTransceiver.setDirection) {
  2156. videoTransceiver.setDirection('inactive');
  2157. } else {
  2158. videoTransceiver.direction = 'inactive';
  2159. }
  2160. }
  2161. } else if (offerOptions.offerToReceiveVideo === true && !videoTransceiver) {
  2162. this.addTransceiver('video');
  2163. }
  2164. }
  2165. return origCreateOffer.apply(this, arguments);
  2166. };
  2167. }
  2168. },{"../utils":15}],15:[function(require,module,exports){
  2169. /*
  2170. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  2171. *
  2172. * Use of this source code is governed by a BSD-style license
  2173. * that can be found in the LICENSE file in the root of the source
  2174. * tree.
  2175. */
  2176. /* eslint-env node */
  2177. 'use strict';
  2178. Object.defineProperty(exports, "__esModule", {
  2179. value: true
  2180. });
  2181. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  2182. exports.extractVersion = extractVersion;
  2183. exports.wrapPeerConnectionEvent = wrapPeerConnectionEvent;
  2184. exports.disableLog = disableLog;
  2185. exports.disableWarnings = disableWarnings;
  2186. exports.log = log;
  2187. exports.deprecated = deprecated;
  2188. exports.detectBrowser = detectBrowser;
  2189. exports.compactObject = compactObject;
  2190. exports.walkStats = walkStats;
  2191. exports.filterStats = filterStats;
  2192. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  2193. var logDisabled_ = true;
  2194. var deprecationWarnings_ = true;
  2195. /**
  2196. * Extract browser version out of the provided user agent string.
  2197. *
  2198. * @param {!string} uastring userAgent string.
  2199. * @param {!string} expr Regular expression used as match criteria.
  2200. * @param {!number} pos position in the version string to be returned.
  2201. * @return {!number} browser version.
  2202. */
  2203. function extractVersion(uastring, expr, pos) {
  2204. var match = uastring.match(expr);
  2205. return match && match.length >= pos && parseInt(match[pos], 10);
  2206. }
  2207. // Wraps the peerconnection event eventNameToWrap in a function
  2208. // which returns the modified event object (or false to prevent
  2209. // the event).
  2210. function wrapPeerConnectionEvent(window, eventNameToWrap, wrapper) {
  2211. if (!window.RTCPeerConnection) {
  2212. return;
  2213. }
  2214. var proto = window.RTCPeerConnection.prototype;
  2215. var nativeAddEventListener = proto.addEventListener;
  2216. proto.addEventListener = function (nativeEventName, cb) {
  2217. if (nativeEventName !== eventNameToWrap) {
  2218. return nativeAddEventListener.apply(this, arguments);
  2219. }
  2220. var wrappedCallback = function wrappedCallback(e) {
  2221. var modifiedEvent = wrapper(e);
  2222. if (modifiedEvent) {
  2223. cb(modifiedEvent);
  2224. }
  2225. };
  2226. this._eventMap = this._eventMap || {};
  2227. this._eventMap[cb] = wrappedCallback;
  2228. return nativeAddEventListener.apply(this, [nativeEventName, wrappedCallback]);
  2229. };
  2230. var nativeRemoveEventListener = proto.removeEventListener;
  2231. proto.removeEventListener = function (nativeEventName, cb) {
  2232. if (nativeEventName !== eventNameToWrap || !this._eventMap || !this._eventMap[cb]) {
  2233. return nativeRemoveEventListener.apply(this, arguments);
  2234. }
  2235. var unwrappedCb = this._eventMap[cb];
  2236. delete this._eventMap[cb];
  2237. return nativeRemoveEventListener.apply(this, [nativeEventName, unwrappedCb]);
  2238. };
  2239. Object.defineProperty(proto, 'on' + eventNameToWrap, {
  2240. get: function get() {
  2241. return this['_on' + eventNameToWrap];
  2242. },
  2243. set: function set(cb) {
  2244. if (this['_on' + eventNameToWrap]) {
  2245. this.removeEventListener(eventNameToWrap, this['_on' + eventNameToWrap]);
  2246. delete this['_on' + eventNameToWrap];
  2247. }
  2248. if (cb) {
  2249. this.addEventListener(eventNameToWrap, this['_on' + eventNameToWrap] = cb);
  2250. }
  2251. },
  2252. enumerable: true,
  2253. configurable: true
  2254. });
  2255. }
  2256. function disableLog(bool) {
  2257. if (typeof bool !== 'boolean') {
  2258. return new Error('Argument type: ' + (typeof bool === 'undefined' ? 'undefined' : _typeof(bool)) + '. Please use a boolean.');
  2259. }
  2260. logDisabled_ = bool;
  2261. return bool ? 'adapter.js logging disabled' : 'adapter.js logging enabled';
  2262. }
  2263. /**
  2264. * Disable or enable deprecation warnings
  2265. * @param {!boolean} bool set to true to disable warnings.
  2266. */
  2267. function disableWarnings(bool) {
  2268. if (typeof bool !== 'boolean') {
  2269. return new Error('Argument type: ' + (typeof bool === 'undefined' ? 'undefined' : _typeof(bool)) + '. Please use a boolean.');
  2270. }
  2271. deprecationWarnings_ = !bool;
  2272. return 'adapter.js deprecation warnings ' + (bool ? 'disabled' : 'enabled');
  2273. }
  2274. function log() {
  2275. if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object') {
  2276. if (logDisabled_) {
  2277. return;
  2278. }
  2279. if (typeof console !== 'undefined' && typeof console.log === 'function') {
  2280. console.log.apply(console, arguments);
  2281. }
  2282. }
  2283. }
  2284. /**
  2285. * Shows a deprecation warning suggesting the modern and spec-compatible API.
  2286. */
  2287. function deprecated(oldMethod, newMethod) {
  2288. if (!deprecationWarnings_) {
  2289. return;
  2290. }
  2291. console.warn(oldMethod + ' is deprecated, please use ' + newMethod + ' instead.');
  2292. }
  2293. /**
  2294. * Browser detector.
  2295. *
  2296. * @return {object} result containing browser and version
  2297. * properties.
  2298. */
  2299. function detectBrowser(window) {
  2300. var navigator = window.navigator;
  2301. // Returned result object.
  2302. var result = { browser: null, version: null };
  2303. // Fail early if it's not a browser
  2304. if (typeof window === 'undefined' || !window.navigator) {
  2305. result.browser = 'Not a browser.';
  2306. return result;
  2307. }
  2308. if (navigator.mozGetUserMedia) {
  2309. // Firefox.
  2310. result.browser = 'firefox';
  2311. result.version = extractVersion(navigator.userAgent, /Firefox\/(\d+)\./, 1);
  2312. } else if (navigator.webkitGetUserMedia || window.isSecureContext === false && window.webkitRTCPeerConnection && !window.RTCIceGatherer) {
  2313. // Chrome, Chromium, Webview, Opera.
  2314. // Version matches Chrome/WebRTC version.
  2315. // Chrome 74 removed webkitGetUserMedia on http as well so we need the
  2316. // more complicated fallback to webkitRTCPeerConnection.
  2317. result.browser = 'chrome';
  2318. result.version = extractVersion(navigator.userAgent, /Chrom(e|ium)\/(\d+)\./, 2);
  2319. } else if (navigator.mediaDevices && navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) {
  2320. // Edge.
  2321. result.browser = 'edge';
  2322. result.version = extractVersion(navigator.userAgent, /Edge\/(\d+).(\d+)$/, 2);
  2323. } else if (window.RTCPeerConnection && navigator.userAgent.match(/AppleWebKit\/(\d+)\./)) {
  2324. // Safari.
  2325. result.browser = 'safari';
  2326. result.version = extractVersion(navigator.userAgent, /AppleWebKit\/(\d+)\./, 1);
  2327. } else {
  2328. // Default fallthrough: not supported.
  2329. result.browser = 'Not a supported browser.';
  2330. return result;
  2331. }
  2332. return result;
  2333. }
  2334. /**
  2335. * Remove all empty objects and undefined values
  2336. * from a nested object -- an enhanced and vanilla version
  2337. * of Lodash's `compact`.
  2338. */
  2339. function compactObject(data) {
  2340. if ((typeof data === 'undefined' ? 'undefined' : _typeof(data)) !== 'object') {
  2341. return data;
  2342. }
  2343. return Object.keys(data).reduce(function (accumulator, key) {
  2344. var isObject = _typeof(data[key]) === 'object';
  2345. var value = isObject ? compactObject(data[key]) : data[key];
  2346. var isEmptyObject = isObject && !Object.keys(value).length;
  2347. if (value === undefined || isEmptyObject) {
  2348. return accumulator;
  2349. }
  2350. return Object.assign(accumulator, _defineProperty({}, key, value));
  2351. }, {});
  2352. }
  2353. /* iterates the stats graph recursively. */
  2354. function walkStats(stats, base, resultSet) {
  2355. if (!base || resultSet.has(base.id)) {
  2356. return;
  2357. }
  2358. resultSet.set(base.id, base);
  2359. Object.keys(base).forEach(function (name) {
  2360. if (name.endsWith('Id')) {
  2361. walkStats(stats, stats.get(base[name]), resultSet);
  2362. } else if (name.endsWith('Ids')) {
  2363. base[name].forEach(function (id) {
  2364. walkStats(stats, stats.get(id), resultSet);
  2365. });
  2366. }
  2367. });
  2368. }
  2369. /* filter getStats for a sender/receiver track. */
  2370. function filterStats(result, track, outbound) {
  2371. var streamStatsType = outbound ? 'outbound-rtp' : 'inbound-rtp';
  2372. var filteredResult = new Map();
  2373. if (track === null) {
  2374. return filteredResult;
  2375. }
  2376. var trackStats = [];
  2377. result.forEach(function (value) {
  2378. if (value.type === 'track' && value.trackIdentifier === track.id) {
  2379. trackStats.push(value);
  2380. }
  2381. });
  2382. trackStats.forEach(function (trackStat) {
  2383. result.forEach(function (stats) {
  2384. if (stats.type === streamStatsType && stats.trackId === trackStat.id) {
  2385. walkStats(result, stats, filteredResult);
  2386. }
  2387. });
  2388. });
  2389. return filteredResult;
  2390. }
  2391. },{}],16:[function(require,module,exports){
  2392. /*
  2393. * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
  2394. *
  2395. * Use of this source code is governed by a BSD-style license
  2396. * that can be found in the LICENSE file in the root of the source
  2397. * tree.
  2398. */
  2399. /* eslint-env node */
  2400. 'use strict';
  2401. var SDPUtils = require('sdp');
  2402. function fixStatsType(stat) {
  2403. return {
  2404. inboundrtp: 'inbound-rtp',
  2405. outboundrtp: 'outbound-rtp',
  2406. candidatepair: 'candidate-pair',
  2407. localcandidate: 'local-candidate',
  2408. remotecandidate: 'remote-candidate'
  2409. }[stat.type] || stat.type;
  2410. }
  2411. function writeMediaSection(transceiver, caps, type, stream, dtlsRole) {
  2412. var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps);
  2413. // Map ICE parameters (ufrag, pwd) to SDP.
  2414. sdp += SDPUtils.writeIceParameters(
  2415. transceiver.iceGatherer.getLocalParameters());
  2416. // Map DTLS parameters to SDP.
  2417. sdp += SDPUtils.writeDtlsParameters(
  2418. transceiver.dtlsTransport.getLocalParameters(),
  2419. type === 'offer' ? 'actpass' : dtlsRole || 'active');
  2420. sdp += 'a=mid:' + transceiver.mid + '\r\n';
  2421. if (transceiver.rtpSender && transceiver.rtpReceiver) {
  2422. sdp += 'a=sendrecv\r\n';
  2423. } else if (transceiver.rtpSender) {
  2424. sdp += 'a=sendonly\r\n';
  2425. } else if (transceiver.rtpReceiver) {
  2426. sdp += 'a=recvonly\r\n';
  2427. } else {
  2428. sdp += 'a=inactive\r\n';
  2429. }
  2430. if (transceiver.rtpSender) {
  2431. var trackId = transceiver.rtpSender._initialTrackId ||
  2432. transceiver.rtpSender.track.id;
  2433. transceiver.rtpSender._initialTrackId = trackId;
  2434. // spec.
  2435. var msid = 'msid:' + (stream ? stream.id : '-') + ' ' +
  2436. trackId + '\r\n';
  2437. sdp += 'a=' + msid;
  2438. // for Chrome. Legacy should no longer be required.
  2439. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  2440. ' ' + msid;
  2441. // RTX
  2442. if (transceiver.sendEncodingParameters[0].rtx) {
  2443. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  2444. ' ' + msid;
  2445. sdp += 'a=ssrc-group:FID ' +
  2446. transceiver.sendEncodingParameters[0].ssrc + ' ' +
  2447. transceiver.sendEncodingParameters[0].rtx.ssrc +
  2448. '\r\n';
  2449. }
  2450. }
  2451. // FIXME: this should be written by writeRtpDescription.
  2452. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  2453. ' cname:' + SDPUtils.localCName + '\r\n';
  2454. if (transceiver.rtpSender && transceiver.sendEncodingParameters[0].rtx) {
  2455. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  2456. ' cname:' + SDPUtils.localCName + '\r\n';
  2457. }
  2458. return sdp;
  2459. }
  2460. // Edge does not like
  2461. // 1) stun: filtered after 14393 unless ?transport=udp is present
  2462. // 2) turn: that does not have all of turn:host:port?transport=udp
  2463. // 3) turn: with ipv6 addresses
  2464. // 4) turn: occurring muliple times
  2465. function filterIceServers(iceServers, edgeVersion) {
  2466. var hasTurn = false;
  2467. iceServers = JSON.parse(JSON.stringify(iceServers));
  2468. return iceServers.filter(function(server) {
  2469. if (server && (server.urls || server.url)) {
  2470. var urls = server.urls || server.url;
  2471. if (server.url && !server.urls) {
  2472. console.warn('RTCIceServer.url is deprecated! Use urls instead.');
  2473. }
  2474. var isString = typeof urls === 'string';
  2475. if (isString) {
  2476. urls = [urls];
  2477. }
  2478. urls = urls.filter(function(url) {
  2479. var validTurn = url.indexOf('turn:') === 0 &&
  2480. url.indexOf('transport=udp') !== -1 &&
  2481. url.indexOf('turn:[') === -1 &&
  2482. !hasTurn;
  2483. if (validTurn) {
  2484. hasTurn = true;
  2485. return true;
  2486. }
  2487. return url.indexOf('stun:') === 0 && edgeVersion >= 14393 &&
  2488. url.indexOf('?transport=udp') === -1;
  2489. });
  2490. delete server.url;
  2491. server.urls = isString ? urls[0] : urls;
  2492. return !!urls.length;
  2493. }
  2494. });
  2495. }
  2496. // Determines the intersection of local and remote capabilities.
  2497. function getCommonCapabilities(localCapabilities, remoteCapabilities) {
  2498. var commonCapabilities = {
  2499. codecs: [],
  2500. headerExtensions: [],
  2501. fecMechanisms: []
  2502. };
  2503. var findCodecByPayloadType = function(pt, codecs) {
  2504. pt = parseInt(pt, 10);
  2505. for (var i = 0; i < codecs.length; i++) {
  2506. if (codecs[i].payloadType === pt ||
  2507. codecs[i].preferredPayloadType === pt) {
  2508. return codecs[i];
  2509. }
  2510. }
  2511. };
  2512. var rtxCapabilityMatches = function(lRtx, rRtx, lCodecs, rCodecs) {
  2513. var lCodec = findCodecByPayloadType(lRtx.parameters.apt, lCodecs);
  2514. var rCodec = findCodecByPayloadType(rRtx.parameters.apt, rCodecs);
  2515. return lCodec && rCodec &&
  2516. lCodec.name.toLowerCase() === rCodec.name.toLowerCase();
  2517. };
  2518. localCapabilities.codecs.forEach(function(lCodec) {
  2519. for (var i = 0; i < remoteCapabilities.codecs.length; i++) {
  2520. var rCodec = remoteCapabilities.codecs[i];
  2521. if (lCodec.name.toLowerCase() === rCodec.name.toLowerCase() &&
  2522. lCodec.clockRate === rCodec.clockRate) {
  2523. if (lCodec.name.toLowerCase() === 'rtx' &&
  2524. lCodec.parameters && rCodec.parameters.apt) {
  2525. // for RTX we need to find the local rtx that has a apt
  2526. // which points to the same local codec as the remote one.
  2527. if (!rtxCapabilityMatches(lCodec, rCodec,
  2528. localCapabilities.codecs, remoteCapabilities.codecs)) {
  2529. continue;
  2530. }
  2531. }
  2532. rCodec = JSON.parse(JSON.stringify(rCodec)); // deepcopy
  2533. // number of channels is the highest common number of channels
  2534. rCodec.numChannels = Math.min(lCodec.numChannels,
  2535. rCodec.numChannels);
  2536. // push rCodec so we reply with offerer payload type
  2537. commonCapabilities.codecs.push(rCodec);
  2538. // determine common feedback mechanisms
  2539. rCodec.rtcpFeedback = rCodec.rtcpFeedback.filter(function(fb) {
  2540. for (var j = 0; j < lCodec.rtcpFeedback.length; j++) {
  2541. if (lCodec.rtcpFeedback[j].type === fb.type &&
  2542. lCodec.rtcpFeedback[j].parameter === fb.parameter) {
  2543. return true;
  2544. }
  2545. }
  2546. return false;
  2547. });
  2548. // FIXME: also need to determine .parameters
  2549. // see https://github.com/openpeer/ortc/issues/569
  2550. break;
  2551. }
  2552. }
  2553. });
  2554. localCapabilities.headerExtensions.forEach(function(lHeaderExtension) {
  2555. for (var i = 0; i < remoteCapabilities.headerExtensions.length;
  2556. i++) {
  2557. var rHeaderExtension = remoteCapabilities.headerExtensions[i];
  2558. if (lHeaderExtension.uri === rHeaderExtension.uri) {
  2559. commonCapabilities.headerExtensions.push(rHeaderExtension);
  2560. break;
  2561. }
  2562. }
  2563. });
  2564. // FIXME: fecMechanisms
  2565. return commonCapabilities;
  2566. }
  2567. // is action=setLocalDescription with type allowed in signalingState
  2568. function isActionAllowedInSignalingState(action, type, signalingState) {
  2569. return {
  2570. offer: {
  2571. setLocalDescription: ['stable', 'have-local-offer'],
  2572. setRemoteDescription: ['stable', 'have-remote-offer']
  2573. },
  2574. answer: {
  2575. setLocalDescription: ['have-remote-offer', 'have-local-pranswer'],
  2576. setRemoteDescription: ['have-local-offer', 'have-remote-pranswer']
  2577. }
  2578. }[type][action].indexOf(signalingState) !== -1;
  2579. }
  2580. function maybeAddCandidate(iceTransport, candidate) {
  2581. // Edge's internal representation adds some fields therefore
  2582. // not all fieldѕ are taken into account.
  2583. var alreadyAdded = iceTransport.getRemoteCandidates()
  2584. .find(function(remoteCandidate) {
  2585. return candidate.foundation === remoteCandidate.foundation &&
  2586. candidate.ip === remoteCandidate.ip &&
  2587. candidate.port === remoteCandidate.port &&
  2588. candidate.priority === remoteCandidate.priority &&
  2589. candidate.protocol === remoteCandidate.protocol &&
  2590. candidate.type === remoteCandidate.type;
  2591. });
  2592. if (!alreadyAdded) {
  2593. iceTransport.addRemoteCandidate(candidate);
  2594. }
  2595. return !alreadyAdded;
  2596. }
  2597. function makeError(name, description) {
  2598. var e = new Error(description);
  2599. e.name = name;
  2600. // legacy error codes from https://heycam.github.io/webidl/#idl-DOMException-error-names
  2601. e.code = {
  2602. NotSupportedError: 9,
  2603. InvalidStateError: 11,
  2604. InvalidAccessError: 15,
  2605. TypeError: undefined,
  2606. OperationError: undefined
  2607. }[name];
  2608. return e;
  2609. }
  2610. module.exports = function(window, edgeVersion) {
  2611. // https://w3c.github.io/mediacapture-main/#mediastream
  2612. // Helper function to add the track to the stream and
  2613. // dispatch the event ourselves.
  2614. function addTrackToStreamAndFireEvent(track, stream) {
  2615. stream.addTrack(track);
  2616. stream.dispatchEvent(new window.MediaStreamTrackEvent('addtrack',
  2617. {track: track}));
  2618. }
  2619. function removeTrackFromStreamAndFireEvent(track, stream) {
  2620. stream.removeTrack(track);
  2621. stream.dispatchEvent(new window.MediaStreamTrackEvent('removetrack',
  2622. {track: track}));
  2623. }
  2624. function fireAddTrack(pc, track, receiver, streams) {
  2625. var trackEvent = new Event('track');
  2626. trackEvent.track = track;
  2627. trackEvent.receiver = receiver;
  2628. trackEvent.transceiver = {receiver: receiver};
  2629. trackEvent.streams = streams;
  2630. window.setTimeout(function() {
  2631. pc._dispatchEvent('track', trackEvent);
  2632. });
  2633. }
  2634. var RTCPeerConnection = function(config) {
  2635. var pc = this;
  2636. var _eventTarget = document.createDocumentFragment();
  2637. ['addEventListener', 'removeEventListener', 'dispatchEvent']
  2638. .forEach(function(method) {
  2639. pc[method] = _eventTarget[method].bind(_eventTarget);
  2640. });
  2641. this.canTrickleIceCandidates = null;
  2642. this.needNegotiation = false;
  2643. this.localStreams = [];
  2644. this.remoteStreams = [];
  2645. this._localDescription = null;
  2646. this._remoteDescription = null;
  2647. this.signalingState = 'stable';
  2648. this.iceConnectionState = 'new';
  2649. this.connectionState = 'new';
  2650. this.iceGatheringState = 'new';
  2651. config = JSON.parse(JSON.stringify(config || {}));
  2652. this.usingBundle = config.bundlePolicy === 'max-bundle';
  2653. if (config.rtcpMuxPolicy === 'negotiate') {
  2654. throw(makeError('NotSupportedError',
  2655. 'rtcpMuxPolicy \'negotiate\' is not supported'));
  2656. } else if (!config.rtcpMuxPolicy) {
  2657. config.rtcpMuxPolicy = 'require';
  2658. }
  2659. switch (config.iceTransportPolicy) {
  2660. case 'all':
  2661. case 'relay':
  2662. break;
  2663. default:
  2664. config.iceTransportPolicy = 'all';
  2665. break;
  2666. }
  2667. switch (config.bundlePolicy) {
  2668. case 'balanced':
  2669. case 'max-compat':
  2670. case 'max-bundle':
  2671. break;
  2672. default:
  2673. config.bundlePolicy = 'balanced';
  2674. break;
  2675. }
  2676. config.iceServers = filterIceServers(config.iceServers || [], edgeVersion);
  2677. this._iceGatherers = [];
  2678. if (config.iceCandidatePoolSize) {
  2679. for (var i = config.iceCandidatePoolSize; i > 0; i--) {
  2680. this._iceGatherers.push(new window.RTCIceGatherer({
  2681. iceServers: config.iceServers,
  2682. gatherPolicy: config.iceTransportPolicy
  2683. }));
  2684. }
  2685. } else {
  2686. config.iceCandidatePoolSize = 0;
  2687. }
  2688. this._config = config;
  2689. // per-track iceGathers, iceTransports, dtlsTransports, rtpSenders, ...
  2690. // everything that is needed to describe a SDP m-line.
  2691. this.transceivers = [];
  2692. this._sdpSessionId = SDPUtils.generateSessionId();
  2693. this._sdpSessionVersion = 0;
  2694. this._dtlsRole = undefined; // role for a=setup to use in answers.
  2695. this._isClosed = false;
  2696. };
  2697. Object.defineProperty(RTCPeerConnection.prototype, 'localDescription', {
  2698. configurable: true,
  2699. get: function() {
  2700. return this._localDescription;
  2701. }
  2702. });
  2703. Object.defineProperty(RTCPeerConnection.prototype, 'remoteDescription', {
  2704. configurable: true,
  2705. get: function() {
  2706. return this._remoteDescription;
  2707. }
  2708. });
  2709. // set up event handlers on prototype
  2710. RTCPeerConnection.prototype.onicecandidate = null;
  2711. RTCPeerConnection.prototype.onaddstream = null;
  2712. RTCPeerConnection.prototype.ontrack = null;
  2713. RTCPeerConnection.prototype.onremovestream = null;
  2714. RTCPeerConnection.prototype.onsignalingstatechange = null;
  2715. RTCPeerConnection.prototype.oniceconnectionstatechange = null;
  2716. RTCPeerConnection.prototype.onconnectionstatechange = null;
  2717. RTCPeerConnection.prototype.onicegatheringstatechange = null;
  2718. RTCPeerConnection.prototype.onnegotiationneeded = null;
  2719. RTCPeerConnection.prototype.ondatachannel = null;
  2720. RTCPeerConnection.prototype._dispatchEvent = function(name, event) {
  2721. if (this._isClosed) {
  2722. return;
  2723. }
  2724. this.dispatchEvent(event);
  2725. if (typeof this['on' + name] === 'function') {
  2726. this['on' + name](event);
  2727. }
  2728. };
  2729. RTCPeerConnection.prototype._emitGatheringStateChange = function() {
  2730. var event = new Event('icegatheringstatechange');
  2731. this._dispatchEvent('icegatheringstatechange', event);
  2732. };
  2733. RTCPeerConnection.prototype.getConfiguration = function() {
  2734. return this._config;
  2735. };
  2736. RTCPeerConnection.prototype.getLocalStreams = function() {
  2737. return this.localStreams;
  2738. };
  2739. RTCPeerConnection.prototype.getRemoteStreams = function() {
  2740. return this.remoteStreams;
  2741. };
  2742. // internal helper to create a transceiver object.
  2743. // (which is not yet the same as the WebRTC 1.0 transceiver)
  2744. RTCPeerConnection.prototype._createTransceiver = function(kind, doNotAdd) {
  2745. var hasBundleTransport = this.transceivers.length > 0;
  2746. var transceiver = {
  2747. track: null,
  2748. iceGatherer: null,
  2749. iceTransport: null,
  2750. dtlsTransport: null,
  2751. localCapabilities: null,
  2752. remoteCapabilities: null,
  2753. rtpSender: null,
  2754. rtpReceiver: null,
  2755. kind: kind,
  2756. mid: null,
  2757. sendEncodingParameters: null,
  2758. recvEncodingParameters: null,
  2759. stream: null,
  2760. associatedRemoteMediaStreams: [],
  2761. wantReceive: true
  2762. };
  2763. if (this.usingBundle && hasBundleTransport) {
  2764. transceiver.iceTransport = this.transceivers[0].iceTransport;
  2765. transceiver.dtlsTransport = this.transceivers[0].dtlsTransport;
  2766. } else {
  2767. var transports = this._createIceAndDtlsTransports();
  2768. transceiver.iceTransport = transports.iceTransport;
  2769. transceiver.dtlsTransport = transports.dtlsTransport;
  2770. }
  2771. if (!doNotAdd) {
  2772. this.transceivers.push(transceiver);
  2773. }
  2774. return transceiver;
  2775. };
  2776. RTCPeerConnection.prototype.addTrack = function(track, stream) {
  2777. if (this._isClosed) {
  2778. throw makeError('InvalidStateError',
  2779. 'Attempted to call addTrack on a closed peerconnection.');
  2780. }
  2781. var alreadyExists = this.transceivers.find(function(s) {
  2782. return s.track === track;
  2783. });
  2784. if (alreadyExists) {
  2785. throw makeError('InvalidAccessError', 'Track already exists.');
  2786. }
  2787. var transceiver;
  2788. for (var i = 0; i < this.transceivers.length; i++) {
  2789. if (!this.transceivers[i].track &&
  2790. this.transceivers[i].kind === track.kind) {
  2791. transceiver = this.transceivers[i];
  2792. }
  2793. }
  2794. if (!transceiver) {
  2795. transceiver = this._createTransceiver(track.kind);
  2796. }
  2797. this._maybeFireNegotiationNeeded();
  2798. if (this.localStreams.indexOf(stream) === -1) {
  2799. this.localStreams.push(stream);
  2800. }
  2801. transceiver.track = track;
  2802. transceiver.stream = stream;
  2803. transceiver.rtpSender = new window.RTCRtpSender(track,
  2804. transceiver.dtlsTransport);
  2805. return transceiver.rtpSender;
  2806. };
  2807. RTCPeerConnection.prototype.addStream = function(stream) {
  2808. var pc = this;
  2809. if (edgeVersion >= 15025) {
  2810. stream.getTracks().forEach(function(track) {
  2811. pc.addTrack(track, stream);
  2812. });
  2813. } else {
  2814. // Clone is necessary for local demos mostly, attaching directly
  2815. // to two different senders does not work (build 10547).
  2816. // Fixed in 15025 (or earlier)
  2817. var clonedStream = stream.clone();
  2818. stream.getTracks().forEach(function(track, idx) {
  2819. var clonedTrack = clonedStream.getTracks()[idx];
  2820. track.addEventListener('enabled', function(event) {
  2821. clonedTrack.enabled = event.enabled;
  2822. });
  2823. });
  2824. clonedStream.getTracks().forEach(function(track) {
  2825. pc.addTrack(track, clonedStream);
  2826. });
  2827. }
  2828. };
  2829. RTCPeerConnection.prototype.removeTrack = function(sender) {
  2830. if (this._isClosed) {
  2831. throw makeError('InvalidStateError',
  2832. 'Attempted to call removeTrack on a closed peerconnection.');
  2833. }
  2834. if (!(sender instanceof window.RTCRtpSender)) {
  2835. throw new TypeError('Argument 1 of RTCPeerConnection.removeTrack ' +
  2836. 'does not implement interface RTCRtpSender.');
  2837. }
  2838. var transceiver = this.transceivers.find(function(t) {
  2839. return t.rtpSender === sender;
  2840. });
  2841. if (!transceiver) {
  2842. throw makeError('InvalidAccessError',
  2843. 'Sender was not created by this connection.');
  2844. }
  2845. var stream = transceiver.stream;
  2846. transceiver.rtpSender.stop();
  2847. transceiver.rtpSender = null;
  2848. transceiver.track = null;
  2849. transceiver.stream = null;
  2850. // remove the stream from the set of local streams
  2851. var localStreams = this.transceivers.map(function(t) {
  2852. return t.stream;
  2853. });
  2854. if (localStreams.indexOf(stream) === -1 &&
  2855. this.localStreams.indexOf(stream) > -1) {
  2856. this.localStreams.splice(this.localStreams.indexOf(stream), 1);
  2857. }
  2858. this._maybeFireNegotiationNeeded();
  2859. };
  2860. RTCPeerConnection.prototype.removeStream = function(stream) {
  2861. var pc = this;
  2862. stream.getTracks().forEach(function(track) {
  2863. var sender = pc.getSenders().find(function(s) {
  2864. return s.track === track;
  2865. });
  2866. if (sender) {
  2867. pc.removeTrack(sender);
  2868. }
  2869. });
  2870. };
  2871. RTCPeerConnection.prototype.getSenders = function() {
  2872. return this.transceivers.filter(function(transceiver) {
  2873. return !!transceiver.rtpSender;
  2874. })
  2875. .map(function(transceiver) {
  2876. return transceiver.rtpSender;
  2877. });
  2878. };
  2879. RTCPeerConnection.prototype.getReceivers = function() {
  2880. return this.transceivers.filter(function(transceiver) {
  2881. return !!transceiver.rtpReceiver;
  2882. })
  2883. .map(function(transceiver) {
  2884. return transceiver.rtpReceiver;
  2885. });
  2886. };
  2887. RTCPeerConnection.prototype._createIceGatherer = function(sdpMLineIndex,
  2888. usingBundle) {
  2889. var pc = this;
  2890. if (usingBundle && sdpMLineIndex > 0) {
  2891. return this.transceivers[0].iceGatherer;
  2892. } else if (this._iceGatherers.length) {
  2893. return this._iceGatherers.shift();
  2894. }
  2895. var iceGatherer = new window.RTCIceGatherer({
  2896. iceServers: this._config.iceServers,
  2897. gatherPolicy: this._config.iceTransportPolicy
  2898. });
  2899. Object.defineProperty(iceGatherer, 'state',
  2900. {value: 'new', writable: true}
  2901. );
  2902. this.transceivers[sdpMLineIndex].bufferedCandidateEvents = [];
  2903. this.transceivers[sdpMLineIndex].bufferCandidates = function(event) {
  2904. var end = !event.candidate || Object.keys(event.candidate).length === 0;
  2905. // polyfill since RTCIceGatherer.state is not implemented in
  2906. // Edge 10547 yet.
  2907. iceGatherer.state = end ? 'completed' : 'gathering';
  2908. if (pc.transceivers[sdpMLineIndex].bufferedCandidateEvents !== null) {
  2909. pc.transceivers[sdpMLineIndex].bufferedCandidateEvents.push(event);
  2910. }
  2911. };
  2912. iceGatherer.addEventListener('localcandidate',
  2913. this.transceivers[sdpMLineIndex].bufferCandidates);
  2914. return iceGatherer;
  2915. };
  2916. // start gathering from an RTCIceGatherer.
  2917. RTCPeerConnection.prototype._gather = function(mid, sdpMLineIndex) {
  2918. var pc = this;
  2919. var iceGatherer = this.transceivers[sdpMLineIndex].iceGatherer;
  2920. if (iceGatherer.onlocalcandidate) {
  2921. return;
  2922. }
  2923. var bufferedCandidateEvents =
  2924. this.transceivers[sdpMLineIndex].bufferedCandidateEvents;
  2925. this.transceivers[sdpMLineIndex].bufferedCandidateEvents = null;
  2926. iceGatherer.removeEventListener('localcandidate',
  2927. this.transceivers[sdpMLineIndex].bufferCandidates);
  2928. iceGatherer.onlocalcandidate = function(evt) {
  2929. if (pc.usingBundle && sdpMLineIndex > 0) {
  2930. // if we know that we use bundle we can drop candidates with
  2931. // ѕdpMLineIndex > 0. If we don't do this then our state gets
  2932. // confused since we dispose the extra ice gatherer.
  2933. return;
  2934. }
  2935. var event = new Event('icecandidate');
  2936. event.candidate = {sdpMid: mid, sdpMLineIndex: sdpMLineIndex};
  2937. var cand = evt.candidate;
  2938. // Edge emits an empty object for RTCIceCandidateComplete‥
  2939. var end = !cand || Object.keys(cand).length === 0;
  2940. if (end) {
  2941. // polyfill since RTCIceGatherer.state is not implemented in
  2942. // Edge 10547 yet.
  2943. if (iceGatherer.state === 'new' || iceGatherer.state === 'gathering') {
  2944. iceGatherer.state = 'completed';
  2945. }
  2946. } else {
  2947. if (iceGatherer.state === 'new') {
  2948. iceGatherer.state = 'gathering';
  2949. }
  2950. // RTCIceCandidate doesn't have a component, needs to be added
  2951. cand.component = 1;
  2952. // also the usernameFragment. TODO: update SDP to take both variants.
  2953. cand.ufrag = iceGatherer.getLocalParameters().usernameFragment;
  2954. var serializedCandidate = SDPUtils.writeCandidate(cand);
  2955. event.candidate = Object.assign(event.candidate,
  2956. SDPUtils.parseCandidate(serializedCandidate));
  2957. event.candidate.candidate = serializedCandidate;
  2958. event.candidate.toJSON = function() {
  2959. return {
  2960. candidate: event.candidate.candidate,
  2961. sdpMid: event.candidate.sdpMid,
  2962. sdpMLineIndex: event.candidate.sdpMLineIndex,
  2963. usernameFragment: event.candidate.usernameFragment
  2964. };
  2965. };
  2966. }
  2967. // update local description.
  2968. var sections = SDPUtils.getMediaSections(pc._localDescription.sdp);
  2969. if (!end) {
  2970. sections[event.candidate.sdpMLineIndex] +=
  2971. 'a=' + event.candidate.candidate + '\r\n';
  2972. } else {
  2973. sections[event.candidate.sdpMLineIndex] +=
  2974. 'a=end-of-candidates\r\n';
  2975. }
  2976. pc._localDescription.sdp =
  2977. SDPUtils.getDescription(pc._localDescription.sdp) +
  2978. sections.join('');
  2979. var complete = pc.transceivers.every(function(transceiver) {
  2980. return transceiver.iceGatherer &&
  2981. transceiver.iceGatherer.state === 'completed';
  2982. });
  2983. if (pc.iceGatheringState !== 'gathering') {
  2984. pc.iceGatheringState = 'gathering';
  2985. pc._emitGatheringStateChange();
  2986. }
  2987. // Emit candidate. Also emit null candidate when all gatherers are
  2988. // complete.
  2989. if (!end) {
  2990. pc._dispatchEvent('icecandidate', event);
  2991. }
  2992. if (complete) {
  2993. pc._dispatchEvent('icecandidate', new Event('icecandidate'));
  2994. pc.iceGatheringState = 'complete';
  2995. pc._emitGatheringStateChange();
  2996. }
  2997. };
  2998. // emit already gathered candidates.
  2999. window.setTimeout(function() {
  3000. bufferedCandidateEvents.forEach(function(e) {
  3001. iceGatherer.onlocalcandidate(e);
  3002. });
  3003. }, 0);
  3004. };
  3005. // Create ICE transport and DTLS transport.
  3006. RTCPeerConnection.prototype._createIceAndDtlsTransports = function() {
  3007. var pc = this;
  3008. var iceTransport = new window.RTCIceTransport(null);
  3009. iceTransport.onicestatechange = function() {
  3010. pc._updateIceConnectionState();
  3011. pc._updateConnectionState();
  3012. };
  3013. var dtlsTransport = new window.RTCDtlsTransport(iceTransport);
  3014. dtlsTransport.ondtlsstatechange = function() {
  3015. pc._updateConnectionState();
  3016. };
  3017. dtlsTransport.onerror = function() {
  3018. // onerror does not set state to failed by itself.
  3019. Object.defineProperty(dtlsTransport, 'state',
  3020. {value: 'failed', writable: true});
  3021. pc._updateConnectionState();
  3022. };
  3023. return {
  3024. iceTransport: iceTransport,
  3025. dtlsTransport: dtlsTransport
  3026. };
  3027. };
  3028. // Destroy ICE gatherer, ICE transport and DTLS transport.
  3029. // Without triggering the callbacks.
  3030. RTCPeerConnection.prototype._disposeIceAndDtlsTransports = function(
  3031. sdpMLineIndex) {
  3032. var iceGatherer = this.transceivers[sdpMLineIndex].iceGatherer;
  3033. if (iceGatherer) {
  3034. delete iceGatherer.onlocalcandidate;
  3035. delete this.transceivers[sdpMLineIndex].iceGatherer;
  3036. }
  3037. var iceTransport = this.transceivers[sdpMLineIndex].iceTransport;
  3038. if (iceTransport) {
  3039. delete iceTransport.onicestatechange;
  3040. delete this.transceivers[sdpMLineIndex].iceTransport;
  3041. }
  3042. var dtlsTransport = this.transceivers[sdpMLineIndex].dtlsTransport;
  3043. if (dtlsTransport) {
  3044. delete dtlsTransport.ondtlsstatechange;
  3045. delete dtlsTransport.onerror;
  3046. delete this.transceivers[sdpMLineIndex].dtlsTransport;
  3047. }
  3048. };
  3049. // Start the RTP Sender and Receiver for a transceiver.
  3050. RTCPeerConnection.prototype._transceive = function(transceiver,
  3051. send, recv) {
  3052. var params = getCommonCapabilities(transceiver.localCapabilities,
  3053. transceiver.remoteCapabilities);
  3054. if (send && transceiver.rtpSender) {
  3055. params.encodings = transceiver.sendEncodingParameters;
  3056. params.rtcp = {
  3057. cname: SDPUtils.localCName,
  3058. compound: transceiver.rtcpParameters.compound
  3059. };
  3060. if (transceiver.recvEncodingParameters.length) {
  3061. params.rtcp.ssrc = transceiver.recvEncodingParameters[0].ssrc;
  3062. }
  3063. transceiver.rtpSender.send(params);
  3064. }
  3065. if (recv && transceiver.rtpReceiver && params.codecs.length > 0) {
  3066. // remove RTX field in Edge 14942
  3067. if (transceiver.kind === 'video'
  3068. && transceiver.recvEncodingParameters
  3069. && edgeVersion < 15019) {
  3070. transceiver.recvEncodingParameters.forEach(function(p) {
  3071. delete p.rtx;
  3072. });
  3073. }
  3074. if (transceiver.recvEncodingParameters.length) {
  3075. params.encodings = transceiver.recvEncodingParameters;
  3076. } else {
  3077. params.encodings = [{}];
  3078. }
  3079. params.rtcp = {
  3080. compound: transceiver.rtcpParameters.compound
  3081. };
  3082. if (transceiver.rtcpParameters.cname) {
  3083. params.rtcp.cname = transceiver.rtcpParameters.cname;
  3084. }
  3085. if (transceiver.sendEncodingParameters.length) {
  3086. params.rtcp.ssrc = transceiver.sendEncodingParameters[0].ssrc;
  3087. }
  3088. transceiver.rtpReceiver.receive(params);
  3089. }
  3090. };
  3091. RTCPeerConnection.prototype.setLocalDescription = function(description) {
  3092. var pc = this;
  3093. // Note: pranswer is not supported.
  3094. if (['offer', 'answer'].indexOf(description.type) === -1) {
  3095. return Promise.reject(makeError('TypeError',
  3096. 'Unsupported type "' + description.type + '"'));
  3097. }
  3098. if (!isActionAllowedInSignalingState('setLocalDescription',
  3099. description.type, pc.signalingState) || pc._isClosed) {
  3100. return Promise.reject(makeError('InvalidStateError',
  3101. 'Can not set local ' + description.type +
  3102. ' in state ' + pc.signalingState));
  3103. }
  3104. var sections;
  3105. var sessionpart;
  3106. if (description.type === 'offer') {
  3107. // VERY limited support for SDP munging. Limited to:
  3108. // * changing the order of codecs
  3109. sections = SDPUtils.splitSections(description.sdp);
  3110. sessionpart = sections.shift();
  3111. sections.forEach(function(mediaSection, sdpMLineIndex) {
  3112. var caps = SDPUtils.parseRtpParameters(mediaSection);
  3113. pc.transceivers[sdpMLineIndex].localCapabilities = caps;
  3114. });
  3115. pc.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  3116. pc._gather(transceiver.mid, sdpMLineIndex);
  3117. });
  3118. } else if (description.type === 'answer') {
  3119. sections = SDPUtils.splitSections(pc._remoteDescription.sdp);
  3120. sessionpart = sections.shift();
  3121. var isIceLite = SDPUtils.matchPrefix(sessionpart,
  3122. 'a=ice-lite').length > 0;
  3123. sections.forEach(function(mediaSection, sdpMLineIndex) {
  3124. var transceiver = pc.transceivers[sdpMLineIndex];
  3125. var iceGatherer = transceiver.iceGatherer;
  3126. var iceTransport = transceiver.iceTransport;
  3127. var dtlsTransport = transceiver.dtlsTransport;
  3128. var localCapabilities = transceiver.localCapabilities;
  3129. var remoteCapabilities = transceiver.remoteCapabilities;
  3130. // treat bundle-only as not-rejected.
  3131. var rejected = SDPUtils.isRejected(mediaSection) &&
  3132. SDPUtils.matchPrefix(mediaSection, 'a=bundle-only').length === 0;
  3133. if (!rejected && !transceiver.rejected) {
  3134. var remoteIceParameters = SDPUtils.getIceParameters(
  3135. mediaSection, sessionpart);
  3136. var remoteDtlsParameters = SDPUtils.getDtlsParameters(
  3137. mediaSection, sessionpart);
  3138. if (isIceLite) {
  3139. remoteDtlsParameters.role = 'server';
  3140. }
  3141. if (!pc.usingBundle || sdpMLineIndex === 0) {
  3142. pc._gather(transceiver.mid, sdpMLineIndex);
  3143. if (iceTransport.state === 'new') {
  3144. iceTransport.start(iceGatherer, remoteIceParameters,
  3145. isIceLite ? 'controlling' : 'controlled');
  3146. }
  3147. if (dtlsTransport.state === 'new') {
  3148. dtlsTransport.start(remoteDtlsParameters);
  3149. }
  3150. }
  3151. // Calculate intersection of capabilities.
  3152. var params = getCommonCapabilities(localCapabilities,
  3153. remoteCapabilities);
  3154. // Start the RTCRtpSender. The RTCRtpReceiver for this
  3155. // transceiver has already been started in setRemoteDescription.
  3156. pc._transceive(transceiver,
  3157. params.codecs.length > 0,
  3158. false);
  3159. }
  3160. });
  3161. }
  3162. pc._localDescription = {
  3163. type: description.type,
  3164. sdp: description.sdp
  3165. };
  3166. if (description.type === 'offer') {
  3167. pc._updateSignalingState('have-local-offer');
  3168. } else {
  3169. pc._updateSignalingState('stable');
  3170. }
  3171. return Promise.resolve();
  3172. };
  3173. RTCPeerConnection.prototype.setRemoteDescription = function(description) {
  3174. var pc = this;
  3175. // Note: pranswer is not supported.
  3176. if (['offer', 'answer'].indexOf(description.type) === -1) {
  3177. return Promise.reject(makeError('TypeError',
  3178. 'Unsupported type "' + description.type + '"'));
  3179. }
  3180. if (!isActionAllowedInSignalingState('setRemoteDescription',
  3181. description.type, pc.signalingState) || pc._isClosed) {
  3182. return Promise.reject(makeError('InvalidStateError',
  3183. 'Can not set remote ' + description.type +
  3184. ' in state ' + pc.signalingState));
  3185. }
  3186. var streams = {};
  3187. pc.remoteStreams.forEach(function(stream) {
  3188. streams[stream.id] = stream;
  3189. });
  3190. var receiverList = [];
  3191. var sections = SDPUtils.splitSections(description.sdp);
  3192. var sessionpart = sections.shift();
  3193. var isIceLite = SDPUtils.matchPrefix(sessionpart,
  3194. 'a=ice-lite').length > 0;
  3195. var usingBundle = SDPUtils.matchPrefix(sessionpart,
  3196. 'a=group:BUNDLE ').length > 0;
  3197. pc.usingBundle = usingBundle;
  3198. var iceOptions = SDPUtils.matchPrefix(sessionpart,
  3199. 'a=ice-options:')[0];
  3200. if (iceOptions) {
  3201. pc.canTrickleIceCandidates = iceOptions.substr(14).split(' ')
  3202. .indexOf('trickle') >= 0;
  3203. } else {
  3204. pc.canTrickleIceCandidates = false;
  3205. }
  3206. sections.forEach(function(mediaSection, sdpMLineIndex) {
  3207. var lines = SDPUtils.splitLines(mediaSection);
  3208. var kind = SDPUtils.getKind(mediaSection);
  3209. // treat bundle-only as not-rejected.
  3210. var rejected = SDPUtils.isRejected(mediaSection) &&
  3211. SDPUtils.matchPrefix(mediaSection, 'a=bundle-only').length === 0;
  3212. var protocol = lines[0].substr(2).split(' ')[2];
  3213. var direction = SDPUtils.getDirection(mediaSection, sessionpart);
  3214. var remoteMsid = SDPUtils.parseMsid(mediaSection);
  3215. var mid = SDPUtils.getMid(mediaSection) || SDPUtils.generateIdentifier();
  3216. // Reject datachannels which are not implemented yet.
  3217. if (rejected || (kind === 'application' && (protocol === 'DTLS/SCTP' ||
  3218. protocol === 'UDP/DTLS/SCTP'))) {
  3219. // TODO: this is dangerous in the case where a non-rejected m-line
  3220. // becomes rejected.
  3221. pc.transceivers[sdpMLineIndex] = {
  3222. mid: mid,
  3223. kind: kind,
  3224. protocol: protocol,
  3225. rejected: true
  3226. };
  3227. return;
  3228. }
  3229. if (!rejected && pc.transceivers[sdpMLineIndex] &&
  3230. pc.transceivers[sdpMLineIndex].rejected) {
  3231. // recycle a rejected transceiver.
  3232. pc.transceivers[sdpMLineIndex] = pc._createTransceiver(kind, true);
  3233. }
  3234. var transceiver;
  3235. var iceGatherer;
  3236. var iceTransport;
  3237. var dtlsTransport;
  3238. var rtpReceiver;
  3239. var sendEncodingParameters;
  3240. var recvEncodingParameters;
  3241. var localCapabilities;
  3242. var track;
  3243. // FIXME: ensure the mediaSection has rtcp-mux set.
  3244. var remoteCapabilities = SDPUtils.parseRtpParameters(mediaSection);
  3245. var remoteIceParameters;
  3246. var remoteDtlsParameters;
  3247. if (!rejected) {
  3248. remoteIceParameters = SDPUtils.getIceParameters(mediaSection,
  3249. sessionpart);
  3250. remoteDtlsParameters = SDPUtils.getDtlsParameters(mediaSection,
  3251. sessionpart);
  3252. remoteDtlsParameters.role = 'client';
  3253. }
  3254. recvEncodingParameters =
  3255. SDPUtils.parseRtpEncodingParameters(mediaSection);
  3256. var rtcpParameters = SDPUtils.parseRtcpParameters(mediaSection);
  3257. var isComplete = SDPUtils.matchPrefix(mediaSection,
  3258. 'a=end-of-candidates', sessionpart).length > 0;
  3259. var cands = SDPUtils.matchPrefix(mediaSection, 'a=candidate:')
  3260. .map(function(cand) {
  3261. return SDPUtils.parseCandidate(cand);
  3262. })
  3263. .filter(function(cand) {
  3264. return cand.component === 1;
  3265. });
  3266. // Check if we can use BUNDLE and dispose transports.
  3267. if ((description.type === 'offer' || description.type === 'answer') &&
  3268. !rejected && usingBundle && sdpMLineIndex > 0 &&
  3269. pc.transceivers[sdpMLineIndex]) {
  3270. pc._disposeIceAndDtlsTransports(sdpMLineIndex);
  3271. pc.transceivers[sdpMLineIndex].iceGatherer =
  3272. pc.transceivers[0].iceGatherer;
  3273. pc.transceivers[sdpMLineIndex].iceTransport =
  3274. pc.transceivers[0].iceTransport;
  3275. pc.transceivers[sdpMLineIndex].dtlsTransport =
  3276. pc.transceivers[0].dtlsTransport;
  3277. if (pc.transceivers[sdpMLineIndex].rtpSender) {
  3278. pc.transceivers[sdpMLineIndex].rtpSender.setTransport(
  3279. pc.transceivers[0].dtlsTransport);
  3280. }
  3281. if (pc.transceivers[sdpMLineIndex].rtpReceiver) {
  3282. pc.transceivers[sdpMLineIndex].rtpReceiver.setTransport(
  3283. pc.transceivers[0].dtlsTransport);
  3284. }
  3285. }
  3286. if (description.type === 'offer' && !rejected) {
  3287. transceiver = pc.transceivers[sdpMLineIndex] ||
  3288. pc._createTransceiver(kind);
  3289. transceiver.mid = mid;
  3290. if (!transceiver.iceGatherer) {
  3291. transceiver.iceGatherer = pc._createIceGatherer(sdpMLineIndex,
  3292. usingBundle);
  3293. }
  3294. if (cands.length && transceiver.iceTransport.state === 'new') {
  3295. if (isComplete && (!usingBundle || sdpMLineIndex === 0)) {
  3296. transceiver.iceTransport.setRemoteCandidates(cands);
  3297. } else {
  3298. cands.forEach(function(candidate) {
  3299. maybeAddCandidate(transceiver.iceTransport, candidate);
  3300. });
  3301. }
  3302. }
  3303. localCapabilities = window.RTCRtpReceiver.getCapabilities(kind);
  3304. // filter RTX until additional stuff needed for RTX is implemented
  3305. // in adapter.js
  3306. if (edgeVersion < 15019) {
  3307. localCapabilities.codecs = localCapabilities.codecs.filter(
  3308. function(codec) {
  3309. return codec.name !== 'rtx';
  3310. });
  3311. }
  3312. sendEncodingParameters = transceiver.sendEncodingParameters || [{
  3313. ssrc: (2 * sdpMLineIndex + 2) * 1001
  3314. }];
  3315. // TODO: rewrite to use http://w3c.github.io/webrtc-pc/#set-associated-remote-streams
  3316. var isNewTrack = false;
  3317. if (direction === 'sendrecv' || direction === 'sendonly') {
  3318. isNewTrack = !transceiver.rtpReceiver;
  3319. rtpReceiver = transceiver.rtpReceiver ||
  3320. new window.RTCRtpReceiver(transceiver.dtlsTransport, kind);
  3321. if (isNewTrack) {
  3322. var stream;
  3323. track = rtpReceiver.track;
  3324. // FIXME: does not work with Plan B.
  3325. if (remoteMsid && remoteMsid.stream === '-') {
  3326. // no-op. a stream id of '-' means: no associated stream.
  3327. } else if (remoteMsid) {
  3328. if (!streams[remoteMsid.stream]) {
  3329. streams[remoteMsid.stream] = new window.MediaStream();
  3330. Object.defineProperty(streams[remoteMsid.stream], 'id', {
  3331. get: function() {
  3332. return remoteMsid.stream;
  3333. }
  3334. });
  3335. }
  3336. Object.defineProperty(track, 'id', {
  3337. get: function() {
  3338. return remoteMsid.track;
  3339. }
  3340. });
  3341. stream = streams[remoteMsid.stream];
  3342. } else {
  3343. if (!streams.default) {
  3344. streams.default = new window.MediaStream();
  3345. }
  3346. stream = streams.default;
  3347. }
  3348. if (stream) {
  3349. addTrackToStreamAndFireEvent(track, stream);
  3350. transceiver.associatedRemoteMediaStreams.push(stream);
  3351. }
  3352. receiverList.push([track, rtpReceiver, stream]);
  3353. }
  3354. } else if (transceiver.rtpReceiver && transceiver.rtpReceiver.track) {
  3355. transceiver.associatedRemoteMediaStreams.forEach(function(s) {
  3356. var nativeTrack = s.getTracks().find(function(t) {
  3357. return t.id === transceiver.rtpReceiver.track.id;
  3358. });
  3359. if (nativeTrack) {
  3360. removeTrackFromStreamAndFireEvent(nativeTrack, s);
  3361. }
  3362. });
  3363. transceiver.associatedRemoteMediaStreams = [];
  3364. }
  3365. transceiver.localCapabilities = localCapabilities;
  3366. transceiver.remoteCapabilities = remoteCapabilities;
  3367. transceiver.rtpReceiver = rtpReceiver;
  3368. transceiver.rtcpParameters = rtcpParameters;
  3369. transceiver.sendEncodingParameters = sendEncodingParameters;
  3370. transceiver.recvEncodingParameters = recvEncodingParameters;
  3371. // Start the RTCRtpReceiver now. The RTPSender is started in
  3372. // setLocalDescription.
  3373. pc._transceive(pc.transceivers[sdpMLineIndex],
  3374. false,
  3375. isNewTrack);
  3376. } else if (description.type === 'answer' && !rejected) {
  3377. transceiver = pc.transceivers[sdpMLineIndex];
  3378. iceGatherer = transceiver.iceGatherer;
  3379. iceTransport = transceiver.iceTransport;
  3380. dtlsTransport = transceiver.dtlsTransport;
  3381. rtpReceiver = transceiver.rtpReceiver;
  3382. sendEncodingParameters = transceiver.sendEncodingParameters;
  3383. localCapabilities = transceiver.localCapabilities;
  3384. pc.transceivers[sdpMLineIndex].recvEncodingParameters =
  3385. recvEncodingParameters;
  3386. pc.transceivers[sdpMLineIndex].remoteCapabilities =
  3387. remoteCapabilities;
  3388. pc.transceivers[sdpMLineIndex].rtcpParameters = rtcpParameters;
  3389. if (cands.length && iceTransport.state === 'new') {
  3390. if ((isIceLite || isComplete) &&
  3391. (!usingBundle || sdpMLineIndex === 0)) {
  3392. iceTransport.setRemoteCandidates(cands);
  3393. } else {
  3394. cands.forEach(function(candidate) {
  3395. maybeAddCandidate(transceiver.iceTransport, candidate);
  3396. });
  3397. }
  3398. }
  3399. if (!usingBundle || sdpMLineIndex === 0) {
  3400. if (iceTransport.state === 'new') {
  3401. iceTransport.start(iceGatherer, remoteIceParameters,
  3402. 'controlling');
  3403. }
  3404. if (dtlsTransport.state === 'new') {
  3405. dtlsTransport.start(remoteDtlsParameters);
  3406. }
  3407. }
  3408. // If the offer contained RTX but the answer did not,
  3409. // remove RTX from sendEncodingParameters.
  3410. var commonCapabilities = getCommonCapabilities(
  3411. transceiver.localCapabilities,
  3412. transceiver.remoteCapabilities);
  3413. var hasRtx = commonCapabilities.codecs.filter(function(c) {
  3414. return c.name.toLowerCase() === 'rtx';
  3415. }).length;
  3416. if (!hasRtx && transceiver.sendEncodingParameters[0].rtx) {
  3417. delete transceiver.sendEncodingParameters[0].rtx;
  3418. }
  3419. pc._transceive(transceiver,
  3420. direction === 'sendrecv' || direction === 'recvonly',
  3421. direction === 'sendrecv' || direction === 'sendonly');
  3422. // TODO: rewrite to use http://w3c.github.io/webrtc-pc/#set-associated-remote-streams
  3423. if (rtpReceiver &&
  3424. (direction === 'sendrecv' || direction === 'sendonly')) {
  3425. track = rtpReceiver.track;
  3426. if (remoteMsid) {
  3427. if (!streams[remoteMsid.stream]) {
  3428. streams[remoteMsid.stream] = new window.MediaStream();
  3429. }
  3430. addTrackToStreamAndFireEvent(track, streams[remoteMsid.stream]);
  3431. receiverList.push([track, rtpReceiver, streams[remoteMsid.stream]]);
  3432. } else {
  3433. if (!streams.default) {
  3434. streams.default = new window.MediaStream();
  3435. }
  3436. addTrackToStreamAndFireEvent(track, streams.default);
  3437. receiverList.push([track, rtpReceiver, streams.default]);
  3438. }
  3439. } else {
  3440. // FIXME: actually the receiver should be created later.
  3441. delete transceiver.rtpReceiver;
  3442. }
  3443. }
  3444. });
  3445. if (pc._dtlsRole === undefined) {
  3446. pc._dtlsRole = description.type === 'offer' ? 'active' : 'passive';
  3447. }
  3448. pc._remoteDescription = {
  3449. type: description.type,
  3450. sdp: description.sdp
  3451. };
  3452. if (description.type === 'offer') {
  3453. pc._updateSignalingState('have-remote-offer');
  3454. } else {
  3455. pc._updateSignalingState('stable');
  3456. }
  3457. Object.keys(streams).forEach(function(sid) {
  3458. var stream = streams[sid];
  3459. if (stream.getTracks().length) {
  3460. if (pc.remoteStreams.indexOf(stream) === -1) {
  3461. pc.remoteStreams.push(stream);
  3462. var event = new Event('addstream');
  3463. event.stream = stream;
  3464. window.setTimeout(function() {
  3465. pc._dispatchEvent('addstream', event);
  3466. });
  3467. }
  3468. receiverList.forEach(function(item) {
  3469. var track = item[0];
  3470. var receiver = item[1];
  3471. if (stream.id !== item[2].id) {
  3472. return;
  3473. }
  3474. fireAddTrack(pc, track, receiver, [stream]);
  3475. });
  3476. }
  3477. });
  3478. receiverList.forEach(function(item) {
  3479. if (item[2]) {
  3480. return;
  3481. }
  3482. fireAddTrack(pc, item[0], item[1], []);
  3483. });
  3484. // check whether addIceCandidate({}) was called within four seconds after
  3485. // setRemoteDescription.
  3486. window.setTimeout(function() {
  3487. if (!(pc && pc.transceivers)) {
  3488. return;
  3489. }
  3490. pc.transceivers.forEach(function(transceiver) {
  3491. if (transceiver.iceTransport &&
  3492. transceiver.iceTransport.state === 'new' &&
  3493. transceiver.iceTransport.getRemoteCandidates().length > 0) {
  3494. console.warn('Timeout for addRemoteCandidate. Consider sending ' +
  3495. 'an end-of-candidates notification');
  3496. transceiver.iceTransport.addRemoteCandidate({});
  3497. }
  3498. });
  3499. }, 4000);
  3500. return Promise.resolve();
  3501. };
  3502. RTCPeerConnection.prototype.close = function() {
  3503. this.transceivers.forEach(function(transceiver) {
  3504. /* not yet
  3505. if (transceiver.iceGatherer) {
  3506. transceiver.iceGatherer.close();
  3507. }
  3508. */
  3509. if (transceiver.iceTransport) {
  3510. transceiver.iceTransport.stop();
  3511. }
  3512. if (transceiver.dtlsTransport) {
  3513. transceiver.dtlsTransport.stop();
  3514. }
  3515. if (transceiver.rtpSender) {
  3516. transceiver.rtpSender.stop();
  3517. }
  3518. if (transceiver.rtpReceiver) {
  3519. transceiver.rtpReceiver.stop();
  3520. }
  3521. });
  3522. // FIXME: clean up tracks, local streams, remote streams, etc
  3523. this._isClosed = true;
  3524. this._updateSignalingState('closed');
  3525. };
  3526. // Update the signaling state.
  3527. RTCPeerConnection.prototype._updateSignalingState = function(newState) {
  3528. this.signalingState = newState;
  3529. var event = new Event('signalingstatechange');
  3530. this._dispatchEvent('signalingstatechange', event);
  3531. };
  3532. // Determine whether to fire the negotiationneeded event.
  3533. RTCPeerConnection.prototype._maybeFireNegotiationNeeded = function() {
  3534. var pc = this;
  3535. if (this.signalingState !== 'stable' || this.needNegotiation === true) {
  3536. return;
  3537. }
  3538. this.needNegotiation = true;
  3539. window.setTimeout(function() {
  3540. if (pc.needNegotiation) {
  3541. pc.needNegotiation = false;
  3542. var event = new Event('negotiationneeded');
  3543. pc._dispatchEvent('negotiationneeded', event);
  3544. }
  3545. }, 0);
  3546. };
  3547. // Update the ice connection state.
  3548. RTCPeerConnection.prototype._updateIceConnectionState = function() {
  3549. var newState;
  3550. var states = {
  3551. 'new': 0,
  3552. closed: 0,
  3553. checking: 0,
  3554. connected: 0,
  3555. completed: 0,
  3556. disconnected: 0,
  3557. failed: 0
  3558. };
  3559. this.transceivers.forEach(function(transceiver) {
  3560. if (transceiver.iceTransport && !transceiver.rejected) {
  3561. states[transceiver.iceTransport.state]++;
  3562. }
  3563. });
  3564. newState = 'new';
  3565. if (states.failed > 0) {
  3566. newState = 'failed';
  3567. } else if (states.checking > 0) {
  3568. newState = 'checking';
  3569. } else if (states.disconnected > 0) {
  3570. newState = 'disconnected';
  3571. } else if (states.new > 0) {
  3572. newState = 'new';
  3573. } else if (states.connected > 0) {
  3574. newState = 'connected';
  3575. } else if (states.completed > 0) {
  3576. newState = 'completed';
  3577. }
  3578. if (newState !== this.iceConnectionState) {
  3579. this.iceConnectionState = newState;
  3580. var event = new Event('iceconnectionstatechange');
  3581. this._dispatchEvent('iceconnectionstatechange', event);
  3582. }
  3583. };
  3584. // Update the connection state.
  3585. RTCPeerConnection.prototype._updateConnectionState = function() {
  3586. var newState;
  3587. var states = {
  3588. 'new': 0,
  3589. closed: 0,
  3590. connecting: 0,
  3591. connected: 0,
  3592. completed: 0,
  3593. disconnected: 0,
  3594. failed: 0
  3595. };
  3596. this.transceivers.forEach(function(transceiver) {
  3597. if (transceiver.iceTransport && transceiver.dtlsTransport &&
  3598. !transceiver.rejected) {
  3599. states[transceiver.iceTransport.state]++;
  3600. states[transceiver.dtlsTransport.state]++;
  3601. }
  3602. });
  3603. // ICETransport.completed and connected are the same for this purpose.
  3604. states.connected += states.completed;
  3605. newState = 'new';
  3606. if (states.failed > 0) {
  3607. newState = 'failed';
  3608. } else if (states.connecting > 0) {
  3609. newState = 'connecting';
  3610. } else if (states.disconnected > 0) {
  3611. newState = 'disconnected';
  3612. } else if (states.new > 0) {
  3613. newState = 'new';
  3614. } else if (states.connected > 0) {
  3615. newState = 'connected';
  3616. }
  3617. if (newState !== this.connectionState) {
  3618. this.connectionState = newState;
  3619. var event = new Event('connectionstatechange');
  3620. this._dispatchEvent('connectionstatechange', event);
  3621. }
  3622. };
  3623. RTCPeerConnection.prototype.createOffer = function() {
  3624. var pc = this;
  3625. if (pc._isClosed) {
  3626. return Promise.reject(makeError('InvalidStateError',
  3627. 'Can not call createOffer after close'));
  3628. }
  3629. var numAudioTracks = pc.transceivers.filter(function(t) {
  3630. return t.kind === 'audio';
  3631. }).length;
  3632. var numVideoTracks = pc.transceivers.filter(function(t) {
  3633. return t.kind === 'video';
  3634. }).length;
  3635. // Determine number of audio and video tracks we need to send/recv.
  3636. var offerOptions = arguments[0];
  3637. if (offerOptions) {
  3638. // Reject Chrome legacy constraints.
  3639. if (offerOptions.mandatory || offerOptions.optional) {
  3640. throw new TypeError(
  3641. 'Legacy mandatory/optional constraints not supported.');
  3642. }
  3643. if (offerOptions.offerToReceiveAudio !== undefined) {
  3644. if (offerOptions.offerToReceiveAudio === true) {
  3645. numAudioTracks = 1;
  3646. } else if (offerOptions.offerToReceiveAudio === false) {
  3647. numAudioTracks = 0;
  3648. } else {
  3649. numAudioTracks = offerOptions.offerToReceiveAudio;
  3650. }
  3651. }
  3652. if (offerOptions.offerToReceiveVideo !== undefined) {
  3653. if (offerOptions.offerToReceiveVideo === true) {
  3654. numVideoTracks = 1;
  3655. } else if (offerOptions.offerToReceiveVideo === false) {
  3656. numVideoTracks = 0;
  3657. } else {
  3658. numVideoTracks = offerOptions.offerToReceiveVideo;
  3659. }
  3660. }
  3661. }
  3662. pc.transceivers.forEach(function(transceiver) {
  3663. if (transceiver.kind === 'audio') {
  3664. numAudioTracks--;
  3665. if (numAudioTracks < 0) {
  3666. transceiver.wantReceive = false;
  3667. }
  3668. } else if (transceiver.kind === 'video') {
  3669. numVideoTracks--;
  3670. if (numVideoTracks < 0) {
  3671. transceiver.wantReceive = false;
  3672. }
  3673. }
  3674. });
  3675. // Create M-lines for recvonly streams.
  3676. while (numAudioTracks > 0 || numVideoTracks > 0) {
  3677. if (numAudioTracks > 0) {
  3678. pc._createTransceiver('audio');
  3679. numAudioTracks--;
  3680. }
  3681. if (numVideoTracks > 0) {
  3682. pc._createTransceiver('video');
  3683. numVideoTracks--;
  3684. }
  3685. }
  3686. var sdp = SDPUtils.writeSessionBoilerplate(pc._sdpSessionId,
  3687. pc._sdpSessionVersion++);
  3688. pc.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  3689. // For each track, create an ice gatherer, ice transport,
  3690. // dtls transport, potentially rtpsender and rtpreceiver.
  3691. var track = transceiver.track;
  3692. var kind = transceiver.kind;
  3693. var mid = transceiver.mid || SDPUtils.generateIdentifier();
  3694. transceiver.mid = mid;
  3695. if (!transceiver.iceGatherer) {
  3696. transceiver.iceGatherer = pc._createIceGatherer(sdpMLineIndex,
  3697. pc.usingBundle);
  3698. }
  3699. var localCapabilities = window.RTCRtpSender.getCapabilities(kind);
  3700. // filter RTX until additional stuff needed for RTX is implemented
  3701. // in adapter.js
  3702. if (edgeVersion < 15019) {
  3703. localCapabilities.codecs = localCapabilities.codecs.filter(
  3704. function(codec) {
  3705. return codec.name !== 'rtx';
  3706. });
  3707. }
  3708. localCapabilities.codecs.forEach(function(codec) {
  3709. // work around https://bugs.chromium.org/p/webrtc/issues/detail?id=6552
  3710. // by adding level-asymmetry-allowed=1
  3711. if (codec.name === 'H264' &&
  3712. codec.parameters['level-asymmetry-allowed'] === undefined) {
  3713. codec.parameters['level-asymmetry-allowed'] = '1';
  3714. }
  3715. // for subsequent offers, we might have to re-use the payload
  3716. // type of the last offer.
  3717. if (transceiver.remoteCapabilities &&
  3718. transceiver.remoteCapabilities.codecs) {
  3719. transceiver.remoteCapabilities.codecs.forEach(function(remoteCodec) {
  3720. if (codec.name.toLowerCase() === remoteCodec.name.toLowerCase() &&
  3721. codec.clockRate === remoteCodec.clockRate) {
  3722. codec.preferredPayloadType = remoteCodec.payloadType;
  3723. }
  3724. });
  3725. }
  3726. });
  3727. localCapabilities.headerExtensions.forEach(function(hdrExt) {
  3728. var remoteExtensions = transceiver.remoteCapabilities &&
  3729. transceiver.remoteCapabilities.headerExtensions || [];
  3730. remoteExtensions.forEach(function(rHdrExt) {
  3731. if (hdrExt.uri === rHdrExt.uri) {
  3732. hdrExt.id = rHdrExt.id;
  3733. }
  3734. });
  3735. });
  3736. // generate an ssrc now, to be used later in rtpSender.send
  3737. var sendEncodingParameters = transceiver.sendEncodingParameters || [{
  3738. ssrc: (2 * sdpMLineIndex + 1) * 1001
  3739. }];
  3740. if (track) {
  3741. // add RTX
  3742. if (edgeVersion >= 15019 && kind === 'video' &&
  3743. !sendEncodingParameters[0].rtx) {
  3744. sendEncodingParameters[0].rtx = {
  3745. ssrc: sendEncodingParameters[0].ssrc + 1
  3746. };
  3747. }
  3748. }
  3749. if (transceiver.wantReceive) {
  3750. transceiver.rtpReceiver = new window.RTCRtpReceiver(
  3751. transceiver.dtlsTransport, kind);
  3752. }
  3753. transceiver.localCapabilities = localCapabilities;
  3754. transceiver.sendEncodingParameters = sendEncodingParameters;
  3755. });
  3756. // always offer BUNDLE and dispose on return if not supported.
  3757. if (pc._config.bundlePolicy !== 'max-compat') {
  3758. sdp += 'a=group:BUNDLE ' + pc.transceivers.map(function(t) {
  3759. return t.mid;
  3760. }).join(' ') + '\r\n';
  3761. }
  3762. sdp += 'a=ice-options:trickle\r\n';
  3763. pc.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  3764. sdp += writeMediaSection(transceiver, transceiver.localCapabilities,
  3765. 'offer', transceiver.stream, pc._dtlsRole);
  3766. sdp += 'a=rtcp-rsize\r\n';
  3767. if (transceiver.iceGatherer && pc.iceGatheringState !== 'new' &&
  3768. (sdpMLineIndex === 0 || !pc.usingBundle)) {
  3769. transceiver.iceGatherer.getLocalCandidates().forEach(function(cand) {
  3770. cand.component = 1;
  3771. sdp += 'a=' + SDPUtils.writeCandidate(cand) + '\r\n';
  3772. });
  3773. if (transceiver.iceGatherer.state === 'completed') {
  3774. sdp += 'a=end-of-candidates\r\n';
  3775. }
  3776. }
  3777. });
  3778. var desc = new window.RTCSessionDescription({
  3779. type: 'offer',
  3780. sdp: sdp
  3781. });
  3782. return Promise.resolve(desc);
  3783. };
  3784. RTCPeerConnection.prototype.createAnswer = function() {
  3785. var pc = this;
  3786. if (pc._isClosed) {
  3787. return Promise.reject(makeError('InvalidStateError',
  3788. 'Can not call createAnswer after close'));
  3789. }
  3790. if (!(pc.signalingState === 'have-remote-offer' ||
  3791. pc.signalingState === 'have-local-pranswer')) {
  3792. return Promise.reject(makeError('InvalidStateError',
  3793. 'Can not call createAnswer in signalingState ' + pc.signalingState));
  3794. }
  3795. var sdp = SDPUtils.writeSessionBoilerplate(pc._sdpSessionId,
  3796. pc._sdpSessionVersion++);
  3797. if (pc.usingBundle) {
  3798. sdp += 'a=group:BUNDLE ' + pc.transceivers.map(function(t) {
  3799. return t.mid;
  3800. }).join(' ') + '\r\n';
  3801. }
  3802. sdp += 'a=ice-options:trickle\r\n';
  3803. var mediaSectionsInOffer = SDPUtils.getMediaSections(
  3804. pc._remoteDescription.sdp).length;
  3805. pc.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  3806. if (sdpMLineIndex + 1 > mediaSectionsInOffer) {
  3807. return;
  3808. }
  3809. if (transceiver.rejected) {
  3810. if (transceiver.kind === 'application') {
  3811. if (transceiver.protocol === 'DTLS/SCTP') { // legacy fmt
  3812. sdp += 'm=application 0 DTLS/SCTP 5000\r\n';
  3813. } else {
  3814. sdp += 'm=application 0 ' + transceiver.protocol +
  3815. ' webrtc-datachannel\r\n';
  3816. }
  3817. } else if (transceiver.kind === 'audio') {
  3818. sdp += 'm=audio 0 UDP/TLS/RTP/SAVPF 0\r\n' +
  3819. 'a=rtpmap:0 PCMU/8000\r\n';
  3820. } else if (transceiver.kind === 'video') {
  3821. sdp += 'm=video 0 UDP/TLS/RTP/SAVPF 120\r\n' +
  3822. 'a=rtpmap:120 VP8/90000\r\n';
  3823. }
  3824. sdp += 'c=IN IP4 0.0.0.0\r\n' +
  3825. 'a=inactive\r\n' +
  3826. 'a=mid:' + transceiver.mid + '\r\n';
  3827. return;
  3828. }
  3829. // FIXME: look at direction.
  3830. if (transceiver.stream) {
  3831. var localTrack;
  3832. if (transceiver.kind === 'audio') {
  3833. localTrack = transceiver.stream.getAudioTracks()[0];
  3834. } else if (transceiver.kind === 'video') {
  3835. localTrack = transceiver.stream.getVideoTracks()[0];
  3836. }
  3837. if (localTrack) {
  3838. // add RTX
  3839. if (edgeVersion >= 15019 && transceiver.kind === 'video' &&
  3840. !transceiver.sendEncodingParameters[0].rtx) {
  3841. transceiver.sendEncodingParameters[0].rtx = {
  3842. ssrc: transceiver.sendEncodingParameters[0].ssrc + 1
  3843. };
  3844. }
  3845. }
  3846. }
  3847. // Calculate intersection of capabilities.
  3848. var commonCapabilities = getCommonCapabilities(
  3849. transceiver.localCapabilities,
  3850. transceiver.remoteCapabilities);
  3851. var hasRtx = commonCapabilities.codecs.filter(function(c) {
  3852. return c.name.toLowerCase() === 'rtx';
  3853. }).length;
  3854. if (!hasRtx && transceiver.sendEncodingParameters[0].rtx) {
  3855. delete transceiver.sendEncodingParameters[0].rtx;
  3856. }
  3857. sdp += writeMediaSection(transceiver, commonCapabilities,
  3858. 'answer', transceiver.stream, pc._dtlsRole);
  3859. if (transceiver.rtcpParameters &&
  3860. transceiver.rtcpParameters.reducedSize) {
  3861. sdp += 'a=rtcp-rsize\r\n';
  3862. }
  3863. });
  3864. var desc = new window.RTCSessionDescription({
  3865. type: 'answer',
  3866. sdp: sdp
  3867. });
  3868. return Promise.resolve(desc);
  3869. };
  3870. RTCPeerConnection.prototype.addIceCandidate = function(candidate) {
  3871. var pc = this;
  3872. var sections;
  3873. if (candidate && !(candidate.sdpMLineIndex !== undefined ||
  3874. candidate.sdpMid)) {
  3875. return Promise.reject(new TypeError('sdpMLineIndex or sdpMid required'));
  3876. }
  3877. // TODO: needs to go into ops queue.
  3878. return new Promise(function(resolve, reject) {
  3879. if (!pc._remoteDescription) {
  3880. return reject(makeError('InvalidStateError',
  3881. 'Can not add ICE candidate without a remote description'));
  3882. } else if (!candidate || candidate.candidate === '') {
  3883. for (var j = 0; j < pc.transceivers.length; j++) {
  3884. if (pc.transceivers[j].rejected) {
  3885. continue;
  3886. }
  3887. pc.transceivers[j].iceTransport.addRemoteCandidate({});
  3888. sections = SDPUtils.getMediaSections(pc._remoteDescription.sdp);
  3889. sections[j] += 'a=end-of-candidates\r\n';
  3890. pc._remoteDescription.sdp =
  3891. SDPUtils.getDescription(pc._remoteDescription.sdp) +
  3892. sections.join('');
  3893. if (pc.usingBundle) {
  3894. break;
  3895. }
  3896. }
  3897. } else {
  3898. var sdpMLineIndex = candidate.sdpMLineIndex;
  3899. if (candidate.sdpMid) {
  3900. for (var i = 0; i < pc.transceivers.length; i++) {
  3901. if (pc.transceivers[i].mid === candidate.sdpMid) {
  3902. sdpMLineIndex = i;
  3903. break;
  3904. }
  3905. }
  3906. }
  3907. var transceiver = pc.transceivers[sdpMLineIndex];
  3908. if (transceiver) {
  3909. if (transceiver.rejected) {
  3910. return resolve();
  3911. }
  3912. var cand = Object.keys(candidate.candidate).length > 0 ?
  3913. SDPUtils.parseCandidate(candidate.candidate) : {};
  3914. // Ignore Chrome's invalid candidates since Edge does not like them.
  3915. if (cand.protocol === 'tcp' && (cand.port === 0 || cand.port === 9)) {
  3916. return resolve();
  3917. }
  3918. // Ignore RTCP candidates, we assume RTCP-MUX.
  3919. if (cand.component && cand.component !== 1) {
  3920. return resolve();
  3921. }
  3922. // when using bundle, avoid adding candidates to the wrong
  3923. // ice transport. And avoid adding candidates added in the SDP.
  3924. if (sdpMLineIndex === 0 || (sdpMLineIndex > 0 &&
  3925. transceiver.iceTransport !== pc.transceivers[0].iceTransport)) {
  3926. if (!maybeAddCandidate(transceiver.iceTransport, cand)) {
  3927. return reject(makeError('OperationError',
  3928. 'Can not add ICE candidate'));
  3929. }
  3930. }
  3931. // update the remoteDescription.
  3932. var candidateString = candidate.candidate.trim();
  3933. if (candidateString.indexOf('a=') === 0) {
  3934. candidateString = candidateString.substr(2);
  3935. }
  3936. sections = SDPUtils.getMediaSections(pc._remoteDescription.sdp);
  3937. sections[sdpMLineIndex] += 'a=' +
  3938. (cand.type ? candidateString : 'end-of-candidates')
  3939. + '\r\n';
  3940. pc._remoteDescription.sdp =
  3941. SDPUtils.getDescription(pc._remoteDescription.sdp) +
  3942. sections.join('');
  3943. } else {
  3944. return reject(makeError('OperationError',
  3945. 'Can not add ICE candidate'));
  3946. }
  3947. }
  3948. resolve();
  3949. });
  3950. };
  3951. RTCPeerConnection.prototype.getStats = function(selector) {
  3952. if (selector && selector instanceof window.MediaStreamTrack) {
  3953. var senderOrReceiver = null;
  3954. this.transceivers.forEach(function(transceiver) {
  3955. if (transceiver.rtpSender &&
  3956. transceiver.rtpSender.track === selector) {
  3957. senderOrReceiver = transceiver.rtpSender;
  3958. } else if (transceiver.rtpReceiver &&
  3959. transceiver.rtpReceiver.track === selector) {
  3960. senderOrReceiver = transceiver.rtpReceiver;
  3961. }
  3962. });
  3963. if (!senderOrReceiver) {
  3964. throw makeError('InvalidAccessError', 'Invalid selector.');
  3965. }
  3966. return senderOrReceiver.getStats();
  3967. }
  3968. var promises = [];
  3969. this.transceivers.forEach(function(transceiver) {
  3970. ['rtpSender', 'rtpReceiver', 'iceGatherer', 'iceTransport',
  3971. 'dtlsTransport'].forEach(function(method) {
  3972. if (transceiver[method]) {
  3973. promises.push(transceiver[method].getStats());
  3974. }
  3975. });
  3976. });
  3977. return Promise.all(promises).then(function(allStats) {
  3978. var results = new Map();
  3979. allStats.forEach(function(stats) {
  3980. stats.forEach(function(stat) {
  3981. results.set(stat.id, stat);
  3982. });
  3983. });
  3984. return results;
  3985. });
  3986. };
  3987. // fix low-level stat names and return Map instead of object.
  3988. var ortcObjects = ['RTCRtpSender', 'RTCRtpReceiver', 'RTCIceGatherer',
  3989. 'RTCIceTransport', 'RTCDtlsTransport'];
  3990. ortcObjects.forEach(function(ortcObjectName) {
  3991. var obj = window[ortcObjectName];
  3992. if (obj && obj.prototype && obj.prototype.getStats) {
  3993. var nativeGetstats = obj.prototype.getStats;
  3994. obj.prototype.getStats = function() {
  3995. return nativeGetstats.apply(this)
  3996. .then(function(nativeStats) {
  3997. var mapStats = new Map();
  3998. Object.keys(nativeStats).forEach(function(id) {
  3999. nativeStats[id].type = fixStatsType(nativeStats[id]);
  4000. mapStats.set(id, nativeStats[id]);
  4001. });
  4002. return mapStats;
  4003. });
  4004. };
  4005. }
  4006. });
  4007. // legacy callback shims. Should be moved to adapter.js some days.
  4008. var methods = ['createOffer', 'createAnswer'];
  4009. methods.forEach(function(method) {
  4010. var nativeMethod = RTCPeerConnection.prototype[method];
  4011. RTCPeerConnection.prototype[method] = function() {
  4012. var args = arguments;
  4013. if (typeof args[0] === 'function' ||
  4014. typeof args[1] === 'function') { // legacy
  4015. return nativeMethod.apply(this, [arguments[2]])
  4016. .then(function(description) {
  4017. if (typeof args[0] === 'function') {
  4018. args[0].apply(null, [description]);
  4019. }
  4020. }, function(error) {
  4021. if (typeof args[1] === 'function') {
  4022. args[1].apply(null, [error]);
  4023. }
  4024. });
  4025. }
  4026. return nativeMethod.apply(this, arguments);
  4027. };
  4028. });
  4029. methods = ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'];
  4030. methods.forEach(function(method) {
  4031. var nativeMethod = RTCPeerConnection.prototype[method];
  4032. RTCPeerConnection.prototype[method] = function() {
  4033. var args = arguments;
  4034. if (typeof args[1] === 'function' ||
  4035. typeof args[2] === 'function') { // legacy
  4036. return nativeMethod.apply(this, arguments)
  4037. .then(function() {
  4038. if (typeof args[1] === 'function') {
  4039. args[1].apply(null);
  4040. }
  4041. }, function(error) {
  4042. if (typeof args[2] === 'function') {
  4043. args[2].apply(null, [error]);
  4044. }
  4045. });
  4046. }
  4047. return nativeMethod.apply(this, arguments);
  4048. };
  4049. });
  4050. // getStats is special. It doesn't have a spec legacy method yet we support
  4051. // getStats(something, cb) without error callbacks.
  4052. ['getStats'].forEach(function(method) {
  4053. var nativeMethod = RTCPeerConnection.prototype[method];
  4054. RTCPeerConnection.prototype[method] = function() {
  4055. var args = arguments;
  4056. if (typeof args[1] === 'function') {
  4057. return nativeMethod.apply(this, arguments)
  4058. .then(function() {
  4059. if (typeof args[1] === 'function') {
  4060. args[1].apply(null);
  4061. }
  4062. });
  4063. }
  4064. return nativeMethod.apply(this, arguments);
  4065. };
  4066. });
  4067. return RTCPeerConnection;
  4068. };
  4069. },{"sdp":17}],17:[function(require,module,exports){
  4070. /* eslint-env node */
  4071. 'use strict';
  4072. // SDP helpers.
  4073. var SDPUtils = {};
  4074. // Generate an alphanumeric identifier for cname or mids.
  4075. // TODO: use UUIDs instead? https://gist.github.com/jed/982883
  4076. SDPUtils.generateIdentifier = function() {
  4077. return Math.random().toString(36).substr(2, 10);
  4078. };
  4079. // The RTCP CNAME used by all peerconnections from the same JS.
  4080. SDPUtils.localCName = SDPUtils.generateIdentifier();
  4081. // Splits SDP into lines, dealing with both CRLF and LF.
  4082. SDPUtils.splitLines = function(blob) {
  4083. return blob.trim().split('\n').map(function(line) {
  4084. return line.trim();
  4085. });
  4086. };
  4087. // Splits SDP into sessionpart and mediasections. Ensures CRLF.
  4088. SDPUtils.splitSections = function(blob) {
  4089. var parts = blob.split('\nm=');
  4090. return parts.map(function(part, index) {
  4091. return (index > 0 ? 'm=' + part : part).trim() + '\r\n';
  4092. });
  4093. };
  4094. // returns the session description.
  4095. SDPUtils.getDescription = function(blob) {
  4096. var sections = SDPUtils.splitSections(blob);
  4097. return sections && sections[0];
  4098. };
  4099. // returns the individual media sections.
  4100. SDPUtils.getMediaSections = function(blob) {
  4101. var sections = SDPUtils.splitSections(blob);
  4102. sections.shift();
  4103. return sections;
  4104. };
  4105. // Returns lines that start with a certain prefix.
  4106. SDPUtils.matchPrefix = function(blob, prefix) {
  4107. return SDPUtils.splitLines(blob).filter(function(line) {
  4108. return line.indexOf(prefix) === 0;
  4109. });
  4110. };
  4111. // Parses an ICE candidate line. Sample input:
  4112. // candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8
  4113. // rport 55996"
  4114. SDPUtils.parseCandidate = function(line) {
  4115. var parts;
  4116. // Parse both variants.
  4117. if (line.indexOf('a=candidate:') === 0) {
  4118. parts = line.substring(12).split(' ');
  4119. } else {
  4120. parts = line.substring(10).split(' ');
  4121. }
  4122. var candidate = {
  4123. foundation: parts[0],
  4124. component: parseInt(parts[1], 10),
  4125. protocol: parts[2].toLowerCase(),
  4126. priority: parseInt(parts[3], 10),
  4127. ip: parts[4],
  4128. address: parts[4], // address is an alias for ip.
  4129. port: parseInt(parts[5], 10),
  4130. // skip parts[6] == 'typ'
  4131. type: parts[7]
  4132. };
  4133. for (var i = 8; i < parts.length; i += 2) {
  4134. switch (parts[i]) {
  4135. case 'raddr':
  4136. candidate.relatedAddress = parts[i + 1];
  4137. break;
  4138. case 'rport':
  4139. candidate.relatedPort = parseInt(parts[i + 1], 10);
  4140. break;
  4141. case 'tcptype':
  4142. candidate.tcpType = parts[i + 1];
  4143. break;
  4144. case 'ufrag':
  4145. candidate.ufrag = parts[i + 1]; // for backward compability.
  4146. candidate.usernameFragment = parts[i + 1];
  4147. break;
  4148. default: // extension handling, in particular ufrag
  4149. candidate[parts[i]] = parts[i + 1];
  4150. break;
  4151. }
  4152. }
  4153. return candidate;
  4154. };
  4155. // Translates a candidate object into SDP candidate attribute.
  4156. SDPUtils.writeCandidate = function(candidate) {
  4157. var sdp = [];
  4158. sdp.push(candidate.foundation);
  4159. sdp.push(candidate.component);
  4160. sdp.push(candidate.protocol.toUpperCase());
  4161. sdp.push(candidate.priority);
  4162. sdp.push(candidate.address || candidate.ip);
  4163. sdp.push(candidate.port);
  4164. var type = candidate.type;
  4165. sdp.push('typ');
  4166. sdp.push(type);
  4167. if (type !== 'host' && candidate.relatedAddress &&
  4168. candidate.relatedPort) {
  4169. sdp.push('raddr');
  4170. sdp.push(candidate.relatedAddress);
  4171. sdp.push('rport');
  4172. sdp.push(candidate.relatedPort);
  4173. }
  4174. if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') {
  4175. sdp.push('tcptype');
  4176. sdp.push(candidate.tcpType);
  4177. }
  4178. if (candidate.usernameFragment || candidate.ufrag) {
  4179. sdp.push('ufrag');
  4180. sdp.push(candidate.usernameFragment || candidate.ufrag);
  4181. }
  4182. return 'candidate:' + sdp.join(' ');
  4183. };
  4184. // Parses an ice-options line, returns an array of option tags.
  4185. // a=ice-options:foo bar
  4186. SDPUtils.parseIceOptions = function(line) {
  4187. return line.substr(14).split(' ');
  4188. };
  4189. // Parses an rtpmap line, returns RTCRtpCoddecParameters. Sample input:
  4190. // a=rtpmap:111 opus/48000/2
  4191. SDPUtils.parseRtpMap = function(line) {
  4192. var parts = line.substr(9).split(' ');
  4193. var parsed = {
  4194. payloadType: parseInt(parts.shift(), 10) // was: id
  4195. };
  4196. parts = parts[0].split('/');
  4197. parsed.name = parts[0];
  4198. parsed.clockRate = parseInt(parts[1], 10); // was: clockrate
  4199. parsed.channels = parts.length === 3 ? parseInt(parts[2], 10) : 1;
  4200. // legacy alias, got renamed back to channels in ORTC.
  4201. parsed.numChannels = parsed.channels;
  4202. return parsed;
  4203. };
  4204. // Generate an a=rtpmap line from RTCRtpCodecCapability or
  4205. // RTCRtpCodecParameters.
  4206. SDPUtils.writeRtpMap = function(codec) {
  4207. var pt = codec.payloadType;
  4208. if (codec.preferredPayloadType !== undefined) {
  4209. pt = codec.preferredPayloadType;
  4210. }
  4211. var channels = codec.channels || codec.numChannels || 1;
  4212. return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate +
  4213. (channels !== 1 ? '/' + channels : '') + '\r\n';
  4214. };
  4215. // Parses an a=extmap line (headerextension from RFC 5285). Sample input:
  4216. // a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  4217. // a=extmap:2/sendonly urn:ietf:params:rtp-hdrext:toffset
  4218. SDPUtils.parseExtmap = function(line) {
  4219. var parts = line.substr(9).split(' ');
  4220. return {
  4221. id: parseInt(parts[0], 10),
  4222. direction: parts[0].indexOf('/') > 0 ? parts[0].split('/')[1] : 'sendrecv',
  4223. uri: parts[1]
  4224. };
  4225. };
  4226. // Generates a=extmap line from RTCRtpHeaderExtensionParameters or
  4227. // RTCRtpHeaderExtension.
  4228. SDPUtils.writeExtmap = function(headerExtension) {
  4229. return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) +
  4230. (headerExtension.direction && headerExtension.direction !== 'sendrecv'
  4231. ? '/' + headerExtension.direction
  4232. : '') +
  4233. ' ' + headerExtension.uri + '\r\n';
  4234. };
  4235. // Parses an ftmp line, returns dictionary. Sample input:
  4236. // a=fmtp:96 vbr=on;cng=on
  4237. // Also deals with vbr=on; cng=on
  4238. SDPUtils.parseFmtp = function(line) {
  4239. var parsed = {};
  4240. var kv;
  4241. var parts = line.substr(line.indexOf(' ') + 1).split(';');
  4242. for (var j = 0; j < parts.length; j++) {
  4243. kv = parts[j].trim().split('=');
  4244. parsed[kv[0].trim()] = kv[1];
  4245. }
  4246. return parsed;
  4247. };
  4248. // Generates an a=ftmp line from RTCRtpCodecCapability or RTCRtpCodecParameters.
  4249. SDPUtils.writeFmtp = function(codec) {
  4250. var line = '';
  4251. var pt = codec.payloadType;
  4252. if (codec.preferredPayloadType !== undefined) {
  4253. pt = codec.preferredPayloadType;
  4254. }
  4255. if (codec.parameters && Object.keys(codec.parameters).length) {
  4256. var params = [];
  4257. Object.keys(codec.parameters).forEach(function(param) {
  4258. if (codec.parameters[param]) {
  4259. params.push(param + '=' + codec.parameters[param]);
  4260. } else {
  4261. params.push(param);
  4262. }
  4263. });
  4264. line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\r\n';
  4265. }
  4266. return line;
  4267. };
  4268. // Parses an rtcp-fb line, returns RTCPRtcpFeedback object. Sample input:
  4269. // a=rtcp-fb:98 nack rpsi
  4270. SDPUtils.parseRtcpFb = function(line) {
  4271. var parts = line.substr(line.indexOf(' ') + 1).split(' ');
  4272. return {
  4273. type: parts.shift(),
  4274. parameter: parts.join(' ')
  4275. };
  4276. };
  4277. // Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters.
  4278. SDPUtils.writeRtcpFb = function(codec) {
  4279. var lines = '';
  4280. var pt = codec.payloadType;
  4281. if (codec.preferredPayloadType !== undefined) {
  4282. pt = codec.preferredPayloadType;
  4283. }
  4284. if (codec.rtcpFeedback && codec.rtcpFeedback.length) {
  4285. // FIXME: special handling for trr-int?
  4286. codec.rtcpFeedback.forEach(function(fb) {
  4287. lines += 'a=rtcp-fb:' + pt + ' ' + fb.type +
  4288. (fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') +
  4289. '\r\n';
  4290. });
  4291. }
  4292. return lines;
  4293. };
  4294. // Parses an RFC 5576 ssrc media attribute. Sample input:
  4295. // a=ssrc:3735928559 cname:something
  4296. SDPUtils.parseSsrcMedia = function(line) {
  4297. var sp = line.indexOf(' ');
  4298. var parts = {
  4299. ssrc: parseInt(line.substr(7, sp - 7), 10)
  4300. };
  4301. var colon = line.indexOf(':', sp);
  4302. if (colon > -1) {
  4303. parts.attribute = line.substr(sp + 1, colon - sp - 1);
  4304. parts.value = line.substr(colon + 1);
  4305. } else {
  4306. parts.attribute = line.substr(sp + 1);
  4307. }
  4308. return parts;
  4309. };
  4310. SDPUtils.parseSsrcGroup = function(line) {
  4311. var parts = line.substr(13).split(' ');
  4312. return {
  4313. semantics: parts.shift(),
  4314. ssrcs: parts.map(function(ssrc) {
  4315. return parseInt(ssrc, 10);
  4316. })
  4317. };
  4318. };
  4319. // Extracts the MID (RFC 5888) from a media section.
  4320. // returns the MID or undefined if no mid line was found.
  4321. SDPUtils.getMid = function(mediaSection) {
  4322. var mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:')[0];
  4323. if (mid) {
  4324. return mid.substr(6);
  4325. }
  4326. };
  4327. SDPUtils.parseFingerprint = function(line) {
  4328. var parts = line.substr(14).split(' ');
  4329. return {
  4330. algorithm: parts[0].toLowerCase(), // algorithm is case-sensitive in Edge.
  4331. value: parts[1]
  4332. };
  4333. };
  4334. // Extracts DTLS parameters from SDP media section or sessionpart.
  4335. // FIXME: for consistency with other functions this should only
  4336. // get the fingerprint line as input. See also getIceParameters.
  4337. SDPUtils.getDtlsParameters = function(mediaSection, sessionpart) {
  4338. var lines = SDPUtils.matchPrefix(mediaSection + sessionpart,
  4339. 'a=fingerprint:');
  4340. // Note: a=setup line is ignored since we use the 'auto' role.
  4341. // Note2: 'algorithm' is not case sensitive except in Edge.
  4342. return {
  4343. role: 'auto',
  4344. fingerprints: lines.map(SDPUtils.parseFingerprint)
  4345. };
  4346. };
  4347. // Serializes DTLS parameters to SDP.
  4348. SDPUtils.writeDtlsParameters = function(params, setupType) {
  4349. var sdp = 'a=setup:' + setupType + '\r\n';
  4350. params.fingerprints.forEach(function(fp) {
  4351. sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n';
  4352. });
  4353. return sdp;
  4354. };
  4355. // Parses ICE information from SDP media section or sessionpart.
  4356. // FIXME: for consistency with other functions this should only
  4357. // get the ice-ufrag and ice-pwd lines as input.
  4358. SDPUtils.getIceParameters = function(mediaSection, sessionpart) {
  4359. var lines = SDPUtils.splitLines(mediaSection);
  4360. // Search in session part, too.
  4361. lines = lines.concat(SDPUtils.splitLines(sessionpart));
  4362. var iceParameters = {
  4363. usernameFragment: lines.filter(function(line) {
  4364. return line.indexOf('a=ice-ufrag:') === 0;
  4365. })[0].substr(12),
  4366. password: lines.filter(function(line) {
  4367. return line.indexOf('a=ice-pwd:') === 0;
  4368. })[0].substr(10)
  4369. };
  4370. return iceParameters;
  4371. };
  4372. // Serializes ICE parameters to SDP.
  4373. SDPUtils.writeIceParameters = function(params) {
  4374. return 'a=ice-ufrag:' + params.usernameFragment + '\r\n' +
  4375. 'a=ice-pwd:' + params.password + '\r\n';
  4376. };
  4377. // Parses the SDP media section and returns RTCRtpParameters.
  4378. SDPUtils.parseRtpParameters = function(mediaSection) {
  4379. var description = {
  4380. codecs: [],
  4381. headerExtensions: [],
  4382. fecMechanisms: [],
  4383. rtcp: []
  4384. };
  4385. var lines = SDPUtils.splitLines(mediaSection);
  4386. var mline = lines[0].split(' ');
  4387. for (var i = 3; i < mline.length; i++) { // find all codecs from mline[3..]
  4388. var pt = mline[i];
  4389. var rtpmapline = SDPUtils.matchPrefix(
  4390. mediaSection, 'a=rtpmap:' + pt + ' ')[0];
  4391. if (rtpmapline) {
  4392. var codec = SDPUtils.parseRtpMap(rtpmapline);
  4393. var fmtps = SDPUtils.matchPrefix(
  4394. mediaSection, 'a=fmtp:' + pt + ' ');
  4395. // Only the first a=fmtp:<pt> is considered.
  4396. codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {};
  4397. codec.rtcpFeedback = SDPUtils.matchPrefix(
  4398. mediaSection, 'a=rtcp-fb:' + pt + ' ')
  4399. .map(SDPUtils.parseRtcpFb);
  4400. description.codecs.push(codec);
  4401. // parse FEC mechanisms from rtpmap lines.
  4402. switch (codec.name.toUpperCase()) {
  4403. case 'RED':
  4404. case 'ULPFEC':
  4405. description.fecMechanisms.push(codec.name.toUpperCase());
  4406. break;
  4407. default: // only RED and ULPFEC are recognized as FEC mechanisms.
  4408. break;
  4409. }
  4410. }
  4411. }
  4412. SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(function(line) {
  4413. description.headerExtensions.push(SDPUtils.parseExtmap(line));
  4414. });
  4415. // FIXME: parse rtcp.
  4416. return description;
  4417. };
  4418. // Generates parts of the SDP media section describing the capabilities /
  4419. // parameters.
  4420. SDPUtils.writeRtpDescription = function(kind, caps) {
  4421. var sdp = '';
  4422. // Build the mline.
  4423. sdp += 'm=' + kind + ' ';
  4424. sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs.
  4425. sdp += ' UDP/TLS/RTP/SAVPF ';
  4426. sdp += caps.codecs.map(function(codec) {
  4427. if (codec.preferredPayloadType !== undefined) {
  4428. return codec.preferredPayloadType;
  4429. }
  4430. return codec.payloadType;
  4431. }).join(' ') + '\r\n';
  4432. sdp += 'c=IN IP4 0.0.0.0\r\n';
  4433. sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n';
  4434. // Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb.
  4435. caps.codecs.forEach(function(codec) {
  4436. sdp += SDPUtils.writeRtpMap(codec);
  4437. sdp += SDPUtils.writeFmtp(codec);
  4438. sdp += SDPUtils.writeRtcpFb(codec);
  4439. });
  4440. var maxptime = 0;
  4441. caps.codecs.forEach(function(codec) {
  4442. if (codec.maxptime > maxptime) {
  4443. maxptime = codec.maxptime;
  4444. }
  4445. });
  4446. if (maxptime > 0) {
  4447. sdp += 'a=maxptime:' + maxptime + '\r\n';
  4448. }
  4449. sdp += 'a=rtcp-mux\r\n';
  4450. if (caps.headerExtensions) {
  4451. caps.headerExtensions.forEach(function(extension) {
  4452. sdp += SDPUtils.writeExtmap(extension);
  4453. });
  4454. }
  4455. // FIXME: write fecMechanisms.
  4456. return sdp;
  4457. };
  4458. // Parses the SDP media section and returns an array of
  4459. // RTCRtpEncodingParameters.
  4460. SDPUtils.parseRtpEncodingParameters = function(mediaSection) {
  4461. var encodingParameters = [];
  4462. var description = SDPUtils.parseRtpParameters(mediaSection);
  4463. var hasRed = description.fecMechanisms.indexOf('RED') !== -1;
  4464. var hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1;
  4465. // filter a=ssrc:... cname:, ignore PlanB-msid
  4466. var ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  4467. .map(function(line) {
  4468. return SDPUtils.parseSsrcMedia(line);
  4469. })
  4470. .filter(function(parts) {
  4471. return parts.attribute === 'cname';
  4472. });
  4473. var primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc;
  4474. var secondarySsrc;
  4475. var flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID')
  4476. .map(function(line) {
  4477. var parts = line.substr(17).split(' ');
  4478. return parts.map(function(part) {
  4479. return parseInt(part, 10);
  4480. });
  4481. });
  4482. if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) {
  4483. secondarySsrc = flows[0][1];
  4484. }
  4485. description.codecs.forEach(function(codec) {
  4486. if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) {
  4487. var encParam = {
  4488. ssrc: primarySsrc,
  4489. codecPayloadType: parseInt(codec.parameters.apt, 10)
  4490. };
  4491. if (primarySsrc && secondarySsrc) {
  4492. encParam.rtx = {ssrc: secondarySsrc};
  4493. }
  4494. encodingParameters.push(encParam);
  4495. if (hasRed) {
  4496. encParam = JSON.parse(JSON.stringify(encParam));
  4497. encParam.fec = {
  4498. ssrc: primarySsrc,
  4499. mechanism: hasUlpfec ? 'red+ulpfec' : 'red'
  4500. };
  4501. encodingParameters.push(encParam);
  4502. }
  4503. }
  4504. });
  4505. if (encodingParameters.length === 0 && primarySsrc) {
  4506. encodingParameters.push({
  4507. ssrc: primarySsrc
  4508. });
  4509. }
  4510. // we support both b=AS and b=TIAS but interpret AS as TIAS.
  4511. var bandwidth = SDPUtils.matchPrefix(mediaSection, 'b=');
  4512. if (bandwidth.length) {
  4513. if (bandwidth[0].indexOf('b=TIAS:') === 0) {
  4514. bandwidth = parseInt(bandwidth[0].substr(7), 10);
  4515. } else if (bandwidth[0].indexOf('b=AS:') === 0) {
  4516. // use formula from JSEP to convert b=AS to TIAS value.
  4517. bandwidth = parseInt(bandwidth[0].substr(5), 10) * 1000 * 0.95
  4518. - (50 * 40 * 8);
  4519. } else {
  4520. bandwidth = undefined;
  4521. }
  4522. encodingParameters.forEach(function(params) {
  4523. params.maxBitrate = bandwidth;
  4524. });
  4525. }
  4526. return encodingParameters;
  4527. };
  4528. // parses http://draft.ortc.org/#rtcrtcpparameters*
  4529. SDPUtils.parseRtcpParameters = function(mediaSection) {
  4530. var rtcpParameters = {};
  4531. // Gets the first SSRC. Note tha with RTX there might be multiple
  4532. // SSRCs.
  4533. var remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  4534. .map(function(line) {
  4535. return SDPUtils.parseSsrcMedia(line);
  4536. })
  4537. .filter(function(obj) {
  4538. return obj.attribute === 'cname';
  4539. })[0];
  4540. if (remoteSsrc) {
  4541. rtcpParameters.cname = remoteSsrc.value;
  4542. rtcpParameters.ssrc = remoteSsrc.ssrc;
  4543. }
  4544. // Edge uses the compound attribute instead of reducedSize
  4545. // compound is !reducedSize
  4546. var rsize = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-rsize');
  4547. rtcpParameters.reducedSize = rsize.length > 0;
  4548. rtcpParameters.compound = rsize.length === 0;
  4549. // parses the rtcp-mux attrіbute.
  4550. // Note that Edge does not support unmuxed RTCP.
  4551. var mux = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-mux');
  4552. rtcpParameters.mux = mux.length > 0;
  4553. return rtcpParameters;
  4554. };
  4555. // parses either a=msid: or a=ssrc:... msid lines and returns
  4556. // the id of the MediaStream and MediaStreamTrack.
  4557. SDPUtils.parseMsid = function(mediaSection) {
  4558. var parts;
  4559. var spec = SDPUtils.matchPrefix(mediaSection, 'a=msid:');
  4560. if (spec.length === 1) {
  4561. parts = spec[0].substr(7).split(' ');
  4562. return {stream: parts[0], track: parts[1]};
  4563. }
  4564. var planB = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  4565. .map(function(line) {
  4566. return SDPUtils.parseSsrcMedia(line);
  4567. })
  4568. .filter(function(msidParts) {
  4569. return msidParts.attribute === 'msid';
  4570. });
  4571. if (planB.length > 0) {
  4572. parts = planB[0].value.split(' ');
  4573. return {stream: parts[0], track: parts[1]};
  4574. }
  4575. };
  4576. // Generate a session ID for SDP.
  4577. // https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-20#section-5.2.1
  4578. // recommends using a cryptographically random +ve 64-bit value
  4579. // but right now this should be acceptable and within the right range
  4580. SDPUtils.generateSessionId = function() {
  4581. return Math.random().toString().substr(2, 21);
  4582. };
  4583. // Write boilder plate for start of SDP
  4584. // sessId argument is optional - if not supplied it will
  4585. // be generated randomly
  4586. // sessVersion is optional and defaults to 2
  4587. // sessUser is optional and defaults to 'thisisadapterortc'
  4588. SDPUtils.writeSessionBoilerplate = function(sessId, sessVer, sessUser) {
  4589. var sessionId;
  4590. var version = sessVer !== undefined ? sessVer : 2;
  4591. if (sessId) {
  4592. sessionId = sessId;
  4593. } else {
  4594. sessionId = SDPUtils.generateSessionId();
  4595. }
  4596. var user = sessUser || 'thisisadapterortc';
  4597. // FIXME: sess-id should be an NTP timestamp.
  4598. return 'v=0\r\n' +
  4599. 'o=' + user + ' ' + sessionId + ' ' + version +
  4600. ' IN IP4 127.0.0.1\r\n' +
  4601. 's=-\r\n' +
  4602. 't=0 0\r\n';
  4603. };
  4604. SDPUtils.writeMediaSection = function(transceiver, caps, type, stream) {
  4605. var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps);
  4606. // Map ICE parameters (ufrag, pwd) to SDP.
  4607. sdp += SDPUtils.writeIceParameters(
  4608. transceiver.iceGatherer.getLocalParameters());
  4609. // Map DTLS parameters to SDP.
  4610. sdp += SDPUtils.writeDtlsParameters(
  4611. transceiver.dtlsTransport.getLocalParameters(),
  4612. type === 'offer' ? 'actpass' : 'active');
  4613. sdp += 'a=mid:' + transceiver.mid + '\r\n';
  4614. if (transceiver.direction) {
  4615. sdp += 'a=' + transceiver.direction + '\r\n';
  4616. } else if (transceiver.rtpSender && transceiver.rtpReceiver) {
  4617. sdp += 'a=sendrecv\r\n';
  4618. } else if (transceiver.rtpSender) {
  4619. sdp += 'a=sendonly\r\n';
  4620. } else if (transceiver.rtpReceiver) {
  4621. sdp += 'a=recvonly\r\n';
  4622. } else {
  4623. sdp += 'a=inactive\r\n';
  4624. }
  4625. if (transceiver.rtpSender) {
  4626. // spec.
  4627. var msid = 'msid:' + stream.id + ' ' +
  4628. transceiver.rtpSender.track.id + '\r\n';
  4629. sdp += 'a=' + msid;
  4630. // for Chrome.
  4631. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  4632. ' ' + msid;
  4633. if (transceiver.sendEncodingParameters[0].rtx) {
  4634. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  4635. ' ' + msid;
  4636. sdp += 'a=ssrc-group:FID ' +
  4637. transceiver.sendEncodingParameters[0].ssrc + ' ' +
  4638. transceiver.sendEncodingParameters[0].rtx.ssrc +
  4639. '\r\n';
  4640. }
  4641. }
  4642. // FIXME: this should be written by writeRtpDescription.
  4643. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  4644. ' cname:' + SDPUtils.localCName + '\r\n';
  4645. if (transceiver.rtpSender && transceiver.sendEncodingParameters[0].rtx) {
  4646. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  4647. ' cname:' + SDPUtils.localCName + '\r\n';
  4648. }
  4649. return sdp;
  4650. };
  4651. // Gets the direction from the mediaSection or the sessionpart.
  4652. SDPUtils.getDirection = function(mediaSection, sessionpart) {
  4653. // Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv.
  4654. var lines = SDPUtils.splitLines(mediaSection);
  4655. for (var i = 0; i < lines.length; i++) {
  4656. switch (lines[i]) {
  4657. case 'a=sendrecv':
  4658. case 'a=sendonly':
  4659. case 'a=recvonly':
  4660. case 'a=inactive':
  4661. return lines[i].substr(2);
  4662. default:
  4663. // FIXME: What should happen here?
  4664. }
  4665. }
  4666. if (sessionpart) {
  4667. return SDPUtils.getDirection(sessionpart);
  4668. }
  4669. return 'sendrecv';
  4670. };
  4671. SDPUtils.getKind = function(mediaSection) {
  4672. var lines = SDPUtils.splitLines(mediaSection);
  4673. var mline = lines[0].split(' ');
  4674. return mline[0].substr(2);
  4675. };
  4676. SDPUtils.isRejected = function(mediaSection) {
  4677. return mediaSection.split(' ', 2)[1] === '0';
  4678. };
  4679. SDPUtils.parseMLine = function(mediaSection) {
  4680. var lines = SDPUtils.splitLines(mediaSection);
  4681. var parts = lines[0].substr(2).split(' ');
  4682. return {
  4683. kind: parts[0],
  4684. port: parseInt(parts[1], 10),
  4685. protocol: parts[2],
  4686. fmt: parts.slice(3).join(' ')
  4687. };
  4688. };
  4689. SDPUtils.parseOLine = function(mediaSection) {
  4690. var line = SDPUtils.matchPrefix(mediaSection, 'o=')[0];
  4691. var parts = line.substr(2).split(' ');
  4692. return {
  4693. username: parts[0],
  4694. sessionId: parts[1],
  4695. sessionVersion: parseInt(parts[2], 10),
  4696. netType: parts[3],
  4697. addressType: parts[4],
  4698. address: parts[5]
  4699. };
  4700. };
  4701. // a very naive interpretation of a valid SDP.
  4702. SDPUtils.isValidSDP = function(blob) {
  4703. if (typeof blob !== 'string' || blob.length === 0) {
  4704. return false;
  4705. }
  4706. var lines = SDPUtils.splitLines(blob);
  4707. for (var i = 0; i < lines.length; i++) {
  4708. if (lines[i].length < 2 || lines[i].charAt(1) !== '=') {
  4709. return false;
  4710. }
  4711. // TODO: check the modifier a bit more.
  4712. }
  4713. return true;
  4714. };
  4715. // Expose public methods.
  4716. if (typeof module === 'object') {
  4717. module.exports = SDPUtils;
  4718. }
  4719. },{}]},{},[1])(1)
  4720. });