adapter-latest_.js 180 KB

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