adapeter.js 275 KB

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