adapter-latest.js 190 KB

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