adapter-latest.js 195 KB

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