adapter-latest.js 192 KB

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