rtcEngine.min.js 268 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  3. typeof define === 'function' && define.amd ? define(factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.RtcEngine = factory());
  5. })(this, (function () { 'use strict';
  6. let ws = null, heartBeatFlag = null;
  7. //此文件实现将控制命令封装成协议,具体协议内容请看:
  8. //链接:http://note.youdao.com/noteshare?id=dabda6c613adef7a416bd2625cd770a1
  9. //bcc校验码计算
  10. //arry: 要计算的数组
  11. //返回计算协议中校验位的校验码
  12. function calBcc(arry)
  13. {
  14. var bcc = 0;
  15. for(let i = 0;i < arry.length;i++)
  16. {
  17. bcc ^= arry[i];
  18. }
  19. return bcc;
  20. }
  21. function makeFrameExtend(sn, dataType, body)
  22. {
  23. var index = 0;
  24. var dataLen = body.length;
  25. var frameLen = dataLen + 26;
  26. var outPut = new Uint8Array(frameLen);
  27. outPut[index++] = 0x68;
  28. outPut[index++] = (dataLen & 0xff000000) >> 24;
  29. outPut[index++] = (dataLen & 0x00ff0000) >> 16;
  30. outPut[index++] = (dataLen & 0x0000ff00) >> 8;
  31. outPut[index++] = dataLen & 0x000000ff;
  32. outPut[index++] = 0;//类型为client
  33. //sn号赋值,string转ascii
  34. for(let i = 0;i< sn.length;i++)
  35. {
  36. outPut[index++] = sn[i].charCodeAt();
  37. }
  38. outPut[index++] = dataType;//指定数据类型为json
  39. //json string转ascii
  40. for(let i = 0;i < body.length;i++)
  41. {
  42. outPut[index++] = body[i];
  43. }
  44. var bccBuffer = outPut.slice(1, frameLen-3 + 1);//忽略协议头和协议尾
  45. outPut[index++] = calBcc(bccBuffer);
  46. outPut[index++] = 0x16;
  47. //var str = PrintArry(outPut);
  48. //console.log("打印数组:%s", PrintArry(outPut));
  49. //return PrintArry(outPut);
  50. return outPut;
  51. }
  52. //根据报文识别屏幕方向, 0横屏,1竖屏
  53. function CheckScreenDirection(data)
  54. {
  55. if (data[0] == 0 && data[1] == 0 && data[2] == 0 &&data[3] == 1)
  56. {
  57. if (data[4] == 1 && data[5] == 1)
  58. {
  59. if (data[6] == 1)
  60. {
  61. screen = data[7];
  62. return screen;
  63. }
  64. }
  65. }
  66. }
  67. //查询屏幕方向
  68. function GetScreenState()
  69. {
  70. var sn = "RK3923C1201900139";
  71. var outPut = new Uint8Array([0x00,0x00,0x00,0x01,0x01,0x01,0x01,0x02]);
  72. return makeFrameExtend(sn, 5, outPut);
  73. }
  74. //生成鉴权报文
  75. function VerifyCode(sn, code)
  76. {
  77. var len = code.length + 1;
  78. var codeBuffer = new TextEncoder("utf-8").encode(code);//获取字符串ascii码
  79. var buffer = new Uint8Array(len);
  80. buffer[0] = 0x04;
  81. for(let i = 0;i < codeBuffer.length;i++)
  82. {
  83. buffer[i + 1] = codeBuffer[i];
  84. }
  85. return makeFrameExtend(sn, 6, buffer);
  86. }
  87. //
  88. function CheckVerifyCode(data)
  89. {
  90. var dataLen = data.length - 26;
  91. var body = data.slice(24, 24 + dataLen);
  92. if(body[3] == 0x03)
  93. {
  94. return true;
  95. }
  96. return false;
  97. }
  98. //通道配置
  99. function ConfigChannel(sn, channelName)
  100. {
  101. var chanelBuffer = new TextEncoder("utf-8").encode(channelName);
  102. var outPut = [];
  103. outPut.push(0x07);
  104. for(let i = 0;i < chanelBuffer.length;i++) {
  105. outPut.push(chanelBuffer[i]);
  106. }
  107. return makeFrameExtend(sn, 6, outPut);
  108. }
  109. //切换清晰度
  110. function makeSharpness(level)
  111. {
  112. var sn = "RK3923C1201900139";
  113. var jsonObj =
  114. {"type":2,"data":{"definition":level,
  115. "clientType": "h5",
  116. "sceneType": "cloudPhone"
  117. }};
  118. var jsonStr = JSON.stringify(jsonObj);
  119. var outPut = new TextEncoder("utf-8").encode(jsonStr);
  120. return makeFrameExtend(sn, 0xD, outPut);
  121. }
  122. //I 帧请求报文生成
  123. function RequestIFrame()
  124. {
  125. var sn = "RK3923C1201900139";
  126. var outPut = new Uint8Array([0x20]);
  127. return makeFrameExtend(sn, 6, outPut);
  128. }
  129. function setFps(frameRate) {
  130. let sn = "RK3923C1201900139";
  131. let jsonObj = { "type": 5, "data": { "frame_rate": frameRate } };
  132. let jsonStr = JSON.stringify(jsonObj);
  133. let outPut = new TextEncoder("utf-8").encode(jsonStr);
  134. return makeFrameExtend(sn, 0x0D, outPut);
  135. }
  136. const Authen_ID = 0x5C;//鉴权标识
  137. const MultiLogin_ID = 0x0B;//多端登录标识
  138. const ScreenDirection_ID = 0x05;//横竖屏状态
  139. const Audio_ID = 0xFF;//音频标识
  140. const Porto_Header_ID = 0x68;//协议头标识
  141. const Landscape_ID = 0x00;//横屏标识
  142. const Vertica_ID = 0X01;//竖屏标识
  143. const SPS_ID = 0X07;//SPD标识
  144. const PPS_ID = 0X08;//PPS标识
  145. const verify_Failed = -1001;//鉴权失败
  146. const OPEN_SUCCESS = 0;//拉流成功,正常显示
  147. function PCMPlayer(option) {
  148. this.init(option);
  149. }
  150. PCMPlayer.prototype.init = function(option) {
  151. var defaults = {
  152. encoding: '16bitInt',
  153. channels: 1,
  154. sampleRate: 8000,
  155. flushingTime: 1000
  156. };
  157. this.option = Object.assign({}, defaults, option);
  158. this.samples = new Float32Array();
  159. this.flush = this.flush.bind(this);
  160. this.interval = setInterval(this.flush, this.option.flushingTime);
  161. this.maxValue = this.getMaxValue();
  162. this.typedArray = this.getTypedArray();
  163. this.createContext();
  164. };
  165. PCMPlayer.prototype.getMaxValue = function () {
  166. var encodings = {
  167. '8bitInt': 128,
  168. '16bitInt': 32768,
  169. '32bitInt': 2147483648,
  170. '32bitFloat': 1
  171. };
  172. return encodings[this.option.encoding] ? encodings[this.option.encoding] : encodings['16bitInt'];
  173. };
  174. PCMPlayer.prototype.getTypedArray = function () {
  175. var typedArrays = {
  176. '8bitInt': Int8Array,
  177. '16bitInt': Int16Array,
  178. '32bitInt': Int32Array,
  179. '32bitFloat': Float32Array
  180. };
  181. return typedArrays[this.option.encoding] ? typedArrays[this.option.encoding] : typedArrays['16bitInt'];
  182. };
  183. PCMPlayer.prototype.createContext = function() {
  184. this.audioCtx = new (window.AudioContext || window.webkitAudioContext)();
  185. this.gainNode = this.audioCtx.createGain();
  186. this.gainNode.gain.value = 1;
  187. this.gainNode.connect(this.audioCtx.destination);
  188. this.startTime = this.audioCtx.currentTime;
  189. };
  190. PCMPlayer.prototype.isTypedArray = function(data) {
  191. return (data.byteLength && data.buffer && data.buffer.constructor == ArrayBuffer);
  192. };
  193. PCMPlayer.prototype.feed = function(data) {
  194. if (!this.isTypedArray(data)) return;
  195. data = this.getFormatedValue(data);
  196. var tmp = new Float32Array(this.samples.length + data.length);
  197. tmp.set(this.samples, 0);
  198. tmp.set(data, this.samples.length);
  199. this.samples = tmp;
  200. };
  201. PCMPlayer.prototype.getFormatedValue = function(data) {
  202. var data = new this.typedArray(data.buffer),
  203. float32 = new Float32Array(data.length),
  204. i;
  205. for (i = 0; i < data.length; i++) {
  206. float32[i] = data[i] / this.maxValue;
  207. }
  208. return float32;
  209. };
  210. PCMPlayer.prototype.volume = function(volume) {
  211. this.gainNode.gain.value = volume;
  212. };
  213. PCMPlayer.prototype.destroy = function() {
  214. if (this.interval) {
  215. clearInterval(this.interval);
  216. }
  217. this.samples = null;
  218. this.audioCtx.close();
  219. this.audioCtx = null;
  220. };
  221. PCMPlayer.prototype.flush = function() {
  222. if (!this.samples.length) return;
  223. var bufferSource = this.audioCtx.createBufferSource(),
  224. length = this.samples.length / this.option.channels,
  225. audioBuffer = this.audioCtx.createBuffer(this.option.channels, length, this.option.sampleRate),
  226. audioData,
  227. channel,
  228. offset,
  229. i,
  230. decrement;
  231. for (channel = 0; channel < this.option.channels; channel++) {
  232. audioData = audioBuffer.getChannelData(channel);
  233. offset = channel;
  234. decrement = 50;
  235. for (i = 0; i < length; i++) {
  236. audioData[i] = this.samples[offset];
  237. /* fadein */
  238. if (i < 50) {
  239. audioData[i] = (audioData[i] * i) / 50;
  240. }
  241. /* fadeout*/
  242. if (i >= (length - 51)) {
  243. audioData[i] = (audioData[i] * decrement--) / 50;
  244. }
  245. offset += this.option.channels;
  246. }
  247. }
  248. if (this.startTime < this.audioCtx.currentTime) {
  249. this.startTime = this.audioCtx.currentTime;
  250. }
  251. //console.log('start vs current '+this.startTime+' vs '+this.audioCtx.currentTime+' duration: '+audioBuffer.duration);
  252. bufferSource.buffer = audioBuffer;
  253. bufferSource.connect(this.gainNode);
  254. bufferSource.start(this.startTime);
  255. this.startTime += audioBuffer.duration;
  256. this.samples = new Float32Array();
  257. };
  258. class AACPlayer {
  259. constructor() {
  260. this.pcmPlayer = new PCMPlayer({
  261. encoding: '16bitInt',
  262. channels: 2,
  263. sampleRate: 44100,
  264. flushingTime: 22,
  265. debug: false
  266. });
  267. this.decodeWorker = new Worker("decodeAACWorker.js");
  268. this.onDecodeFinished = this.onDecodeFinished.bind(this);
  269. this.decodeWorker.onmessage = this.onDecodeFinished;
  270. }
  271. onDecodeFinished(event) {
  272. let data = event.data;
  273. if(data.type == "pcmData") {
  274. this.pcmPlayer.feed(data.data);
  275. }
  276. }
  277. feed(data) {
  278. let info = {
  279. type:"aacData",
  280. data:data
  281. };
  282. this.decodeWorker.postMessage(info);
  283. }
  284. stop() {
  285. this.decodeWorker.terminate();
  286. this.pcmPlayer.destroy();
  287. }
  288. }
  289. //import JMuxer from 'jmuxer';
  290. class MseConnect {
  291. constructor(option) {
  292. this.token = option.token;
  293. this.callback = option.callback;
  294. this.url = option.url;
  295. this.videoId = option.videoId;
  296. this.fps = 60;
  297. this.wsOnMessage = this.wsOnMessage.bind(this);
  298. this.wsOnClose = this.wsOnClose.bind(this);
  299. this.wsOpen = this.wsOpen.bind(this);
  300. this.heartBeat = this.heartBeat.bind(this);
  301. this.startPlay = this.startPlay.bind(this);
  302. this.wasmFinish = false;
  303. this.isFeed = true;
  304. this.lastRequseTime = 0;
  305. this.netFps = 0;
  306. this.lastCalTime = 0;
  307. this.videoNum = 0;
  308. }
  309. heartBeat() {
  310. this.ws.send("ping");
  311. let interval = new Date().getTime() - this.lastRequseTime;
  312. if(interval >= 3000*10 && this.isFeed) {
  313. this.doReqesuIFrame();
  314. this.lastRequseTime = new Date().getTime();
  315. }
  316. }
  317. pause() {
  318. this.isFeed = false;
  319. }
  320. resume() {
  321. this.doReqesuIFrame();
  322. }
  323. doReqesuIFrame() {
  324. let buffer = RequestIFrame();
  325. this.ws.send(buffer);
  326. }
  327. stateCallBack(eventName, value, desc) {
  328. let info = {
  329. type:eventName,
  330. val: value,
  331. description:desc
  332. };
  333. this.callback(info);
  334. }
  335. setFps() {
  336. let buffer = setFps(this.fps);
  337. this.ws.send(buffer);
  338. }
  339. connect() {
  340. this.ws.onmessage = this.wsOnMessage;
  341. this.ws.onopen = this.wsOpen;
  342. this.ws.onclose = this.wsOnClose;
  343. this.ws = new WebSocket(this.url);
  344. this.ws.binaryType = 'arraybuffer';
  345. this.jmuxer = new JMuxer({
  346. node: this.videoId,
  347. flushingTime:0 ,
  348. fps: this.fps,
  349. mode:'video',
  350. debug: false
  351. });
  352. this.aacPlayer = new AACPlayer();
  353. this.videoTag = document.getElementById(this.videoId);
  354. let videoElement = document.getElementById(this.videoId);
  355. videoElement.onplay = this.startPlay;
  356. }
  357. startPlay() {
  358. this.stateCallBack("open", OPEN_SUCCESS, "拉流成功");
  359. }
  360. parseProto (data) {
  361. let input = new Uint8Array(data);
  362. var duration, video, audio, frameType;
  363. if(input[0] == 0 && input[1] == 0 && input[2] == 0 && input[3] == 1) {
  364. video = input;
  365. frameType = input[4] & 0x1f;
  366. }
  367. if(input[0] == Audio_ID) {
  368. audio = input;
  369. }
  370. if(input[0] == Porto_Header_ID) {
  371. if(input[23] == MultiLogin_ID) ;
  372. if(input[23] == Authen_ID) {
  373. if(CheckVerifyCode(input)) {
  374. this.configChannel();
  375. this.setFps();
  376. }
  377. else {
  378. this.stateCallBack("verifyFailed", verify_Failed, "鉴权失败");
  379. }
  380. }
  381. if(input[23] == ScreenDirection_ID) {
  382. let direction = CheckScreenDirection(input.slice(24, 24 + 8));
  383. if(direction == Vertica_ID) {
  384. this.stateCallBack("screenChange", direction, "安卓卡竖屏");
  385. }
  386. if(direction == Landscape_ID) {
  387. this.stateCallBack("screenChange", direction, "安卓卡横屏");
  388. }
  389. }
  390. }
  391. duration = 1000/this.fps;
  392. return {
  393. audio:audio,
  394. video:video,
  395. duration:duration,
  396. frameType:frameType
  397. }
  398. }
  399. configChannel() {
  400. let sn = "RK3923C1201900139";
  401. this.ws.send(ConfigChannel(sn, "chaohang"));//chaohang ??
  402. this.ws.send(GetScreenState());
  403. }
  404. switchShapness(sharpnessLevel) {
  405. let buffer = makeSharpness(sharpnessLevel);
  406. this.ws.send(buffer);
  407. }
  408. wsOnMessage(event) {
  409. let data = this.parseProto(event.data);
  410. if(data.audio != null) {
  411. this.aacPlayer.feed(data.audio);
  412. }
  413. if(data.video != null) {
  414. if(data.frameType == SPS_ID || data.frameType == PPS_ID){
  415. this.isFeed = true;
  416. }
  417. if(this.isFeed)
  418. this.jmuxer.feed(data);
  419. }
  420. }
  421. wsOpen(event) {
  422. let sn = "RK3923C1201900139";
  423. let verifyBuffer = VerifyCode(sn, this.token);
  424. this.ws.send(verifyBuffer);
  425. this.heartBeatFlag = setInterval(this.heartBeat, 2000);
  426. heartBeatFlag = this.heartBeatFlag
  427. }
  428. wsOnClose(event) {
  429. this.stateCallBack("closeEvent", event.code, "WS关闭事件");
  430. }
  431. disconnect() {
  432. clearInterval(this.heartBeatFlag);
  433. this.aacPlayer.stop();
  434. this.jmuxer.destroy();
  435. this.ws.close();
  436. this.onclose = undefined;
  437. }
  438. }
  439. const Events$1 = {
  440. WEBRTC_NOT_SUPPORT: 'WEBRTC_NOT_SUPPORT',
  441. WEBRTC_ICE_CANDIDATE_ERROR: 'WEBRTC_ICE_CANDIDATE_ERROR',
  442. WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED: 'WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED',
  443. WEBRTC_ON_REMOTE_STREAMS: 'WEBRTC_ON_REMOTE_STREAMS',
  444. WEBRTC_ON_LOCAL_STREAM: 'WEBRTC_ON_LOCAL_STREAM',
  445. WEBRTC_ON_CONNECTION_STATE_CHANGE: 'WEBRTC_ON_CONNECTION_STATE_CHANGE',
  446. WEBRTC_ON_DATA_CHANNEL_OPEN: 'WEBRTC_ON_DATA_CHANNEL_OPEN',
  447. WEBRTC_ON_DATA_CHANNEL_CLOSE: 'WEBRTC_ON_DATA_CHANNEL_CLOSE',
  448. WEBRTC_ON_DATA_CHANNEL_ERR: 'WEBRTC_ON_DATA_CHANNEL_ERR',
  449. WEBRTC_ON_DATA_CHANNEL_MSG: 'WEBRTC_ON_DATA_CHANNEL_MSG',
  450. CAPTURE_STREAM_FAILED: 'CAPTURE_STREAM_FAILED'
  451. };
  452. const VERSION$1 = '1.0.1';
  453. const BUILD_DATE = 'Fri Aug 26 2022 15:21:07 GMT+0800 (中国标准时间)';
  454. // Copyright (C) <2018> Intel Corporation
  455. //
  456. // SPDX-License-Identifier: Apache-2.0
  457. // eslint-disable-next-line require-jsdoc
  458. function isFirefox() {
  459. return window.navigator.userAgent.match('Firefox') !== null;
  460. } // eslint-disable-next-line require-jsdoc
  461. function isChrome() {
  462. return window.navigator.userAgent.match('Chrome') !== null;
  463. } // eslint-disable-next-line require-jsdoc
  464. function isEdge() {
  465. return window.navigator.userAgent.match(/Edge\/(\d+).(\d+)$/) !== null;
  466. } // eslint-disable-next-line require-jsdoc
  467. // Copyright (C) <2018> Intel Corporation
  468. /**
  469. * @class AudioSourceInfo
  470. * @classDesc Source info about an audio track. Values: 'mic', 'screen-cast', 'file', 'mixed'.
  471. * @memberOf Owt.Base
  472. * @readonly
  473. * @enum {string}
  474. */
  475. const AudioSourceInfo = {
  476. MIC: 'mic',
  477. SCREENCAST: 'screen-cast',
  478. FILE: 'file',
  479. MIXED: 'mixed'
  480. };
  481. /**
  482. * @class VideoSourceInfo
  483. * @classDesc Source info about a video track. Values: 'camera', 'screen-cast', 'file', 'mixed'.
  484. * @memberOf Owt.Base
  485. * @readonly
  486. * @enum {string}
  487. */
  488. const VideoSourceInfo = {
  489. CAMERA: 'camera',
  490. SCREENCAST: 'screen-cast',
  491. FILE: 'file',
  492. MIXED: 'mixed'
  493. };
  494. /**
  495. * @class Resolution
  496. * @memberOf Owt.Base
  497. * @classDesc The Resolution defines the size of a rectangle.
  498. * @constructor
  499. * @param {number} width
  500. * @param {number} height
  501. */
  502. class Resolution {
  503. // eslint-disable-next-line require-jsdoc
  504. constructor(width, height) {
  505. /**
  506. * @member {number} width
  507. * @instance
  508. * @memberof Owt.Base.Resolution
  509. */
  510. this.width = width;
  511. /**
  512. * @member {number} height
  513. * @instance
  514. * @memberof Owt.Base.Resolution
  515. */
  516. this.height = height;
  517. }
  518. }
  519. /*
  520. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  521. *
  522. * Use of this source code is governed by a BSD-style license
  523. * that can be found in the LICENSE file in the root of the source
  524. * tree.
  525. */
  526. let logDisabled_ = true;
  527. let deprecationWarnings_ = true;
  528. /**
  529. * Extract browser version out of the provided user agent string.
  530. *
  531. * @param {!string} uastring userAgent string.
  532. * @param {!string} expr Regular expression used as match criteria.
  533. * @param {!number} pos position in the version string to be returned.
  534. * @return {!number} browser version.
  535. */
  536. function extractVersion(uastring, expr, pos) {
  537. const match = uastring.match(expr);
  538. return match && match.length >= pos && parseInt(match[pos], 10);
  539. }
  540. // Wraps the peerconnection event eventNameToWrap in a function
  541. // which returns the modified event object (or false to prevent
  542. // the event).
  543. function wrapPeerConnectionEvent(window, eventNameToWrap, wrapper) {
  544. if (!window.RTCPeerConnection) {
  545. return;
  546. }
  547. const proto = window.RTCPeerConnection.prototype;
  548. const nativeAddEventListener = proto.addEventListener;
  549. proto.addEventListener = function(nativeEventName, cb) {
  550. if (nativeEventName !== eventNameToWrap) {
  551. return nativeAddEventListener.apply(this, arguments);
  552. }
  553. const wrappedCallback = (e) => {
  554. const modifiedEvent = wrapper(e);
  555. if (modifiedEvent) {
  556. if (cb.handleEvent) {
  557. cb.handleEvent(modifiedEvent);
  558. } else {
  559. cb(modifiedEvent);
  560. }
  561. }
  562. };
  563. this._eventMap = this._eventMap || {};
  564. if (!this._eventMap[eventNameToWrap]) {
  565. this._eventMap[eventNameToWrap] = new Map();
  566. }
  567. this._eventMap[eventNameToWrap].set(cb, wrappedCallback);
  568. return nativeAddEventListener.apply(this, [nativeEventName,
  569. wrappedCallback
  570. ]);
  571. };
  572. const nativeRemoveEventListener = proto.removeEventListener;
  573. proto.removeEventListener = function(nativeEventName, cb) {
  574. if (nativeEventName !== eventNameToWrap || !this._eventMap ||
  575. !this._eventMap[eventNameToWrap]) {
  576. return nativeRemoveEventListener.apply(this, arguments);
  577. }
  578. if (!this._eventMap[eventNameToWrap].has(cb)) {
  579. return nativeRemoveEventListener.apply(this, arguments);
  580. }
  581. const unwrappedCb = this._eventMap[eventNameToWrap].get(cb);
  582. this._eventMap[eventNameToWrap].delete(cb);
  583. if (this._eventMap[eventNameToWrap].size === 0) {
  584. delete this._eventMap[eventNameToWrap];
  585. }
  586. if (Object.keys(this._eventMap).length === 0) {
  587. delete this._eventMap;
  588. }
  589. return nativeRemoveEventListener.apply(this, [nativeEventName,
  590. unwrappedCb
  591. ]);
  592. };
  593. Object.defineProperty(proto, 'on' + eventNameToWrap, {
  594. get() {
  595. return this['_on' + eventNameToWrap];
  596. },
  597. set(cb) {
  598. if (this['_on' + eventNameToWrap]) {
  599. this.removeEventListener(eventNameToWrap,
  600. this['_on' + eventNameToWrap]);
  601. delete this['_on' + eventNameToWrap];
  602. }
  603. if (cb) {
  604. this.addEventListener(eventNameToWrap,
  605. this['_on' + eventNameToWrap] = cb);
  606. }
  607. },
  608. enumerable: true,
  609. configurable: true
  610. });
  611. }
  612. function disableLog(bool) {
  613. if (typeof bool !== 'boolean') {
  614. return new Error('Argument type: ' + typeof bool +
  615. '. Please use a boolean.');
  616. }
  617. logDisabled_ = bool;
  618. return (bool) ? 'adapter.js logging disabled' :
  619. 'adapter.js logging enabled';
  620. }
  621. /**
  622. * Disable or enable deprecation warnings
  623. * @param {!boolean} bool set to true to disable warnings.
  624. */
  625. function disableWarnings(bool) {
  626. if (typeof bool !== 'boolean') {
  627. return new Error('Argument type: ' + typeof bool +
  628. '. Please use a boolean.');
  629. }
  630. deprecationWarnings_ = !bool;
  631. return 'adapter.js deprecation warnings ' + (bool ? 'disabled' : 'enabled');
  632. }
  633. function log$1() {
  634. if (typeof window === 'object') {
  635. if (logDisabled_) {
  636. return;
  637. }
  638. if (typeof console !== 'undefined' && typeof console.log === 'function') {
  639. console.log.apply(console, arguments);
  640. }
  641. }
  642. }
  643. /**
  644. * Shows a deprecation warning suggesting the modern and spec-compatible API.
  645. */
  646. function deprecated(oldMethod, newMethod) {
  647. if (!deprecationWarnings_) {
  648. return;
  649. }
  650. console.warn(oldMethod + ' is deprecated, please use ' + newMethod +
  651. ' instead.');
  652. }
  653. /**
  654. * Browser detector.
  655. *
  656. * @return {object} result containing browser and version
  657. * properties.
  658. */
  659. function detectBrowser(window) {
  660. // Returned result object.
  661. const result = {
  662. browser: null,
  663. version: null
  664. };
  665. // Fail early if it's not a browser
  666. if (typeof window === 'undefined' || !window.navigator) {
  667. result.browser = 'Not a browser.';
  668. return result;
  669. }
  670. const {
  671. navigator
  672. } = window;
  673. if (navigator.mozGetUserMedia) { // Firefox.
  674. result.browser = 'firefox';
  675. result.version = extractVersion(navigator.userAgent,
  676. /Firefox\/(\d+)\./, 1);
  677. } else if (navigator.webkitGetUserMedia ||
  678. (window.isSecureContext === false && window.webkitRTCPeerConnection &&
  679. !window.RTCIceGatherer)) {
  680. // Chrome, Chromium, Webview, Opera.
  681. // Version matches Chrome/WebRTC version.
  682. // Chrome 74 removed webkitGetUserMedia on http as well so we need the
  683. // more complicated fallback to webkitRTCPeerConnection.
  684. result.browser = 'chrome';
  685. result.version = extractVersion(navigator.userAgent,
  686. /Chrom(e|ium)\/(\d+)\./, 2);
  687. } else if (navigator.mediaDevices &&
  688. navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) { // Edge.
  689. result.browser = 'edge';
  690. result.version = extractVersion(navigator.userAgent,
  691. /Edge\/(\d+).(\d+)$/, 2);
  692. } else if (window.RTCPeerConnection &&
  693. navigator.userAgent.match(/AppleWebKit\/(\d+)\./)) { // Safari.
  694. result.browser = 'safari';
  695. result.version = extractVersion(navigator.userAgent,
  696. /AppleWebKit\/(\d+)\./, 1);
  697. result.supportsUnifiedPlan = window.RTCRtpTransceiver &&
  698. 'currentDirection' in window.RTCRtpTransceiver.prototype;
  699. } else { // Default fallthrough: not supported.
  700. result.browser = 'Not a supported browser.';
  701. return result;
  702. }
  703. return result;
  704. }
  705. /**
  706. * Checks if something is an object.
  707. *
  708. * @param {*} val The something you want to check.
  709. * @return true if val is an object, false otherwise.
  710. */
  711. function isObject$1(val) {
  712. return Object.prototype.toString.call(val) === '[object Object]';
  713. }
  714. /**
  715. * Remove all empty objects and undefined values
  716. * from a nested object -- an enhanced and vanilla version
  717. * of Lodash's `compact`.
  718. */
  719. function compactObject(data) {
  720. if (!isObject$1(data)) {
  721. return data;
  722. }
  723. return Object.keys(data).reduce(function(accumulator, key) {
  724. const isObj = isObject$1(data[key]);
  725. const value = isObj ? compactObject(data[key]) : data[key];
  726. const isEmptyObject = isObj && !Object.keys(value).length;
  727. if (value === undefined || isEmptyObject) {
  728. return accumulator;
  729. }
  730. return Object.assign(accumulator, {
  731. [key]: value
  732. });
  733. }, {});
  734. }
  735. /* iterates the stats graph recursively. */
  736. function walkStats(stats, base, resultSet) {
  737. if (!base || resultSet.has(base.id)) {
  738. return;
  739. }
  740. resultSet.set(base.id, base);
  741. Object.keys(base).forEach(name => {
  742. if (name.endsWith('Id')) {
  743. walkStats(stats, stats.get(base[name]), resultSet);
  744. } else if (name.endsWith('Ids')) {
  745. base[name].forEach(id => {
  746. walkStats(stats, stats.get(id), resultSet);
  747. });
  748. }
  749. });
  750. }
  751. /* filter getStats for a sender/receiver track. */
  752. function filterStats(result, track, outbound) {
  753. const streamStatsType = outbound ? 'outbound-rtp' : 'inbound-rtp';
  754. const filteredResult = new Map();
  755. if (track === null) {
  756. return filteredResult;
  757. }
  758. const trackStats = [];
  759. result.forEach(value => {
  760. if (value.type === 'track' &&
  761. value.trackIdentifier === track.id) {
  762. trackStats.push(value);
  763. }
  764. });
  765. trackStats.forEach(trackStat => {
  766. result.forEach(stats => {
  767. if (stats.type === streamStatsType && stats.trackId === trackStat.id) {
  768. walkStats(result, stats, filteredResult);
  769. }
  770. });
  771. });
  772. return filteredResult;
  773. }
  774. /*
  775. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  776. *
  777. * Use of this source code is governed by a BSD-style license
  778. * that can be found in the LICENSE file in the root of the source
  779. * tree.
  780. */
  781. const logging = log$1;
  782. function shimGetUserMedia$3(window, browserDetails) {
  783. const navigator = window && window.navigator;
  784. if (!navigator.mediaDevices) {
  785. return;
  786. }
  787. const constraintsToChrome_ = function(c) {
  788. if (typeof c !== 'object' || c.mandatory || c.optional) {
  789. return c;
  790. }
  791. const cc = {};
  792. Object.keys(c).forEach(key => {
  793. if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
  794. return;
  795. }
  796. const r = (typeof c[key] === 'object') ? c[key] : {
  797. ideal: c[key]
  798. };
  799. if (r.exact !== undefined && typeof r.exact === 'number') {
  800. r.min = r.max = r.exact;
  801. }
  802. const oldname_ = function(prefix, name) {
  803. if (prefix) {
  804. return prefix + name.charAt(0).toUpperCase() + name.slice(1);
  805. }
  806. return (name === 'deviceId') ? 'sourceId' : name;
  807. };
  808. if (r.ideal !== undefined) {
  809. cc.optional = cc.optional || [];
  810. let oc = {};
  811. if (typeof r.ideal === 'number') {
  812. oc[oldname_('min', key)] = r.ideal;
  813. cc.optional.push(oc);
  814. oc = {};
  815. oc[oldname_('max', key)] = r.ideal;
  816. cc.optional.push(oc);
  817. } else {
  818. oc[oldname_('', key)] = r.ideal;
  819. cc.optional.push(oc);
  820. }
  821. }
  822. if (r.exact !== undefined && typeof r.exact !== 'number') {
  823. cc.mandatory = cc.mandatory || {};
  824. cc.mandatory[oldname_('', key)] = r.exact;
  825. } else {
  826. ['min', 'max'].forEach(mix => {
  827. if (r[mix] !== undefined) {
  828. cc.mandatory = cc.mandatory || {};
  829. cc.mandatory[oldname_(mix, key)] = r[mix];
  830. }
  831. });
  832. }
  833. });
  834. if (c.advanced) {
  835. cc.optional = (cc.optional || []).concat(c.advanced);
  836. }
  837. return cc;
  838. };
  839. const shimConstraints_ = function(constraints, func) {
  840. if (browserDetails.version >= 61) {
  841. return func(constraints);
  842. }
  843. constraints = JSON.parse(JSON.stringify(constraints));
  844. if (constraints && typeof constraints.audio === 'object') {
  845. const remap = function(obj, a, b) {
  846. if (a in obj && !(b in obj)) {
  847. obj[b] = obj[a];
  848. delete obj[a];
  849. }
  850. };
  851. constraints = JSON.parse(JSON.stringify(constraints));
  852. remap(constraints.audio, 'autoGainControl', 'googAutoGainControl');
  853. remap(constraints.audio, 'noiseSuppression', 'googNoiseSuppression');
  854. constraints.audio = constraintsToChrome_(constraints.audio);
  855. }
  856. if (constraints && typeof constraints.video === 'object') {
  857. // Shim facingMode for mobile & surface pro.
  858. let face = constraints.video.facingMode;
  859. face = face && ((typeof face === 'object') ? face : {
  860. ideal: face
  861. });
  862. const getSupportedFacingModeLies = browserDetails.version < 66;
  863. if ((face && (face.exact === 'user' || face.exact === 'environment' ||
  864. face.ideal === 'user' || face.ideal === 'environment')) &&
  865. !(navigator.mediaDevices.getSupportedConstraints &&
  866. navigator.mediaDevices.getSupportedConstraints().facingMode &&
  867. !getSupportedFacingModeLies)) {
  868. delete constraints.video.facingMode;
  869. let matches;
  870. if (face.exact === 'environment' || face.ideal === 'environment') {
  871. matches = ['back', 'rear'];
  872. } else if (face.exact === 'user' || face.ideal === 'user') {
  873. matches = ['front'];
  874. }
  875. if (matches) {
  876. // Look for matches in label, or use last cam for back (typical).
  877. return navigator.mediaDevices.enumerateDevices()
  878. .then(devices => {
  879. devices = devices.filter(d => d.kind === 'videoinput');
  880. let dev = devices.find(d => matches.some(match =>
  881. d.label.toLowerCase().includes(match)));
  882. if (!dev && devices.length && matches.includes('back')) {
  883. dev = devices[devices.length - 1]; // more likely the back cam
  884. }
  885. if (dev) {
  886. constraints.video.deviceId = face.exact ? {
  887. exact: dev.deviceId
  888. } : {
  889. ideal: dev.deviceId
  890. };
  891. }
  892. constraints.video = constraintsToChrome_(constraints.video);
  893. logging('chrome: ' + JSON.stringify(constraints));
  894. return func(constraints);
  895. });
  896. }
  897. }
  898. constraints.video = constraintsToChrome_(constraints.video);
  899. }
  900. logging('chrome: ' + JSON.stringify(constraints));
  901. return func(constraints);
  902. };
  903. const shimError_ = function(e) {
  904. if (browserDetails.version >= 64) {
  905. return e;
  906. }
  907. return {
  908. name: {
  909. PermissionDeniedError: 'NotAllowedError',
  910. PermissionDismissedError: 'NotAllowedError',
  911. InvalidStateError: 'NotAllowedError',
  912. DevicesNotFoundError: 'NotFoundError',
  913. ConstraintNotSatisfiedError: 'OverconstrainedError',
  914. TrackStartError: 'NotReadableError',
  915. MediaDeviceFailedDueToShutdown: 'NotAllowedError',
  916. MediaDeviceKillSwitchOn: 'NotAllowedError',
  917. TabCaptureError: 'AbortError',
  918. ScreenCaptureError: 'AbortError',
  919. DeviceCaptureError: 'AbortError'
  920. } [e.name] || e.name,
  921. message: e.message,
  922. constraint: e.constraint || e.constraintName,
  923. toString() {
  924. return this.name + (this.message && ': ') + this.message;
  925. }
  926. };
  927. };
  928. const getUserMedia_ = function(constraints, onSuccess, onError) {
  929. shimConstraints_(constraints, c => {
  930. navigator.webkitGetUserMedia(c, onSuccess, e => {
  931. if (onError) {
  932. onError(shimError_(e));
  933. }
  934. });
  935. });
  936. };
  937. navigator.getUserMedia = getUserMedia_.bind(navigator);
  938. // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia
  939. // function which returns a Promise, it does not accept spec-style
  940. // constraints.
  941. if (navigator.mediaDevices.getUserMedia) {
  942. const origGetUserMedia = navigator.mediaDevices.getUserMedia.
  943. bind(navigator.mediaDevices);
  944. navigator.mediaDevices.getUserMedia = function(cs) {
  945. return shimConstraints_(cs, c => origGetUserMedia(c).then(stream => {
  946. if (c.audio && !stream.getAudioTracks().length ||
  947. c.video && !stream.getVideoTracks().length) {
  948. stream.getTracks().forEach(track => {
  949. track.stop();
  950. });
  951. throw new DOMException('', 'NotFoundError');
  952. }
  953. return stream;
  954. }, e => Promise.reject(shimError_(e))));
  955. };
  956. }
  957. }
  958. /*
  959. * Copyright (c) 2018 The adapter.js project authors. All Rights Reserved.
  960. *
  961. * Use of this source code is governed by a BSD-style license
  962. * that can be found in the LICENSE file in the root of the source
  963. * tree.
  964. */
  965. function shimGetDisplayMedia$2(window, getSourceId) {
  966. if (window.navigator.mediaDevices &&
  967. 'getDisplayMedia' in window.navigator.mediaDevices) {
  968. return;
  969. }
  970. if (!(window.navigator.mediaDevices)) {
  971. return;
  972. }
  973. // getSourceId is a function that returns a promise resolving with
  974. // the sourceId of the screen/window/tab to be shared.
  975. if (typeof getSourceId !== 'function') {
  976. console.error('shimGetDisplayMedia: getSourceId argument is not ' +
  977. 'a function');
  978. return;
  979. }
  980. window.navigator.mediaDevices.getDisplayMedia =
  981. function getDisplayMedia(constraints) {
  982. return getSourceId(constraints)
  983. .then(sourceId => {
  984. const widthSpecified = constraints.video && constraints.video.width;
  985. const heightSpecified = constraints.video &&
  986. constraints.video.height;
  987. const frameRateSpecified = constraints.video &&
  988. constraints.video.frameRate;
  989. constraints.video = {
  990. mandatory: {
  991. chromeMediaSource: 'desktop',
  992. chromeMediaSourceId: sourceId,
  993. maxFrameRate: frameRateSpecified || 3
  994. }
  995. };
  996. if (widthSpecified) {
  997. constraints.video.mandatory.maxWidth = widthSpecified;
  998. }
  999. if (heightSpecified) {
  1000. constraints.video.mandatory.maxHeight = heightSpecified;
  1001. }
  1002. return window.navigator.mediaDevices.getUserMedia(constraints);
  1003. });
  1004. };
  1005. }
  1006. /*
  1007. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  1008. *
  1009. * Use of this source code is governed by a BSD-style license
  1010. * that can be found in the LICENSE file in the root of the source
  1011. * tree.
  1012. */
  1013. function shimMediaStream(window) {
  1014. window.MediaStream = window.MediaStream || window.webkitMediaStream;
  1015. }
  1016. function shimOnTrack$1(window) {
  1017. if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
  1018. window.RTCPeerConnection.prototype)) {
  1019. Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
  1020. get() {
  1021. return this._ontrack;
  1022. },
  1023. set(f) {
  1024. if (this._ontrack) {
  1025. this.removeEventListener('track', this._ontrack);
  1026. }
  1027. this.addEventListener('track', this._ontrack = f);
  1028. },
  1029. enumerable: true,
  1030. configurable: true
  1031. });
  1032. const origSetRemoteDescription =
  1033. window.RTCPeerConnection.prototype.setRemoteDescription;
  1034. window.RTCPeerConnection.prototype.setRemoteDescription =
  1035. function setRemoteDescription() {
  1036. if (!this._ontrackpoly) {
  1037. this._ontrackpoly = (e) => {
  1038. // onaddstream does not fire when a track is added to an existing
  1039. // stream. But stream.onaddtrack is implemented so we use that.
  1040. e.stream.addEventListener('addtrack', te => {
  1041. let receiver;
  1042. if (window.RTCPeerConnection.prototype.getReceivers) {
  1043. receiver = this.getReceivers()
  1044. .find(r => r.track && r.track.id === te.track.id);
  1045. } else {
  1046. receiver = {
  1047. track: te.track
  1048. };
  1049. }
  1050. const event = new Event('track');
  1051. event.track = te.track;
  1052. event.receiver = receiver;
  1053. event.transceiver = {
  1054. receiver
  1055. };
  1056. event.streams = [e.stream];
  1057. this.dispatchEvent(event);
  1058. });
  1059. e.stream.getTracks().forEach(track => {
  1060. let receiver;
  1061. if (window.RTCPeerConnection.prototype.getReceivers) {
  1062. receiver = this.getReceivers()
  1063. .find(r => r.track && r.track.id === track.id);
  1064. } else {
  1065. receiver = {
  1066. track
  1067. };
  1068. }
  1069. const event = new Event('track');
  1070. event.track = track;
  1071. event.receiver = receiver;
  1072. event.transceiver = {
  1073. receiver
  1074. };
  1075. event.streams = [e.stream];
  1076. this.dispatchEvent(event);
  1077. });
  1078. };
  1079. this.addEventListener('addstream', this._ontrackpoly);
  1080. }
  1081. return origSetRemoteDescription.apply(this, arguments);
  1082. };
  1083. } else {
  1084. // even if RTCRtpTransceiver is in window, it is only used and
  1085. // emitted in unified-plan. Unfortunately this means we need
  1086. // to unconditionally wrap the event.
  1087. wrapPeerConnectionEvent(window, 'track', e => {
  1088. if (!e.transceiver) {
  1089. Object.defineProperty(e, 'transceiver', {
  1090. value: {
  1091. receiver: e.receiver
  1092. }
  1093. });
  1094. }
  1095. return e;
  1096. });
  1097. }
  1098. }
  1099. function shimGetSendersWithDtmf(window) {
  1100. // Overrides addTrack/removeTrack, depends on shimAddTrackRemoveTrack.
  1101. if (typeof window === 'object' && window.RTCPeerConnection &&
  1102. !('getSenders' in window.RTCPeerConnection.prototype) &&
  1103. 'createDTMFSender' in window.RTCPeerConnection.prototype) {
  1104. const shimSenderWithDtmf = function(pc, track) {
  1105. return {
  1106. track,
  1107. get dtmf() {
  1108. if (this._dtmf === undefined) {
  1109. if (track.kind === 'audio') {
  1110. this._dtmf = pc.createDTMFSender(track);
  1111. } else {
  1112. this._dtmf = null;
  1113. }
  1114. }
  1115. return this._dtmf;
  1116. },
  1117. _pc: pc
  1118. };
  1119. };
  1120. // augment addTrack when getSenders is not available.
  1121. if (!window.RTCPeerConnection.prototype.getSenders) {
  1122. window.RTCPeerConnection.prototype.getSenders = function getSenders() {
  1123. this._senders = this._senders || [];
  1124. return this._senders.slice(); // return a copy of the internal state.
  1125. };
  1126. const origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  1127. window.RTCPeerConnection.prototype.addTrack =
  1128. function addTrack(track, stream) {
  1129. let sender = origAddTrack.apply(this, arguments);
  1130. if (!sender) {
  1131. sender = shimSenderWithDtmf(this, track);
  1132. this._senders.push(sender);
  1133. }
  1134. return sender;
  1135. };
  1136. const origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;
  1137. window.RTCPeerConnection.prototype.removeTrack =
  1138. function removeTrack(sender) {
  1139. origRemoveTrack.apply(this, arguments);
  1140. const idx = this._senders.indexOf(sender);
  1141. if (idx !== -1) {
  1142. this._senders.splice(idx, 1);
  1143. }
  1144. };
  1145. }
  1146. const origAddStream = window.RTCPeerConnection.prototype.addStream;
  1147. window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
  1148. this._senders = this._senders || [];
  1149. origAddStream.apply(this, [stream]);
  1150. stream.getTracks().forEach(track => {
  1151. this._senders.push(shimSenderWithDtmf(this, track));
  1152. });
  1153. };
  1154. const origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
  1155. window.RTCPeerConnection.prototype.removeStream =
  1156. function removeStream(stream) {
  1157. this._senders = this._senders || [];
  1158. origRemoveStream.apply(this, [stream]);
  1159. stream.getTracks().forEach(track => {
  1160. const sender = this._senders.find(s => s.track === track);
  1161. if (sender) { // remove sender
  1162. this._senders.splice(this._senders.indexOf(sender), 1);
  1163. }
  1164. });
  1165. };
  1166. } else if (typeof window === 'object' && window.RTCPeerConnection &&
  1167. 'getSenders' in window.RTCPeerConnection.prototype &&
  1168. 'createDTMFSender' in window.RTCPeerConnection.prototype &&
  1169. window.RTCRtpSender &&
  1170. !('dtmf' in window.RTCRtpSender.prototype)) {
  1171. const origGetSenders = window.RTCPeerConnection.prototype.getSenders;
  1172. window.RTCPeerConnection.prototype.getSenders = function getSenders() {
  1173. const senders = origGetSenders.apply(this, []);
  1174. senders.forEach(sender => sender._pc = this);
  1175. return senders;
  1176. };
  1177. Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', {
  1178. get() {
  1179. if (this._dtmf === undefined) {
  1180. if (this.track.kind === 'audio') {
  1181. this._dtmf = this._pc.createDTMFSender(this.track);
  1182. } else {
  1183. this._dtmf = null;
  1184. }
  1185. }
  1186. return this._dtmf;
  1187. }
  1188. });
  1189. }
  1190. }
  1191. function shimGetStats(window) {
  1192. if (!window.RTCPeerConnection) {
  1193. return;
  1194. }
  1195. const origGetStats = window.RTCPeerConnection.prototype.getStats;
  1196. window.RTCPeerConnection.prototype.getStats = function getStats() {
  1197. const [selector, onSucc, onErr] = arguments;
  1198. // If selector is a function then we are in the old style stats so just
  1199. // pass back the original getStats format to avoid breaking old users.
  1200. if (arguments.length > 0 && typeof selector === 'function') {
  1201. return origGetStats.apply(this, arguments);
  1202. }
  1203. // When spec-style getStats is supported, return those when called with
  1204. // either no arguments or the selector argument is null.
  1205. if (origGetStats.length === 0 && (arguments.length === 0 ||
  1206. typeof selector !== 'function')) {
  1207. return origGetStats.apply(this, []);
  1208. }
  1209. const fixChromeStats_ = function(response) {
  1210. const standardReport = {};
  1211. const reports = response.result();
  1212. reports.forEach(report => {
  1213. const standardStats = {
  1214. id: report.id,
  1215. timestamp: report.timestamp,
  1216. type: {
  1217. localcandidate: 'local-candidate',
  1218. remotecandidate: 'remote-candidate'
  1219. } [report.type] || report.type
  1220. };
  1221. report.names().forEach(name => {
  1222. standardStats[name] = report.stat(name);
  1223. });
  1224. standardReport[standardStats.id] = standardStats;
  1225. });
  1226. return standardReport;
  1227. };
  1228. // shim getStats with maplike support
  1229. const makeMapStats = function(stats) {
  1230. return new Map(Object.keys(stats).map(key => [key, stats[key]]));
  1231. };
  1232. if (arguments.length >= 2) {
  1233. const successCallbackWrapper_ = function(response) {
  1234. onSucc(makeMapStats(fixChromeStats_(response)));
  1235. };
  1236. return origGetStats.apply(this, [successCallbackWrapper_,
  1237. selector
  1238. ]);
  1239. }
  1240. // promise-support
  1241. return new Promise((resolve, reject) => {
  1242. origGetStats.apply(this, [
  1243. function(response) {
  1244. resolve(makeMapStats(fixChromeStats_(response)));
  1245. },
  1246. reject
  1247. ]);
  1248. }).then(onSucc, onErr);
  1249. };
  1250. }
  1251. function shimSenderReceiverGetStats(window) {
  1252. if (!(typeof window === 'object' && window.RTCPeerConnection &&
  1253. window.RTCRtpSender && window.RTCRtpReceiver)) {
  1254. return;
  1255. }
  1256. // shim sender stats.
  1257. if (!('getStats' in window.RTCRtpSender.prototype)) {
  1258. const origGetSenders = window.RTCPeerConnection.prototype.getSenders;
  1259. if (origGetSenders) {
  1260. window.RTCPeerConnection.prototype.getSenders = function getSenders() {
  1261. const senders = origGetSenders.apply(this, []);
  1262. senders.forEach(sender => sender._pc = this);
  1263. return senders;
  1264. };
  1265. }
  1266. const origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  1267. if (origAddTrack) {
  1268. window.RTCPeerConnection.prototype.addTrack = function addTrack() {
  1269. const sender = origAddTrack.apply(this, arguments);
  1270. sender._pc = this;
  1271. return sender;
  1272. };
  1273. }
  1274. window.RTCRtpSender.prototype.getStats = function getStats() {
  1275. const sender = this;
  1276. return this._pc.getStats().then(result =>
  1277. /* Note: this will include stats of all senders that
  1278. * send a track with the same id as sender.track as
  1279. * it is not possible to identify the RTCRtpSender.
  1280. */
  1281. filterStats(result, sender.track, true));
  1282. };
  1283. }
  1284. // shim receiver stats.
  1285. if (!('getStats' in window.RTCRtpReceiver.prototype)) {
  1286. const origGetReceivers = window.RTCPeerConnection.prototype.getReceivers;
  1287. if (origGetReceivers) {
  1288. window.RTCPeerConnection.prototype.getReceivers =
  1289. function getReceivers() {
  1290. const receivers = origGetReceivers.apply(this, []);
  1291. receivers.forEach(receiver => receiver._pc = this);
  1292. return receivers;
  1293. };
  1294. }
  1295. wrapPeerConnectionEvent(window, 'track', e => {
  1296. e.receiver._pc = e.srcElement;
  1297. return e;
  1298. });
  1299. window.RTCRtpReceiver.prototype.getStats = function getStats() {
  1300. const receiver = this;
  1301. return this._pc.getStats().then(result =>
  1302. filterStats(result, receiver.track, false));
  1303. };
  1304. }
  1305. if (!('getStats' in window.RTCRtpSender.prototype &&
  1306. 'getStats' in window.RTCRtpReceiver.prototype)) {
  1307. return;
  1308. }
  1309. // shim RTCPeerConnection.getStats(track).
  1310. const origGetStats = window.RTCPeerConnection.prototype.getStats;
  1311. window.RTCPeerConnection.prototype.getStats = function getStats() {
  1312. if (arguments.length > 0 &&
  1313. arguments[0] instanceof window.MediaStreamTrack) {
  1314. const track = arguments[0];
  1315. let sender;
  1316. let receiver;
  1317. let err;
  1318. this.getSenders().forEach(s => {
  1319. if (s.track === track) {
  1320. if (sender) {
  1321. err = true;
  1322. } else {
  1323. sender = s;
  1324. }
  1325. }
  1326. });
  1327. this.getReceivers().forEach(r => {
  1328. if (r.track === track) {
  1329. if (receiver) {
  1330. err = true;
  1331. } else {
  1332. receiver = r;
  1333. }
  1334. }
  1335. return r.track === track;
  1336. });
  1337. if (err || (sender && receiver)) {
  1338. return Promise.reject(new DOMException(
  1339. 'There are more than one sender or receiver for the track.',
  1340. 'InvalidAccessError'));
  1341. } else if (sender) {
  1342. return sender.getStats();
  1343. } else if (receiver) {
  1344. return receiver.getStats();
  1345. }
  1346. return Promise.reject(new DOMException(
  1347. 'There is no sender or receiver for the track.',
  1348. 'InvalidAccessError'));
  1349. }
  1350. return origGetStats.apply(this, arguments);
  1351. };
  1352. }
  1353. function shimAddTrackRemoveTrackWithNative(window) {
  1354. // shim addTrack/removeTrack with native variants in order to make
  1355. // the interactions with legacy getLocalStreams behave as in other browsers.
  1356. // Keeps a mapping stream.id => [stream, rtpsenders...]
  1357. window.RTCPeerConnection.prototype.getLocalStreams =
  1358. function getLocalStreams() {
  1359. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  1360. return Object.keys(this._shimmedLocalStreams)
  1361. .map(streamId => this._shimmedLocalStreams[streamId][0]);
  1362. };
  1363. const origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  1364. window.RTCPeerConnection.prototype.addTrack =
  1365. function addTrack(track, stream) {
  1366. if (!stream) {
  1367. return origAddTrack.apply(this, arguments);
  1368. }
  1369. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  1370. const sender = origAddTrack.apply(this, arguments);
  1371. if (!this._shimmedLocalStreams[stream.id]) {
  1372. this._shimmedLocalStreams[stream.id] = [stream, sender];
  1373. } else if (this._shimmedLocalStreams[stream.id].indexOf(sender) === -1) {
  1374. this._shimmedLocalStreams[stream.id].push(sender);
  1375. }
  1376. return sender;
  1377. };
  1378. const origAddStream = window.RTCPeerConnection.prototype.addStream;
  1379. window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
  1380. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  1381. stream.getTracks().forEach(track => {
  1382. const alreadyExists = this.getSenders().find(s => s.track === track);
  1383. if (alreadyExists) {
  1384. throw new DOMException('Track already exists.',
  1385. 'InvalidAccessError');
  1386. }
  1387. });
  1388. const existingSenders = this.getSenders();
  1389. origAddStream.apply(this, arguments);
  1390. const newSenders = this.getSenders()
  1391. .filter(newSender => existingSenders.indexOf(newSender) === -1);
  1392. this._shimmedLocalStreams[stream.id] = [stream].concat(newSenders);
  1393. };
  1394. const origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
  1395. window.RTCPeerConnection.prototype.removeStream =
  1396. function removeStream(stream) {
  1397. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  1398. delete this._shimmedLocalStreams[stream.id];
  1399. return origRemoveStream.apply(this, arguments);
  1400. };
  1401. const origRemoveTrack = window.RTCPeerConnection.prototype.removeTrack;
  1402. window.RTCPeerConnection.prototype.removeTrack =
  1403. function removeTrack(sender) {
  1404. this._shimmedLocalStreams = this._shimmedLocalStreams || {};
  1405. if (sender) {
  1406. Object.keys(this._shimmedLocalStreams).forEach(streamId => {
  1407. const idx = this._shimmedLocalStreams[streamId].indexOf(sender);
  1408. if (idx !== -1) {
  1409. this._shimmedLocalStreams[streamId].splice(idx, 1);
  1410. }
  1411. if (this._shimmedLocalStreams[streamId].length === 1) {
  1412. delete this._shimmedLocalStreams[streamId];
  1413. }
  1414. });
  1415. }
  1416. return origRemoveTrack.apply(this, arguments);
  1417. };
  1418. }
  1419. function shimAddTrackRemoveTrack(window, browserDetails) {
  1420. if (!window.RTCPeerConnection) {
  1421. return;
  1422. }
  1423. // shim addTrack and removeTrack.
  1424. if (window.RTCPeerConnection.prototype.addTrack &&
  1425. browserDetails.version >= 65) {
  1426. return shimAddTrackRemoveTrackWithNative(window);
  1427. }
  1428. // also shim pc.getLocalStreams when addTrack is shimmed
  1429. // to return the original streams.
  1430. const origGetLocalStreams = window.RTCPeerConnection.prototype
  1431. .getLocalStreams;
  1432. window.RTCPeerConnection.prototype.getLocalStreams =
  1433. function getLocalStreams() {
  1434. const nativeStreams = origGetLocalStreams.apply(this);
  1435. this._reverseStreams = this._reverseStreams || {};
  1436. return nativeStreams.map(stream => this._reverseStreams[stream.id]);
  1437. };
  1438. const origAddStream = window.RTCPeerConnection.prototype.addStream;
  1439. window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
  1440. this._streams = this._streams || {};
  1441. this._reverseStreams = this._reverseStreams || {};
  1442. stream.getTracks().forEach(track => {
  1443. const alreadyExists = this.getSenders().find(s => s.track === track);
  1444. if (alreadyExists) {
  1445. throw new DOMException('Track already exists.',
  1446. 'InvalidAccessError');
  1447. }
  1448. });
  1449. // Add identity mapping for consistency with addTrack.
  1450. // Unless this is being used with a stream from addTrack.
  1451. if (!this._reverseStreams[stream.id]) {
  1452. const newStream = new window.MediaStream(stream.getTracks());
  1453. this._streams[stream.id] = newStream;
  1454. this._reverseStreams[newStream.id] = stream;
  1455. stream = newStream;
  1456. }
  1457. origAddStream.apply(this, [stream]);
  1458. };
  1459. const origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
  1460. window.RTCPeerConnection.prototype.removeStream =
  1461. function removeStream(stream) {
  1462. this._streams = this._streams || {};
  1463. this._reverseStreams = this._reverseStreams || {};
  1464. origRemoveStream.apply(this, [(this._streams[stream.id] || stream)]);
  1465. delete this._reverseStreams[(this._streams[stream.id] ?
  1466. this._streams[stream.id].id : stream.id)];
  1467. delete this._streams[stream.id];
  1468. };
  1469. window.RTCPeerConnection.prototype.addTrack =
  1470. function addTrack(track, stream) {
  1471. if (this.signalingState === 'closed') {
  1472. throw new DOMException(
  1473. 'The RTCPeerConnection\'s signalingState is \'closed\'.',
  1474. 'InvalidStateError');
  1475. }
  1476. const streams = [].slice.call(arguments, 1);
  1477. if (streams.length !== 1 ||
  1478. !streams[0].getTracks().find(t => t === track)) {
  1479. // this is not fully correct but all we can manage without
  1480. // [[associated MediaStreams]] internal slot.
  1481. throw new DOMException(
  1482. 'The adapter.js addTrack polyfill only supports a single ' +
  1483. ' stream which is associated with the specified track.',
  1484. 'NotSupportedError');
  1485. }
  1486. const alreadyExists = this.getSenders().find(s => s.track === track);
  1487. if (alreadyExists) {
  1488. throw new DOMException('Track already exists.',
  1489. 'InvalidAccessError');
  1490. }
  1491. this._streams = this._streams || {};
  1492. this._reverseStreams = this._reverseStreams || {};
  1493. const oldStream = this._streams[stream.id];
  1494. if (oldStream) {
  1495. // this is using odd Chrome behaviour, use with caution:
  1496. // https://bugs.chromium.org/p/webrtc/issues/detail?id=7815
  1497. // Note: we rely on the high-level addTrack/dtmf shim to
  1498. // create the sender with a dtmf sender.
  1499. oldStream.addTrack(track);
  1500. // Trigger ONN async.
  1501. Promise.resolve().then(() => {
  1502. this.dispatchEvent(new Event('negotiationneeded'));
  1503. });
  1504. } else {
  1505. const newStream = new window.MediaStream([track]);
  1506. this._streams[stream.id] = newStream;
  1507. this._reverseStreams[newStream.id] = stream;
  1508. this.addStream(newStream);
  1509. }
  1510. return this.getSenders().find(s => s.track === track);
  1511. };
  1512. // replace the internal stream id with the external one and
  1513. // vice versa.
  1514. function replaceInternalStreamId(pc, description) {
  1515. let sdp = description.sdp;
  1516. Object.keys(pc._reverseStreams || []).forEach(internalId => {
  1517. const externalStream = pc._reverseStreams[internalId];
  1518. const internalStream = pc._streams[externalStream.id];
  1519. sdp = sdp.replace(new RegExp(internalStream.id, 'g'),
  1520. externalStream.id);
  1521. });
  1522. return new RTCSessionDescription({
  1523. type: description.type,
  1524. sdp
  1525. });
  1526. }
  1527. function replaceExternalStreamId(pc, description) {
  1528. let sdp = description.sdp;
  1529. Object.keys(pc._reverseStreams || []).forEach(internalId => {
  1530. const externalStream = pc._reverseStreams[internalId];
  1531. const internalStream = pc._streams[externalStream.id];
  1532. sdp = sdp.replace(new RegExp(externalStream.id, 'g'),
  1533. internalStream.id);
  1534. });
  1535. return new RTCSessionDescription({
  1536. type: description.type,
  1537. sdp
  1538. });
  1539. }
  1540. ['createOffer', 'createAnswer'].forEach(function(method) {
  1541. const nativeMethod = window.RTCPeerConnection.prototype[method];
  1542. const methodObj = {
  1543. [method]() {
  1544. const args = arguments;
  1545. const isLegacyCall = arguments.length &&
  1546. typeof arguments[0] === 'function';
  1547. if (isLegacyCall) {
  1548. return nativeMethod.apply(this, [
  1549. (description) => {
  1550. const desc = replaceInternalStreamId(this, description);
  1551. args[0].apply(null, [desc]);
  1552. },
  1553. (err) => {
  1554. if (args[1]) {
  1555. args[1].apply(null, err);
  1556. }
  1557. },
  1558. arguments[2]
  1559. ]);
  1560. }
  1561. return nativeMethod.apply(this, arguments)
  1562. .then(description => replaceInternalStreamId(this, description));
  1563. }
  1564. };
  1565. window.RTCPeerConnection.prototype[method] = methodObj[method];
  1566. });
  1567. const origSetLocalDescription =
  1568. window.RTCPeerConnection.prototype.setLocalDescription;
  1569. window.RTCPeerConnection.prototype.setLocalDescription =
  1570. function setLocalDescription() {
  1571. if (!arguments.length || !arguments[0].type) {
  1572. return origSetLocalDescription.apply(this, arguments);
  1573. }
  1574. arguments[0] = replaceExternalStreamId(this, arguments[0]);
  1575. return origSetLocalDescription.apply(this, arguments);
  1576. };
  1577. // TODO: mangle getStats: https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamstats-streamidentifier
  1578. const origLocalDescription = Object.getOwnPropertyDescriptor(
  1579. window.RTCPeerConnection.prototype, 'localDescription');
  1580. Object.defineProperty(window.RTCPeerConnection.prototype,
  1581. 'localDescription', {
  1582. get() {
  1583. const description = origLocalDescription.get.apply(this);
  1584. if (description.type === '') {
  1585. return description;
  1586. }
  1587. return replaceInternalStreamId(this, description);
  1588. }
  1589. });
  1590. window.RTCPeerConnection.prototype.removeTrack =
  1591. function removeTrack(sender) {
  1592. if (this.signalingState === 'closed') {
  1593. throw new DOMException(
  1594. 'The RTCPeerConnection\'s signalingState is \'closed\'.',
  1595. 'InvalidStateError');
  1596. }
  1597. // We can not yet check for sender instanceof RTCRtpSender
  1598. // since we shim RTPSender. So we check if sender._pc is set.
  1599. if (!sender._pc) {
  1600. throw new DOMException('Argument 1 of RTCPeerConnection.removeTrack ' +
  1601. 'does not implement interface RTCRtpSender.', 'TypeError');
  1602. }
  1603. const isLocal = sender._pc === this;
  1604. if (!isLocal) {
  1605. throw new DOMException('Sender was not created by this connection.',
  1606. 'InvalidAccessError');
  1607. }
  1608. // Search for the native stream the senders track belongs to.
  1609. this._streams = this._streams || {};
  1610. let stream;
  1611. Object.keys(this._streams).forEach(streamid => {
  1612. const hasTrack = this._streams[streamid].getTracks()
  1613. .find(track => sender.track === track);
  1614. if (hasTrack) {
  1615. stream = this._streams[streamid];
  1616. }
  1617. });
  1618. if (stream) {
  1619. if (stream.getTracks().length === 1) {
  1620. // if this is the last track of the stream, remove the stream. This
  1621. // takes care of any shimmed _senders.
  1622. this.removeStream(this._reverseStreams[stream.id]);
  1623. } else {
  1624. // relying on the same odd chrome behaviour as above.
  1625. stream.removeTrack(sender.track);
  1626. }
  1627. this.dispatchEvent(new Event('negotiationneeded'));
  1628. }
  1629. };
  1630. }
  1631. function shimPeerConnection$2(window, browserDetails) {
  1632. if (!window.RTCPeerConnection && window.webkitRTCPeerConnection) {
  1633. // very basic support for old versions.
  1634. window.RTCPeerConnection = window.webkitRTCPeerConnection;
  1635. }
  1636. if (!window.RTCPeerConnection) {
  1637. return;
  1638. }
  1639. // shim implicit creation of RTCSessionDescription/RTCIceCandidate
  1640. if (browserDetails.version < 53) {
  1641. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
  1642. .forEach(function(method) {
  1643. const nativeMethod = window.RTCPeerConnection.prototype[method];
  1644. const methodObj = {
  1645. [method]() {
  1646. arguments[0] = new((method === 'addIceCandidate') ?
  1647. window.RTCIceCandidate :
  1648. window.RTCSessionDescription)(arguments[0]);
  1649. return nativeMethod.apply(this, arguments);
  1650. }
  1651. };
  1652. window.RTCPeerConnection.prototype[method] = methodObj[method];
  1653. });
  1654. }
  1655. }
  1656. // Attempt to fix ONN in plan-b mode.
  1657. function fixNegotiationNeeded(window, browserDetails) {
  1658. wrapPeerConnectionEvent(window, 'negotiationneeded', e => {
  1659. const pc = e.target;
  1660. if (browserDetails.version < 72 || (pc.getConfiguration &&
  1661. pc.getConfiguration().sdpSemantics === 'plan-b')) {
  1662. if (pc.signalingState !== 'stable') {
  1663. return;
  1664. }
  1665. }
  1666. return e;
  1667. });
  1668. }
  1669. var chromeShim = /*#__PURE__*/ Object.freeze({
  1670. __proto__: null,
  1671. shimMediaStream: shimMediaStream,
  1672. shimOnTrack: shimOnTrack$1,
  1673. shimGetSendersWithDtmf: shimGetSendersWithDtmf,
  1674. shimGetStats: shimGetStats,
  1675. shimSenderReceiverGetStats: shimSenderReceiverGetStats,
  1676. shimAddTrackRemoveTrackWithNative: shimAddTrackRemoveTrackWithNative,
  1677. shimAddTrackRemoveTrack: shimAddTrackRemoveTrack,
  1678. shimPeerConnection: shimPeerConnection$2,
  1679. fixNegotiationNeeded: fixNegotiationNeeded,
  1680. shimGetUserMedia: shimGetUserMedia$3,
  1681. shimGetDisplayMedia: shimGetDisplayMedia$2
  1682. });
  1683. /*
  1684. * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
  1685. *
  1686. * Use of this source code is governed by a BSD-style license
  1687. * that can be found in the LICENSE file in the root of the source
  1688. * tree.
  1689. */
  1690. // Edge does not like
  1691. // 1) stun: filtered after 14393 unless ?transport=udp is present
  1692. // 2) turn: that does not have all of turn:host:port?transport=udp
  1693. // 3) turn: with ipv6 addresses
  1694. // 4) turn: occurring muliple times
  1695. function filterIceServers$1(iceServers, edgeVersion) {
  1696. let hasTurn = false;
  1697. iceServers = JSON.parse(JSON.stringify(iceServers));
  1698. return iceServers.filter(server => {
  1699. if (server && (server.urls || server.url)) {
  1700. let urls = server.urls || server.url;
  1701. if (server.url && !server.urls) {
  1702. deprecated('RTCIceServer.url', 'RTCIceServer.urls');
  1703. }
  1704. const isString = typeof urls === 'string';
  1705. if (isString) {
  1706. urls = [urls];
  1707. }
  1708. urls = urls.filter(url => {
  1709. // filter STUN unconditionally.
  1710. if (url.indexOf('stun:') === 0) {
  1711. return false;
  1712. }
  1713. const validTurn = url.startsWith('turn') &&
  1714. !url.startsWith('turn:[') &&
  1715. url.includes('transport=udp');
  1716. if (validTurn && !hasTurn) {
  1717. hasTurn = true;
  1718. return true;
  1719. }
  1720. return validTurn && !hasTurn;
  1721. });
  1722. delete server.url;
  1723. server.urls = isString ? urls[0] : urls;
  1724. return !!urls.length;
  1725. }
  1726. });
  1727. }
  1728. function createCommonjsModule(fn) {
  1729. var module = {
  1730. exports: {}
  1731. };
  1732. return fn(module, module.exports), module.exports;
  1733. }
  1734. /* eslint-env node */
  1735. var sdp = createCommonjsModule(function(module) {
  1736. // SDP helpers.
  1737. var SDPUtils = {};
  1738. // Generate an alphanumeric identifier for cname or mids.
  1739. // TODO: use UUIDs instead? https://gist.github.com/jed/982883
  1740. SDPUtils.generateIdentifier = function() {
  1741. return Math.random().toString(36).substr(2, 10);
  1742. };
  1743. // The RTCP CNAME used by all peerconnections from the same JS.
  1744. SDPUtils.localCName = SDPUtils.generateIdentifier();
  1745. // Splits SDP into lines, dealing with both CRLF and LF.
  1746. SDPUtils.splitLines = function(blob) {
  1747. return blob.trim().split('\n').map(function(line) {
  1748. return line.trim();
  1749. });
  1750. };
  1751. // Splits SDP into sessionpart and mediasections. Ensures CRLF.
  1752. SDPUtils.splitSections = function(blob) {
  1753. var parts = blob.split('\nm=');
  1754. return parts.map(function(part, index) {
  1755. return (index > 0 ? 'm=' + part : part).trim() + '\r\n';
  1756. });
  1757. };
  1758. // returns the session description.
  1759. SDPUtils.getDescription = function(blob) {
  1760. var sections = SDPUtils.splitSections(blob);
  1761. return sections && sections[0];
  1762. };
  1763. // returns the individual media sections.
  1764. SDPUtils.getMediaSections = function(blob) {
  1765. var sections = SDPUtils.splitSections(blob);
  1766. sections.shift();
  1767. return sections;
  1768. };
  1769. // Returns lines that start with a certain prefix.
  1770. SDPUtils.matchPrefix = function(blob, prefix) {
  1771. return SDPUtils.splitLines(blob).filter(function(line) {
  1772. return line.indexOf(prefix) === 0;
  1773. });
  1774. };
  1775. // Parses an ICE candidate line. Sample input:
  1776. // candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8
  1777. // rport 55996"
  1778. SDPUtils.parseCandidate = function(line) {
  1779. var parts;
  1780. // Parse both variants.
  1781. if (line.indexOf('a=candidate:') === 0) {
  1782. parts = line.substring(12).split(' ');
  1783. } else {
  1784. parts = line.substring(10).split(' ');
  1785. }
  1786. var candidate = {
  1787. foundation: parts[0],
  1788. component: parseInt(parts[1], 10),
  1789. protocol: parts[2].toLowerCase(),
  1790. priority: parseInt(parts[3], 10),
  1791. ip: parts[4],
  1792. address: parts[4], // address is an alias for ip.
  1793. port: parseInt(parts[5], 10),
  1794. // skip parts[6] == 'typ'
  1795. type: parts[7]
  1796. };
  1797. for (var i = 8; i < parts.length; i += 2) {
  1798. switch (parts[i]) {
  1799. case 'raddr':
  1800. candidate.relatedAddress = parts[i + 1];
  1801. break;
  1802. case 'rport':
  1803. candidate.relatedPort = parseInt(parts[i + 1], 10);
  1804. break;
  1805. case 'tcptype':
  1806. candidate.tcpType = parts[i + 1];
  1807. break;
  1808. case 'ufrag':
  1809. candidate.ufrag = parts[i + 1]; // for backward compability.
  1810. candidate.usernameFragment = parts[i + 1];
  1811. break;
  1812. default: // extension handling, in particular ufrag
  1813. candidate[parts[i]] = parts[i + 1];
  1814. break;
  1815. }
  1816. }
  1817. return candidate;
  1818. };
  1819. // Translates a candidate object into SDP candidate attribute.
  1820. SDPUtils.writeCandidate = function(candidate) {
  1821. var sdp = [];
  1822. sdp.push(candidate.foundation);
  1823. sdp.push(candidate.component);
  1824. sdp.push(candidate.protocol.toUpperCase());
  1825. sdp.push(candidate.priority);
  1826. sdp.push(candidate.address || candidate.ip);
  1827. sdp.push(candidate.port);
  1828. var type = candidate.type;
  1829. sdp.push('typ');
  1830. sdp.push(type);
  1831. if (type !== 'host' && candidate.relatedAddress &&
  1832. candidate.relatedPort) {
  1833. sdp.push('raddr');
  1834. sdp.push(candidate.relatedAddress);
  1835. sdp.push('rport');
  1836. sdp.push(candidate.relatedPort);
  1837. }
  1838. if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') {
  1839. sdp.push('tcptype');
  1840. sdp.push(candidate.tcpType);
  1841. }
  1842. if (candidate.usernameFragment || candidate.ufrag) {
  1843. sdp.push('ufrag');
  1844. sdp.push(candidate.usernameFragment || candidate.ufrag);
  1845. }
  1846. return 'candidate:' + sdp.join(' ');
  1847. };
  1848. // Parses an ice-options line, returns an array of option tags.
  1849. // a=ice-options:foo bar
  1850. SDPUtils.parseIceOptions = function(line) {
  1851. return line.substr(14).split(' ');
  1852. };
  1853. // Parses an rtpmap line, returns RTCRtpCoddecParameters. Sample input:
  1854. // a=rtpmap:111 opus/48000/2
  1855. SDPUtils.parseRtpMap = function(line) {
  1856. var parts = line.substr(9).split(' ');
  1857. var parsed = {
  1858. payloadType: parseInt(parts.shift(), 10) // was: id
  1859. };
  1860. parts = parts[0].split('/');
  1861. parsed.name = parts[0];
  1862. parsed.clockRate = parseInt(parts[1], 10); // was: clockrate
  1863. parsed.channels = parts.length === 3 ? parseInt(parts[2], 10) : 1;
  1864. // legacy alias, got renamed back to channels in ORTC.
  1865. parsed.numChannels = parsed.channels;
  1866. return parsed;
  1867. };
  1868. // Generate an a=rtpmap line from RTCRtpCodecCapability or
  1869. // RTCRtpCodecParameters.
  1870. SDPUtils.writeRtpMap = function(codec) {
  1871. var pt = codec.payloadType;
  1872. if (codec.preferredPayloadType !== undefined) {
  1873. pt = codec.preferredPayloadType;
  1874. }
  1875. var channels = codec.channels || codec.numChannels || 1;
  1876. return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate +
  1877. (channels !== 1 ? '/' + channels : '') + '\r\n';
  1878. };
  1879. // Parses an a=extmap line (headerextension from RFC 5285). Sample input:
  1880. // a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  1881. // a=extmap:2/sendonly urn:ietf:params:rtp-hdrext:toffset
  1882. SDPUtils.parseExtmap = function(line) {
  1883. var parts = line.substr(9).split(' ');
  1884. return {
  1885. id: parseInt(parts[0], 10),
  1886. direction: parts[0].indexOf('/') > 0 ? parts[0].split('/')[1] : 'sendrecv',
  1887. uri: parts[1]
  1888. };
  1889. };
  1890. // Generates a=extmap line from RTCRtpHeaderExtensionParameters or
  1891. // RTCRtpHeaderExtension.
  1892. SDPUtils.writeExtmap = function(headerExtension) {
  1893. return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) +
  1894. (headerExtension.direction && headerExtension.direction !== 'sendrecv' ?
  1895. '/' + headerExtension.direction :
  1896. '') +
  1897. ' ' + headerExtension.uri + '\r\n';
  1898. };
  1899. // Parses an ftmp line, returns dictionary. Sample input:
  1900. // a=fmtp:96 vbr=on;cng=on
  1901. // Also deals with vbr=on; cng=on
  1902. SDPUtils.parseFmtp = function(line) {
  1903. var parsed = {};
  1904. var kv;
  1905. var parts = line.substr(line.indexOf(' ') + 1).split(';');
  1906. for (var j = 0; j < parts.length; j++) {
  1907. kv = parts[j].trim().split('=');
  1908. parsed[kv[0].trim()] = kv[1];
  1909. }
  1910. return parsed;
  1911. };
  1912. // Generates an a=ftmp line from RTCRtpCodecCapability or RTCRtpCodecParameters.
  1913. SDPUtils.writeFmtp = function(codec) {
  1914. var line = '';
  1915. var pt = codec.payloadType;
  1916. if (codec.preferredPayloadType !== undefined) {
  1917. pt = codec.preferredPayloadType;
  1918. }
  1919. if (codec.parameters && Object.keys(codec.parameters).length) {
  1920. var params = [];
  1921. Object.keys(codec.parameters).forEach(function(param) {
  1922. if (codec.parameters[param]) {
  1923. params.push(param + '=' + codec.parameters[param]);
  1924. } else {
  1925. params.push(param);
  1926. }
  1927. });
  1928. line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\r\n';
  1929. }
  1930. return line;
  1931. };
  1932. // Parses an rtcp-fb line, returns RTCPRtcpFeedback object. Sample input:
  1933. // a=rtcp-fb:98 nack rpsi
  1934. SDPUtils.parseRtcpFb = function(line) {
  1935. var parts = line.substr(line.indexOf(' ') + 1).split(' ');
  1936. return {
  1937. type: parts.shift(),
  1938. parameter: parts.join(' ')
  1939. };
  1940. };
  1941. // Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters.
  1942. SDPUtils.writeRtcpFb = function(codec) {
  1943. var lines = '';
  1944. var pt = codec.payloadType;
  1945. if (codec.preferredPayloadType !== undefined) {
  1946. pt = codec.preferredPayloadType;
  1947. }
  1948. if (codec.rtcpFeedback && codec.rtcpFeedback.length) {
  1949. // FIXME: special handling for trr-int?
  1950. codec.rtcpFeedback.forEach(function(fb) {
  1951. lines += 'a=rtcp-fb:' + pt + ' ' + fb.type +
  1952. (fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') +
  1953. '\r\n';
  1954. });
  1955. }
  1956. return lines;
  1957. };
  1958. // Parses an RFC 5576 ssrc media attribute. Sample input:
  1959. // a=ssrc:3735928559 cname:something
  1960. SDPUtils.parseSsrcMedia = function(line) {
  1961. var sp = line.indexOf(' ');
  1962. var parts = {
  1963. ssrc: parseInt(line.substr(7, sp - 7), 10)
  1964. };
  1965. var colon = line.indexOf(':', sp);
  1966. if (colon > -1) {
  1967. parts.attribute = line.substr(sp + 1, colon - sp - 1);
  1968. parts.value = line.substr(colon + 1);
  1969. } else {
  1970. parts.attribute = line.substr(sp + 1);
  1971. }
  1972. return parts;
  1973. };
  1974. SDPUtils.parseSsrcGroup = function(line) {
  1975. var parts = line.substr(13).split(' ');
  1976. return {
  1977. semantics: parts.shift(),
  1978. ssrcs: parts.map(function(ssrc) {
  1979. return parseInt(ssrc, 10);
  1980. })
  1981. };
  1982. };
  1983. // Extracts the MID (RFC 5888) from a media section.
  1984. // returns the MID or undefined if no mid line was found.
  1985. SDPUtils.getMid = function(mediaSection) {
  1986. var mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:')[0];
  1987. if (mid) {
  1988. return mid.substr(6);
  1989. }
  1990. };
  1991. SDPUtils.parseFingerprint = function(line) {
  1992. var parts = line.substr(14).split(' ');
  1993. return {
  1994. algorithm: parts[0].toLowerCase(), // algorithm is case-sensitive in Edge.
  1995. value: parts[1]
  1996. };
  1997. };
  1998. // Extracts DTLS parameters from SDP media section or sessionpart.
  1999. // FIXME: for consistency with other functions this should only
  2000. // get the fingerprint line as input. See also getIceParameters.
  2001. SDPUtils.getDtlsParameters = function(mediaSection, sessionpart) {
  2002. var lines = SDPUtils.matchPrefix(mediaSection + sessionpart,
  2003. 'a=fingerprint:');
  2004. // Note: a=setup line is ignored since we use the 'auto' role.
  2005. // Note2: 'algorithm' is not case sensitive except in Edge.
  2006. return {
  2007. role: 'auto',
  2008. fingerprints: lines.map(SDPUtils.parseFingerprint)
  2009. };
  2010. };
  2011. // Serializes DTLS parameters to SDP.
  2012. SDPUtils.writeDtlsParameters = function(params, setupType) {
  2013. var sdp = 'a=setup:' + setupType + '\r\n';
  2014. params.fingerprints.forEach(function(fp) {
  2015. sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n';
  2016. });
  2017. return sdp;
  2018. };
  2019. // Parses a=crypto lines into
  2020. // https://rawgit.com/aboba/edgertc/master/msortc-rs4.html#dictionary-rtcsrtpsdesparameters-members
  2021. SDPUtils.parseCryptoLine = function(line) {
  2022. var parts = line.substr(9).split(' ');
  2023. return {
  2024. tag: parseInt(parts[0], 10),
  2025. cryptoSuite: parts[1],
  2026. keyParams: parts[2],
  2027. sessionParams: parts.slice(3),
  2028. };
  2029. };
  2030. SDPUtils.writeCryptoLine = function(parameters) {
  2031. return 'a=crypto:' + parameters.tag + ' ' +
  2032. parameters.cryptoSuite + ' ' +
  2033. (typeof parameters.keyParams === 'object' ?
  2034. SDPUtils.writeCryptoKeyParams(parameters.keyParams) :
  2035. parameters.keyParams) +
  2036. (parameters.sessionParams ? ' ' + parameters.sessionParams.join(' ') : '') +
  2037. '\r\n';
  2038. };
  2039. // Parses the crypto key parameters into
  2040. // https://rawgit.com/aboba/edgertc/master/msortc-rs4.html#rtcsrtpkeyparam*
  2041. SDPUtils.parseCryptoKeyParams = function(keyParams) {
  2042. if (keyParams.indexOf('inline:') !== 0) {
  2043. return null;
  2044. }
  2045. var parts = keyParams.substr(7).split('|');
  2046. return {
  2047. keyMethod: 'inline',
  2048. keySalt: parts[0],
  2049. lifeTime: parts[1],
  2050. mkiValue: parts[2] ? parts[2].split(':')[0] : undefined,
  2051. mkiLength: parts[2] ? parts[2].split(':')[1] : undefined,
  2052. };
  2053. };
  2054. SDPUtils.writeCryptoKeyParams = function(keyParams) {
  2055. return keyParams.keyMethod + ':' +
  2056. keyParams.keySalt +
  2057. (keyParams.lifeTime ? '|' + keyParams.lifeTime : '') +
  2058. (keyParams.mkiValue && keyParams.mkiLength ?
  2059. '|' + keyParams.mkiValue + ':' + keyParams.mkiLength :
  2060. '');
  2061. };
  2062. // Extracts all SDES paramters.
  2063. SDPUtils.getCryptoParameters = function(mediaSection, sessionpart) {
  2064. var lines = SDPUtils.matchPrefix(mediaSection + sessionpart,
  2065. 'a=crypto:');
  2066. return lines.map(SDPUtils.parseCryptoLine);
  2067. };
  2068. // Parses ICE information from SDP media section or sessionpart.
  2069. // FIXME: for consistency with other functions this should only
  2070. // get the ice-ufrag and ice-pwd lines as input.
  2071. SDPUtils.getIceParameters = function(mediaSection, sessionpart) {
  2072. var ufrag = SDPUtils.matchPrefix(mediaSection + sessionpart,
  2073. 'a=ice-ufrag:')[0];
  2074. var pwd = SDPUtils.matchPrefix(mediaSection + sessionpart,
  2075. 'a=ice-pwd:')[0];
  2076. if (!(ufrag && pwd)) {
  2077. return null;
  2078. }
  2079. return {
  2080. usernameFragment: ufrag.substr(12),
  2081. password: pwd.substr(10),
  2082. };
  2083. };
  2084. // Serializes ICE parameters to SDP.
  2085. SDPUtils.writeIceParameters = function(params) {
  2086. return 'a=ice-ufrag:' + params.usernameFragment + '\r\n' +
  2087. 'a=ice-pwd:' + params.password + '\r\n';
  2088. };
  2089. // Parses the SDP media section and returns RTCRtpParameters.
  2090. SDPUtils.parseRtpParameters = function(mediaSection) {
  2091. var description = {
  2092. codecs: [],
  2093. headerExtensions: [],
  2094. fecMechanisms: [],
  2095. rtcp: []
  2096. };
  2097. var lines = SDPUtils.splitLines(mediaSection);
  2098. var mline = lines[0].split(' ');
  2099. for (var i = 3; i < mline.length; i++) { // find all codecs from mline[3..]
  2100. var pt = mline[i];
  2101. var rtpmapline = SDPUtils.matchPrefix(
  2102. mediaSection, 'a=rtpmap:' + pt + ' ')[0];
  2103. if (rtpmapline) {
  2104. var codec = SDPUtils.parseRtpMap(rtpmapline);
  2105. var fmtps = SDPUtils.matchPrefix(
  2106. mediaSection, 'a=fmtp:' + pt + ' ');
  2107. // Only the first a=fmtp:<pt> is considered.
  2108. codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {};
  2109. codec.rtcpFeedback = SDPUtils.matchPrefix(
  2110. mediaSection, 'a=rtcp-fb:' + pt + ' ')
  2111. .map(SDPUtils.parseRtcpFb);
  2112. description.codecs.push(codec);
  2113. // parse FEC mechanisms from rtpmap lines.
  2114. switch (codec.name.toUpperCase()) {
  2115. case 'RED':
  2116. case 'ULPFEC':
  2117. description.fecMechanisms.push(codec.name.toUpperCase());
  2118. break;
  2119. }
  2120. }
  2121. }
  2122. SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(function(line) {
  2123. description.headerExtensions.push(SDPUtils.parseExtmap(line));
  2124. });
  2125. // FIXME: parse rtcp.
  2126. return description;
  2127. };
  2128. // Generates parts of the SDP media section describing the capabilities /
  2129. // parameters.
  2130. SDPUtils.writeRtpDescription = function(kind, caps) {
  2131. var sdp = '';
  2132. // Build the mline.
  2133. sdp += 'm=' + kind + ' ';
  2134. sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs.
  2135. sdp += ' UDP/TLS/RTP/SAVPF ';
  2136. sdp += caps.codecs.map(function(codec) {
  2137. if (codec.preferredPayloadType !== undefined) {
  2138. return codec.preferredPayloadType;
  2139. }
  2140. return codec.payloadType;
  2141. }).join(' ') + '\r\n';
  2142. sdp += 'c=IN IP4 0.0.0.0\r\n';
  2143. sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n';
  2144. // Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb.
  2145. caps.codecs.forEach(function(codec) {
  2146. sdp += SDPUtils.writeRtpMap(codec);
  2147. sdp += SDPUtils.writeFmtp(codec);
  2148. sdp += SDPUtils.writeRtcpFb(codec);
  2149. });
  2150. var maxptime = 0;
  2151. caps.codecs.forEach(function(codec) {
  2152. if (codec.maxptime > maxptime) {
  2153. maxptime = codec.maxptime;
  2154. }
  2155. });
  2156. if (maxptime > 0) {
  2157. sdp += 'a=maxptime:' + maxptime + '\r\n';
  2158. }
  2159. sdp += 'a=rtcp-mux\r\n';
  2160. if (caps.headerExtensions) {
  2161. caps.headerExtensions.forEach(function(extension) {
  2162. sdp += SDPUtils.writeExtmap(extension);
  2163. });
  2164. }
  2165. // FIXME: write fecMechanisms.
  2166. return sdp;
  2167. };
  2168. // Parses the SDP media section and returns an array of
  2169. // RTCRtpEncodingParameters.
  2170. SDPUtils.parseRtpEncodingParameters = function(mediaSection) {
  2171. var encodingParameters = [];
  2172. var description = SDPUtils.parseRtpParameters(mediaSection);
  2173. var hasRed = description.fecMechanisms.indexOf('RED') !== -1;
  2174. var hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1;
  2175. // filter a=ssrc:... cname:, ignore PlanB-msid
  2176. var ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  2177. .map(function(line) {
  2178. return SDPUtils.parseSsrcMedia(line);
  2179. })
  2180. .filter(function(parts) {
  2181. return parts.attribute === 'cname';
  2182. });
  2183. var primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc;
  2184. var secondarySsrc;
  2185. var flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID')
  2186. .map(function(line) {
  2187. var parts = line.substr(17).split(' ');
  2188. return parts.map(function(part) {
  2189. return parseInt(part, 10);
  2190. });
  2191. });
  2192. if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) {
  2193. secondarySsrc = flows[0][1];
  2194. }
  2195. description.codecs.forEach(function(codec) {
  2196. if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) {
  2197. var encParam = {
  2198. ssrc: primarySsrc,
  2199. codecPayloadType: parseInt(codec.parameters.apt, 10)
  2200. };
  2201. if (primarySsrc && secondarySsrc) {
  2202. encParam.rtx = {
  2203. ssrc: secondarySsrc
  2204. };
  2205. }
  2206. encodingParameters.push(encParam);
  2207. if (hasRed) {
  2208. encParam = JSON.parse(JSON.stringify(encParam));
  2209. encParam.fec = {
  2210. ssrc: primarySsrc,
  2211. mechanism: hasUlpfec ? 'red+ulpfec' : 'red'
  2212. };
  2213. encodingParameters.push(encParam);
  2214. }
  2215. }
  2216. });
  2217. if (encodingParameters.length === 0 && primarySsrc) {
  2218. encodingParameters.push({
  2219. ssrc: primarySsrc
  2220. });
  2221. }
  2222. // we support both b=AS and b=TIAS but interpret AS as TIAS.
  2223. var bandwidth = SDPUtils.matchPrefix(mediaSection, 'b=');
  2224. if (bandwidth.length) {
  2225. if (bandwidth[0].indexOf('b=TIAS:') === 0) {
  2226. bandwidth = parseInt(bandwidth[0].substr(7), 10);
  2227. } else if (bandwidth[0].indexOf('b=AS:') === 0) {
  2228. // use formula from JSEP to convert b=AS to TIAS value.
  2229. bandwidth = parseInt(bandwidth[0].substr(5), 10) * 1000 * 0.95 -
  2230. (50 * 40 * 8);
  2231. } else {
  2232. bandwidth = undefined;
  2233. }
  2234. encodingParameters.forEach(function(params) {
  2235. params.maxBitrate = bandwidth;
  2236. });
  2237. }
  2238. return encodingParameters;
  2239. };
  2240. // parses http://draft.ortc.org/#rtcrtcpparameters*
  2241. SDPUtils.parseRtcpParameters = function(mediaSection) {
  2242. var rtcpParameters = {};
  2243. // Gets the first SSRC. Note tha with RTX there might be multiple
  2244. // SSRCs.
  2245. var remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  2246. .map(function(line) {
  2247. return SDPUtils.parseSsrcMedia(line);
  2248. })
  2249. .filter(function(obj) {
  2250. return obj.attribute === 'cname';
  2251. })[0];
  2252. if (remoteSsrc) {
  2253. rtcpParameters.cname = remoteSsrc.value;
  2254. rtcpParameters.ssrc = remoteSsrc.ssrc;
  2255. }
  2256. // Edge uses the compound attribute instead of reducedSize
  2257. // compound is !reducedSize
  2258. var rsize = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-rsize');
  2259. rtcpParameters.reducedSize = rsize.length > 0;
  2260. rtcpParameters.compound = rsize.length === 0;
  2261. // parses the rtcp-mux attrіbute.
  2262. // Note that Edge does not support unmuxed RTCP.
  2263. var mux = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-mux');
  2264. rtcpParameters.mux = mux.length > 0;
  2265. return rtcpParameters;
  2266. };
  2267. // parses either a=msid: or a=ssrc:... msid lines and returns
  2268. // the id of the MediaStream and MediaStreamTrack.
  2269. SDPUtils.parseMsid = function(mediaSection) {
  2270. var parts;
  2271. var spec = SDPUtils.matchPrefix(mediaSection, 'a=msid:');
  2272. if (spec.length === 1) {
  2273. parts = spec[0].substr(7).split(' ');
  2274. return {
  2275. stream: parts[0],
  2276. track: parts[1]
  2277. };
  2278. }
  2279. var planB = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  2280. .map(function(line) {
  2281. return SDPUtils.parseSsrcMedia(line);
  2282. })
  2283. .filter(function(msidParts) {
  2284. return msidParts.attribute === 'msid';
  2285. });
  2286. if (planB.length > 0) {
  2287. parts = planB[0].value.split(' ');
  2288. return {
  2289. stream: parts[0],
  2290. track: parts[1]
  2291. };
  2292. }
  2293. };
  2294. // SCTP
  2295. // parses draft-ietf-mmusic-sctp-sdp-26 first and falls back
  2296. // to draft-ietf-mmusic-sctp-sdp-05
  2297. SDPUtils.parseSctpDescription = function(mediaSection) {
  2298. var mline = SDPUtils.parseMLine(mediaSection);
  2299. var maxSizeLine = SDPUtils.matchPrefix(mediaSection, 'a=max-message-size:');
  2300. var maxMessageSize;
  2301. if (maxSizeLine.length > 0) {
  2302. maxMessageSize = parseInt(maxSizeLine[0].substr(19), 10);
  2303. }
  2304. if (isNaN(maxMessageSize)) {
  2305. maxMessageSize = 65536;
  2306. }
  2307. var sctpPort = SDPUtils.matchPrefix(mediaSection, 'a=sctp-port:');
  2308. if (sctpPort.length > 0) {
  2309. return {
  2310. port: parseInt(sctpPort[0].substr(12), 10),
  2311. protocol: mline.fmt,
  2312. maxMessageSize: maxMessageSize
  2313. };
  2314. }
  2315. var sctpMapLines = SDPUtils.matchPrefix(mediaSection, 'a=sctpmap:');
  2316. if (sctpMapLines.length > 0) {
  2317. var parts = SDPUtils.matchPrefix(mediaSection, 'a=sctpmap:')[0]
  2318. .substr(10)
  2319. .split(' ');
  2320. return {
  2321. port: parseInt(parts[0], 10),
  2322. protocol: parts[1],
  2323. maxMessageSize: maxMessageSize
  2324. };
  2325. }
  2326. };
  2327. // SCTP
  2328. // outputs the draft-ietf-mmusic-sctp-sdp-26 version that all browsers
  2329. // support by now receiving in this format, unless we originally parsed
  2330. // as the draft-ietf-mmusic-sctp-sdp-05 format (indicated by the m-line
  2331. // protocol of DTLS/SCTP -- without UDP/ or TCP/)
  2332. SDPUtils.writeSctpDescription = function(media, sctp) {
  2333. var output = [];
  2334. if (media.protocol !== 'DTLS/SCTP') {
  2335. output = [
  2336. 'm=' + media.kind + ' 9 ' + media.protocol + ' ' + sctp.protocol + '\r\n',
  2337. 'c=IN IP4 0.0.0.0\r\n',
  2338. 'a=sctp-port:' + sctp.port + '\r\n'
  2339. ];
  2340. } else {
  2341. output = [
  2342. 'm=' + media.kind + ' 9 ' + media.protocol + ' ' + sctp.port + '\r\n',
  2343. 'c=IN IP4 0.0.0.0\r\n',
  2344. 'a=sctpmap:' + sctp.port + ' ' + sctp.protocol + ' 65535\r\n'
  2345. ];
  2346. }
  2347. if (sctp.maxMessageSize !== undefined) {
  2348. output.push('a=max-message-size:' + sctp.maxMessageSize + '\r\n');
  2349. }
  2350. return output.join('');
  2351. };
  2352. // Generate a session ID for SDP.
  2353. // https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-20#section-5.2.1
  2354. // recommends using a cryptographically random +ve 64-bit value
  2355. // but right now this should be acceptable and within the right range
  2356. SDPUtils.generateSessionId = function() {
  2357. return Math.random().toString().substr(2, 21);
  2358. };
  2359. // Write boilder plate for start of SDP
  2360. // sessId argument is optional - if not supplied it will
  2361. // be generated randomly
  2362. // sessVersion is optional and defaults to 2
  2363. // sessUser is optional and defaults to 'thisisadapterortc'
  2364. SDPUtils.writeSessionBoilerplate = function(sessId, sessVer, sessUser) {
  2365. var sessionId;
  2366. var version = sessVer !== undefined ? sessVer : 2;
  2367. if (sessId) {
  2368. sessionId = sessId;
  2369. } else {
  2370. sessionId = SDPUtils.generateSessionId();
  2371. }
  2372. var user = sessUser || 'thisisadapterortc';
  2373. // FIXME: sess-id should be an NTP timestamp.
  2374. return 'v=0\r\n' +
  2375. 'o=' + user + ' ' + sessionId + ' ' + version +
  2376. ' IN IP4 127.0.0.1\r\n' +
  2377. 's=-\r\n' +
  2378. 't=0 0\r\n';
  2379. };
  2380. SDPUtils.writeMediaSection = function(transceiver, caps, type, stream) {
  2381. var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps);
  2382. // Map ICE parameters (ufrag, pwd) to SDP.
  2383. sdp += SDPUtils.writeIceParameters(
  2384. transceiver.iceGatherer.getLocalParameters());
  2385. // Map DTLS parameters to SDP.
  2386. sdp += SDPUtils.writeDtlsParameters(
  2387. transceiver.dtlsTransport.getLocalParameters(),
  2388. type === 'offer' ? 'actpass' : 'active');
  2389. sdp += 'a=mid:' + transceiver.mid + '\r\n';
  2390. if (transceiver.direction) {
  2391. sdp += 'a=' + transceiver.direction + '\r\n';
  2392. } else if (transceiver.rtpSender && transceiver.rtpReceiver) {
  2393. sdp += 'a=sendrecv\r\n';
  2394. } else if (transceiver.rtpSender) {
  2395. sdp += 'a=sendonly\r\n';
  2396. } else if (transceiver.rtpReceiver) {
  2397. sdp += 'a=recvonly\r\n';
  2398. } else {
  2399. sdp += 'a=inactive\r\n';
  2400. }
  2401. if (transceiver.rtpSender) {
  2402. // spec.
  2403. var msid = 'msid:' + stream.id + ' ' +
  2404. transceiver.rtpSender.track.id + '\r\n';
  2405. sdp += 'a=' + msid;
  2406. // for Chrome.
  2407. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  2408. ' ' + msid;
  2409. if (transceiver.sendEncodingParameters[0].rtx) {
  2410. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  2411. ' ' + msid;
  2412. sdp += 'a=ssrc-group:FID ' +
  2413. transceiver.sendEncodingParameters[0].ssrc + ' ' +
  2414. transceiver.sendEncodingParameters[0].rtx.ssrc +
  2415. '\r\n';
  2416. }
  2417. }
  2418. // FIXME: this should be written by writeRtpDescription.
  2419. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  2420. ' cname:' + SDPUtils.localCName + '\r\n';
  2421. if (transceiver.rtpSender && transceiver.sendEncodingParameters[0].rtx) {
  2422. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  2423. ' cname:' + SDPUtils.localCName + '\r\n';
  2424. }
  2425. return sdp;
  2426. };
  2427. // Gets the direction from the mediaSection or the sessionpart.
  2428. SDPUtils.getDirection = function(mediaSection, sessionpart) {
  2429. // Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv.
  2430. var lines = SDPUtils.splitLines(mediaSection);
  2431. for (var i = 0; i < lines.length; i++) {
  2432. switch (lines[i]) {
  2433. case 'a=sendrecv':
  2434. case 'a=sendonly':
  2435. case 'a=recvonly':
  2436. case 'a=inactive':
  2437. return lines[i].substr(2);
  2438. // FIXME: What should happen here?
  2439. }
  2440. }
  2441. if (sessionpart) {
  2442. return SDPUtils.getDirection(sessionpart);
  2443. }
  2444. return 'sendrecv';
  2445. };
  2446. SDPUtils.getKind = function(mediaSection) {
  2447. var lines = SDPUtils.splitLines(mediaSection);
  2448. var mline = lines[0].split(' ');
  2449. return mline[0].substr(2);
  2450. };
  2451. SDPUtils.isRejected = function(mediaSection) {
  2452. return mediaSection.split(' ', 2)[1] === '0';
  2453. };
  2454. SDPUtils.parseMLine = function(mediaSection) {
  2455. var lines = SDPUtils.splitLines(mediaSection);
  2456. var parts = lines[0].substr(2).split(' ');
  2457. return {
  2458. kind: parts[0],
  2459. port: parseInt(parts[1], 10),
  2460. protocol: parts[2],
  2461. fmt: parts.slice(3).join(' ')
  2462. };
  2463. };
  2464. SDPUtils.parseOLine = function(mediaSection) {
  2465. var line = SDPUtils.matchPrefix(mediaSection, 'o=')[0];
  2466. var parts = line.substr(2).split(' ');
  2467. return {
  2468. username: parts[0],
  2469. sessionId: parts[1],
  2470. sessionVersion: parseInt(parts[2], 10),
  2471. netType: parts[3],
  2472. addressType: parts[4],
  2473. address: parts[5]
  2474. };
  2475. };
  2476. // a very naive interpretation of a valid SDP.
  2477. SDPUtils.isValidSDP = function(blob) {
  2478. if (typeof blob !== 'string' || blob.length === 0) {
  2479. return false;
  2480. }
  2481. var lines = SDPUtils.splitLines(blob);
  2482. for (var i = 0; i < lines.length; i++) {
  2483. if (lines[i].length < 2 || lines[i].charAt(1) !== '=') {
  2484. return false;
  2485. }
  2486. // TODO: check the modifier a bit more.
  2487. }
  2488. return true;
  2489. };
  2490. // Expose public methods.
  2491. {
  2492. module.exports = SDPUtils;
  2493. }
  2494. });
  2495. /*
  2496. * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
  2497. *
  2498. * Use of this source code is governed by a BSD-style license
  2499. * that can be found in the LICENSE file in the root of the source
  2500. * tree.
  2501. */
  2502. function fixStatsType(stat) {
  2503. return {
  2504. inboundrtp: 'inbound-rtp',
  2505. outboundrtp: 'outbound-rtp',
  2506. candidatepair: 'candidate-pair',
  2507. localcandidate: 'local-candidate',
  2508. remotecandidate: 'remote-candidate'
  2509. } [stat.type] || stat.type;
  2510. }
  2511. function writeMediaSection(transceiver, caps, type, stream, dtlsRole) {
  2512. var sdp$1 = sdp.writeRtpDescription(transceiver.kind, caps);
  2513. // Map ICE parameters (ufrag, pwd) to SDP.
  2514. sdp$1 += sdp.writeIceParameters(
  2515. transceiver.iceGatherer.getLocalParameters());
  2516. // Map DTLS parameters to SDP.
  2517. sdp$1 += sdp.writeDtlsParameters(
  2518. transceiver.dtlsTransport.getLocalParameters(),
  2519. type === 'offer' ? 'actpass' : dtlsRole || 'active');
  2520. sdp$1 += 'a=mid:' + transceiver.mid + '\r\n';
  2521. if (transceiver.rtpSender && transceiver.rtpReceiver) {
  2522. sdp$1 += 'a=sendrecv\r\n';
  2523. } else if (transceiver.rtpSender) {
  2524. sdp$1 += 'a=sendonly\r\n';
  2525. } else if (transceiver.rtpReceiver) {
  2526. sdp$1 += 'a=recvonly\r\n';
  2527. } else {
  2528. sdp$1 += 'a=inactive\r\n';
  2529. }
  2530. if (transceiver.rtpSender) {
  2531. var trackId = transceiver.rtpSender._initialTrackId ||
  2532. transceiver.rtpSender.track.id;
  2533. transceiver.rtpSender._initialTrackId = trackId;
  2534. // spec.
  2535. var msid = 'msid:' + (stream ? stream.id : '-') + ' ' +
  2536. trackId + '\r\n';
  2537. sdp$1 += 'a=' + msid;
  2538. // for Chrome. Legacy should no longer be required.
  2539. sdp$1 += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  2540. ' ' + msid;
  2541. // RTX
  2542. if (transceiver.sendEncodingParameters[0].rtx) {
  2543. sdp$1 += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  2544. ' ' + msid;
  2545. sdp$1 += 'a=ssrc-group:FID ' +
  2546. transceiver.sendEncodingParameters[0].ssrc + ' ' +
  2547. transceiver.sendEncodingParameters[0].rtx.ssrc +
  2548. '\r\n';
  2549. }
  2550. }
  2551. // FIXME: this should be written by writeRtpDescription.
  2552. sdp$1 += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  2553. ' cname:' + sdp.localCName + '\r\n';
  2554. if (transceiver.rtpSender && transceiver.sendEncodingParameters[0].rtx) {
  2555. sdp$1 += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  2556. ' cname:' + sdp.localCName + '\r\n';
  2557. }
  2558. return sdp$1;
  2559. }
  2560. // Edge does not like
  2561. // 1) stun: filtered after 14393 unless ?transport=udp is present
  2562. // 2) turn: that does not have all of turn:host:port?transport=udp
  2563. // 3) turn: with ipv6 addresses
  2564. // 4) turn: occurring muliple times
  2565. function filterIceServers(iceServers, edgeVersion) {
  2566. var hasTurn = false;
  2567. iceServers = JSON.parse(JSON.stringify(iceServers));
  2568. return iceServers.filter(function(server) {
  2569. if (server && (server.urls || server.url)) {
  2570. var urls = server.urls || server.url;
  2571. if (server.url && !server.urls) {
  2572. console.warn('RTCIceServer.url is deprecated! Use urls instead.');
  2573. }
  2574. var isString = typeof urls === 'string';
  2575. if (isString) {
  2576. urls = [urls];
  2577. }
  2578. urls = urls.filter(function(url) {
  2579. var validTurn = url.indexOf('turn:') === 0 &&
  2580. url.indexOf('transport=udp') !== -1 &&
  2581. url.indexOf('turn:[') === -1 &&
  2582. !hasTurn;
  2583. if (validTurn) {
  2584. hasTurn = true;
  2585. return true;
  2586. }
  2587. return url.indexOf('stun:') === 0 && edgeVersion >= 14393 &&
  2588. url.indexOf('?transport=udp') === -1;
  2589. });
  2590. delete server.url;
  2591. server.urls = isString ? urls[0] : urls;
  2592. return !!urls.length;
  2593. }
  2594. });
  2595. }
  2596. // Determines the intersection of local and remote capabilities.
  2597. function getCommonCapabilities(localCapabilities, remoteCapabilities) {
  2598. var commonCapabilities = {
  2599. codecs: [],
  2600. headerExtensions: [],
  2601. fecMechanisms: []
  2602. };
  2603. var findCodecByPayloadType = function(pt, codecs) {
  2604. pt = parseInt(pt, 10);
  2605. for (var i = 0; i < codecs.length; i++) {
  2606. if (codecs[i].payloadType === pt ||
  2607. codecs[i].preferredPayloadType === pt) {
  2608. return codecs[i];
  2609. }
  2610. }
  2611. };
  2612. var rtxCapabilityMatches = function(lRtx, rRtx, lCodecs, rCodecs) {
  2613. var lCodec = findCodecByPayloadType(lRtx.parameters.apt, lCodecs);
  2614. var rCodec = findCodecByPayloadType(rRtx.parameters.apt, rCodecs);
  2615. return lCodec && rCodec &&
  2616. lCodec.name.toLowerCase() === rCodec.name.toLowerCase();
  2617. };
  2618. localCapabilities.codecs.forEach(function(lCodec) {
  2619. for (var i = 0; i < remoteCapabilities.codecs.length; i++) {
  2620. var rCodec = remoteCapabilities.codecs[i];
  2621. if (lCodec.name.toLowerCase() === rCodec.name.toLowerCase() &&
  2622. lCodec.clockRate === rCodec.clockRate) {
  2623. if (lCodec.name.toLowerCase() === 'rtx' &&
  2624. lCodec.parameters && rCodec.parameters.apt) {
  2625. // for RTX we need to find the local rtx that has a apt
  2626. // which points to the same local codec as the remote one.
  2627. if (!rtxCapabilityMatches(lCodec, rCodec,
  2628. localCapabilities.codecs, remoteCapabilities.codecs)) {
  2629. continue;
  2630. }
  2631. }
  2632. rCodec = JSON.parse(JSON.stringify(rCodec)); // deepcopy
  2633. // number of channels is the highest common number of channels
  2634. rCodec.numChannels = Math.min(lCodec.numChannels,
  2635. rCodec.numChannels);
  2636. // push rCodec so we reply with offerer payload type
  2637. commonCapabilities.codecs.push(rCodec);
  2638. // determine common feedback mechanisms
  2639. rCodec.rtcpFeedback = rCodec.rtcpFeedback.filter(function(fb) {
  2640. for (var j = 0; j < lCodec.rtcpFeedback.length; j++) {
  2641. if (lCodec.rtcpFeedback[j].type === fb.type &&
  2642. lCodec.rtcpFeedback[j].parameter === fb.parameter) {
  2643. return true;
  2644. }
  2645. }
  2646. return false;
  2647. });
  2648. // FIXME: also need to determine .parameters
  2649. // see https://github.com/openpeer/ortc/issues/569
  2650. break;
  2651. }
  2652. }
  2653. });
  2654. localCapabilities.headerExtensions.forEach(function(lHeaderExtension) {
  2655. for (var i = 0; i < remoteCapabilities.headerExtensions.length; i++) {
  2656. var rHeaderExtension = remoteCapabilities.headerExtensions[i];
  2657. if (lHeaderExtension.uri === rHeaderExtension.uri) {
  2658. commonCapabilities.headerExtensions.push(rHeaderExtension);
  2659. break;
  2660. }
  2661. }
  2662. });
  2663. // FIXME: fecMechanisms
  2664. return commonCapabilities;
  2665. }
  2666. // is action=setLocalDescription with type allowed in signalingState
  2667. function isActionAllowedInSignalingState(action, type, signalingState) {
  2668. return {
  2669. offer: {
  2670. setLocalDescription: ['stable', 'have-local-offer'],
  2671. setRemoteDescription: ['stable', 'have-remote-offer']
  2672. },
  2673. answer: {
  2674. setLocalDescription: ['have-remote-offer', 'have-local-pranswer'],
  2675. setRemoteDescription: ['have-local-offer', 'have-remote-pranswer']
  2676. }
  2677. } [type][action].indexOf(signalingState) !== -1;
  2678. }
  2679. function maybeAddCandidate(iceTransport, candidate) {
  2680. // Edge's internal representation adds some fields therefore
  2681. // not all fieldѕ are taken into account.
  2682. var alreadyAdded = iceTransport.getRemoteCandidates()
  2683. .find(function(remoteCandidate) {
  2684. return candidate.foundation === remoteCandidate.foundation &&
  2685. candidate.ip === remoteCandidate.ip &&
  2686. candidate.port === remoteCandidate.port &&
  2687. candidate.priority === remoteCandidate.priority &&
  2688. candidate.protocol === remoteCandidate.protocol &&
  2689. candidate.type === remoteCandidate.type;
  2690. });
  2691. if (!alreadyAdded) {
  2692. iceTransport.addRemoteCandidate(candidate);
  2693. }
  2694. return !alreadyAdded;
  2695. }
  2696. function makeError(name, description) {
  2697. var e = new Error(description);
  2698. e.name = name;
  2699. // legacy error codes from https://heycam.github.io/webidl/#idl-DOMException-error-names
  2700. e.code = {
  2701. NotSupportedError: 9,
  2702. InvalidStateError: 11,
  2703. InvalidAccessError: 15,
  2704. TypeError: undefined,
  2705. OperationError: undefined
  2706. } [name];
  2707. return e;
  2708. }
  2709. var rtcpeerconnection = function(window, edgeVersion) {
  2710. // https://w3c.github.io/mediacapture-main/#mediastream
  2711. // Helper function to add the track to the stream and
  2712. // dispatch the event ourselves.
  2713. function addTrackToStreamAndFireEvent(track, stream) {
  2714. stream.addTrack(track);
  2715. stream.dispatchEvent(new window.MediaStreamTrackEvent('addtrack', {
  2716. track: track
  2717. }));
  2718. }
  2719. function removeTrackFromStreamAndFireEvent(track, stream) {
  2720. stream.removeTrack(track);
  2721. stream.dispatchEvent(new window.MediaStreamTrackEvent('removetrack', {
  2722. track: track
  2723. }));
  2724. }
  2725. function fireAddTrack(pc, track, receiver, streams) {
  2726. var trackEvent = new Event('track');
  2727. trackEvent.track = track;
  2728. trackEvent.receiver = receiver;
  2729. trackEvent.transceiver = {
  2730. receiver: receiver
  2731. };
  2732. trackEvent.streams = streams;
  2733. window.setTimeout(function() {
  2734. pc._dispatchEvent('track', trackEvent);
  2735. });
  2736. }
  2737. var RTCPeerConnection = function(config) {
  2738. var pc = this;
  2739. var _eventTarget = document.createDocumentFragment();
  2740. ['addEventListener', 'removeEventListener', 'dispatchEvent']
  2741. .forEach(function(method) {
  2742. pc[method] = _eventTarget[method].bind(_eventTarget);
  2743. });
  2744. this.canTrickleIceCandidates = null;
  2745. this.needNegotiation = false;
  2746. this.localStreams = [];
  2747. this.remoteStreams = [];
  2748. this._localDescription = null;
  2749. this._remoteDescription = null;
  2750. this.signalingState = 'stable';
  2751. this.iceConnectionState = 'new';
  2752. this.connectionState = 'new';
  2753. this.iceGatheringState = 'new';
  2754. config = JSON.parse(JSON.stringify(config || {}));
  2755. this.usingBundle = config.bundlePolicy === 'max-bundle';
  2756. if (config.rtcpMuxPolicy === 'negotiate') {
  2757. throw (makeError('NotSupportedError',
  2758. 'rtcpMuxPolicy \'negotiate\' is not supported'));
  2759. } else if (!config.rtcpMuxPolicy) {
  2760. config.rtcpMuxPolicy = 'require';
  2761. }
  2762. switch (config.iceTransportPolicy) {
  2763. case 'all':
  2764. case 'relay':
  2765. break;
  2766. default:
  2767. config.iceTransportPolicy = 'all';
  2768. break;
  2769. }
  2770. switch (config.bundlePolicy) {
  2771. case 'balanced':
  2772. case 'max-compat':
  2773. case 'max-bundle':
  2774. break;
  2775. default:
  2776. config.bundlePolicy = 'balanced';
  2777. break;
  2778. }
  2779. config.iceServers = filterIceServers(config.iceServers || [], edgeVersion);
  2780. this._iceGatherers = [];
  2781. if (config.iceCandidatePoolSize) {
  2782. for (var i = config.iceCandidatePoolSize; i > 0; i--) {
  2783. this._iceGatherers.push(new window.RTCIceGatherer({
  2784. iceServers: config.iceServers,
  2785. gatherPolicy: config.iceTransportPolicy
  2786. }));
  2787. }
  2788. } else {
  2789. config.iceCandidatePoolSize = 0;
  2790. }
  2791. this._config = config;
  2792. // per-track iceGathers, iceTransports, dtlsTransports, rtpSenders, ...
  2793. // everything that is needed to describe a SDP m-line.
  2794. this.transceivers = [];
  2795. this._sdpSessionId = sdp.generateSessionId();
  2796. this._sdpSessionVersion = 0;
  2797. this._dtlsRole = undefined; // role for a=setup to use in answers.
  2798. this._isClosed = false;
  2799. };
  2800. Object.defineProperty(RTCPeerConnection.prototype, 'localDescription', {
  2801. configurable: true,
  2802. get: function() {
  2803. return this._localDescription;
  2804. }
  2805. });
  2806. Object.defineProperty(RTCPeerConnection.prototype, 'remoteDescription', {
  2807. configurable: true,
  2808. get: function() {
  2809. return this._remoteDescription;
  2810. }
  2811. });
  2812. // set up event handlers on prototype
  2813. RTCPeerConnection.prototype.onicecandidate = null;
  2814. RTCPeerConnection.prototype.onaddstream = null;
  2815. RTCPeerConnection.prototype.ontrack = null;
  2816. RTCPeerConnection.prototype.onremovestream = null;
  2817. RTCPeerConnection.prototype.onsignalingstatechange = null;
  2818. RTCPeerConnection.prototype.oniceconnectionstatechange = null;
  2819. RTCPeerConnection.prototype.onconnectionstatechange = null;
  2820. RTCPeerConnection.prototype.onicegatheringstatechange = null;
  2821. RTCPeerConnection.prototype.onnegotiationneeded = null;
  2822. RTCPeerConnection.prototype.ondatachannel = null;
  2823. RTCPeerConnection.prototype._dispatchEvent = function(name, event) {
  2824. if (this._isClosed) {
  2825. return;
  2826. }
  2827. this.dispatchEvent(event);
  2828. if (typeof this['on' + name] === 'function') {
  2829. this['on' + name](event);
  2830. }
  2831. };
  2832. RTCPeerConnection.prototype._emitGatheringStateChange = function() {
  2833. var event = new Event('icegatheringstatechange');
  2834. this._dispatchEvent('icegatheringstatechange', event);
  2835. };
  2836. RTCPeerConnection.prototype.getConfiguration = function() {
  2837. return this._config;
  2838. };
  2839. RTCPeerConnection.prototype.getLocalStreams = function() {
  2840. return this.localStreams;
  2841. };
  2842. RTCPeerConnection.prototype.getRemoteStreams = function() {
  2843. return this.remoteStreams;
  2844. };
  2845. // internal helper to create a transceiver object.
  2846. // (which is not yet the same as the WebRTC 1.0 transceiver)
  2847. RTCPeerConnection.prototype._createTransceiver = function(kind, doNotAdd) {
  2848. var hasBundleTransport = this.transceivers.length > 0;
  2849. var transceiver = {
  2850. track: null,
  2851. iceGatherer: null,
  2852. iceTransport: null,
  2853. dtlsTransport: null,
  2854. localCapabilities: null,
  2855. remoteCapabilities: null,
  2856. rtpSender: null,
  2857. rtpReceiver: null,
  2858. kind: kind,
  2859. mid: null,
  2860. sendEncodingParameters: null,
  2861. recvEncodingParameters: null,
  2862. stream: null,
  2863. associatedRemoteMediaStreams: [],
  2864. wantReceive: true
  2865. };
  2866. if (this.usingBundle && hasBundleTransport) {
  2867. transceiver.iceTransport = this.transceivers[0].iceTransport;
  2868. transceiver.dtlsTransport = this.transceivers[0].dtlsTransport;
  2869. } else {
  2870. var transports = this._createIceAndDtlsTransports();
  2871. transceiver.iceTransport = transports.iceTransport;
  2872. transceiver.dtlsTransport = transports.dtlsTransport;
  2873. }
  2874. if (!doNotAdd) {
  2875. this.transceivers.push(transceiver);
  2876. }
  2877. return transceiver;
  2878. };
  2879. RTCPeerConnection.prototype.addTrack = function(track, stream) {
  2880. if (this._isClosed) {
  2881. throw makeError('InvalidStateError',
  2882. 'Attempted to call addTrack on a closed peerconnection.');
  2883. }
  2884. var alreadyExists = this.transceivers.find(function(s) {
  2885. return s.track === track;
  2886. });
  2887. if (alreadyExists) {
  2888. throw makeError('InvalidAccessError', 'Track already exists.');
  2889. }
  2890. var transceiver;
  2891. for (var i = 0; i < this.transceivers.length; i++) {
  2892. if (!this.transceivers[i].track &&
  2893. this.transceivers[i].kind === track.kind) {
  2894. transceiver = this.transceivers[i];
  2895. }
  2896. }
  2897. if (!transceiver) {
  2898. transceiver = this._createTransceiver(track.kind);
  2899. }
  2900. this._maybeFireNegotiationNeeded();
  2901. if (this.localStreams.indexOf(stream) === -1) {
  2902. this.localStreams.push(stream);
  2903. }
  2904. transceiver.track = track;
  2905. transceiver.stream = stream;
  2906. transceiver.rtpSender = new window.RTCRtpSender(track,
  2907. transceiver.dtlsTransport);
  2908. return transceiver.rtpSender;
  2909. };
  2910. RTCPeerConnection.prototype.addStream = function(stream) {
  2911. var pc = this;
  2912. if (edgeVersion >= 15025) {
  2913. stream.getTracks().forEach(function(track) {
  2914. pc.addTrack(track, stream);
  2915. });
  2916. } else {
  2917. // Clone is necessary for local demos mostly, attaching directly
  2918. // to two different senders does not work (build 10547).
  2919. // Fixed in 15025 (or earlier)
  2920. var clonedStream = stream.clone();
  2921. stream.getTracks().forEach(function(track, idx) {
  2922. var clonedTrack = clonedStream.getTracks()[idx];
  2923. track.addEventListener('enabled', function(event) {
  2924. clonedTrack.enabled = event.enabled;
  2925. });
  2926. });
  2927. clonedStream.getTracks().forEach(function(track) {
  2928. pc.addTrack(track, clonedStream);
  2929. });
  2930. }
  2931. };
  2932. RTCPeerConnection.prototype.removeTrack = function(sender) {
  2933. if (this._isClosed) {
  2934. throw makeError('InvalidStateError',
  2935. 'Attempted to call removeTrack on a closed peerconnection.');
  2936. }
  2937. if (!(sender instanceof window.RTCRtpSender)) {
  2938. throw new TypeError('Argument 1 of RTCPeerConnection.removeTrack ' +
  2939. 'does not implement interface RTCRtpSender.');
  2940. }
  2941. var transceiver = this.transceivers.find(function(t) {
  2942. return t.rtpSender === sender;
  2943. });
  2944. if (!transceiver) {
  2945. throw makeError('InvalidAccessError',
  2946. 'Sender was not created by this connection.');
  2947. }
  2948. var stream = transceiver.stream;
  2949. transceiver.rtpSender.stop();
  2950. transceiver.rtpSender = null;
  2951. transceiver.track = null;
  2952. transceiver.stream = null;
  2953. // remove the stream from the set of local streams
  2954. var localStreams = this.transceivers.map(function(t) {
  2955. return t.stream;
  2956. });
  2957. if (localStreams.indexOf(stream) === -1 &&
  2958. this.localStreams.indexOf(stream) > -1) {
  2959. this.localStreams.splice(this.localStreams.indexOf(stream), 1);
  2960. }
  2961. this._maybeFireNegotiationNeeded();
  2962. };
  2963. RTCPeerConnection.prototype.removeStream = function(stream) {
  2964. var pc = this;
  2965. stream.getTracks().forEach(function(track) {
  2966. var sender = pc.getSenders().find(function(s) {
  2967. return s.track === track;
  2968. });
  2969. if (sender) {
  2970. pc.removeTrack(sender);
  2971. }
  2972. });
  2973. };
  2974. RTCPeerConnection.prototype.getSenders = function() {
  2975. return this.transceivers.filter(function(transceiver) {
  2976. return !!transceiver.rtpSender;
  2977. })
  2978. .map(function(transceiver) {
  2979. return transceiver.rtpSender;
  2980. });
  2981. };
  2982. RTCPeerConnection.prototype.getReceivers = function() {
  2983. return this.transceivers.filter(function(transceiver) {
  2984. return !!transceiver.rtpReceiver;
  2985. })
  2986. .map(function(transceiver) {
  2987. return transceiver.rtpReceiver;
  2988. });
  2989. };
  2990. RTCPeerConnection.prototype._createIceGatherer = function(sdpMLineIndex,
  2991. usingBundle) {
  2992. var pc = this;
  2993. if (usingBundle && sdpMLineIndex > 0) {
  2994. return this.transceivers[0].iceGatherer;
  2995. } else if (this._iceGatherers.length) {
  2996. return this._iceGatherers.shift();
  2997. }
  2998. var iceGatherer = new window.RTCIceGatherer({
  2999. iceServers: this._config.iceServers,
  3000. gatherPolicy: this._config.iceTransportPolicy
  3001. });
  3002. Object.defineProperty(iceGatherer, 'state', {
  3003. value: 'new',
  3004. writable: true
  3005. });
  3006. this.transceivers[sdpMLineIndex].bufferedCandidateEvents = [];
  3007. this.transceivers[sdpMLineIndex].bufferCandidates = function(event) {
  3008. var end = !event.candidate || Object.keys(event.candidate).length === 0;
  3009. // polyfill since RTCIceGatherer.state is not implemented in
  3010. // Edge 10547 yet.
  3011. iceGatherer.state = end ? 'completed' : 'gathering';
  3012. if (pc.transceivers[sdpMLineIndex].bufferedCandidateEvents !== null) {
  3013. pc.transceivers[sdpMLineIndex].bufferedCandidateEvents.push(event);
  3014. }
  3015. };
  3016. iceGatherer.addEventListener('localcandidate',
  3017. this.transceivers[sdpMLineIndex].bufferCandidates);
  3018. return iceGatherer;
  3019. };
  3020. // start gathering from an RTCIceGatherer.
  3021. RTCPeerConnection.prototype._gather = function(mid, sdpMLineIndex) {
  3022. var pc = this;
  3023. var iceGatherer = this.transceivers[sdpMLineIndex].iceGatherer;
  3024. if (iceGatherer.onlocalcandidate) {
  3025. return;
  3026. }
  3027. var bufferedCandidateEvents =
  3028. this.transceivers[sdpMLineIndex].bufferedCandidateEvents;
  3029. this.transceivers[sdpMLineIndex].bufferedCandidateEvents = null;
  3030. iceGatherer.removeEventListener('localcandidate',
  3031. this.transceivers[sdpMLineIndex].bufferCandidates);
  3032. iceGatherer.onlocalcandidate = function(evt) {
  3033. if (pc.usingBundle && sdpMLineIndex > 0) {
  3034. // if we know that we use bundle we can drop candidates with
  3035. // ѕdpMLineIndex > 0. If we don't do this then our state gets
  3036. // confused since we dispose the extra ice gatherer.
  3037. return;
  3038. }
  3039. var event = new Event('icecandidate');
  3040. event.candidate = {
  3041. sdpMid: mid,
  3042. sdpMLineIndex: sdpMLineIndex
  3043. };
  3044. var cand = evt.candidate;
  3045. // Edge emits an empty object for RTCIceCandidateComplete‥
  3046. var end = !cand || Object.keys(cand).length === 0;
  3047. if (end) {
  3048. // polyfill since RTCIceGatherer.state is not implemented in
  3049. // Edge 10547 yet.
  3050. if (iceGatherer.state === 'new' || iceGatherer.state === 'gathering') {
  3051. iceGatherer.state = 'completed';
  3052. }
  3053. } else {
  3054. if (iceGatherer.state === 'new') {
  3055. iceGatherer.state = 'gathering';
  3056. }
  3057. // RTCIceCandidate doesn't have a component, needs to be added
  3058. cand.component = 1;
  3059. // also the usernameFragment. TODO: update SDP to take both variants.
  3060. cand.ufrag = iceGatherer.getLocalParameters().usernameFragment;
  3061. var serializedCandidate = sdp.writeCandidate(cand);
  3062. event.candidate = Object.assign(event.candidate,
  3063. sdp.parseCandidate(serializedCandidate));
  3064. event.candidate.candidate = serializedCandidate;
  3065. event.candidate.toJSON = function() {
  3066. return {
  3067. candidate: event.candidate.candidate,
  3068. sdpMid: event.candidate.sdpMid,
  3069. sdpMLineIndex: event.candidate.sdpMLineIndex,
  3070. usernameFragment: event.candidate.usernameFragment
  3071. };
  3072. };
  3073. }
  3074. // update local description.
  3075. var sections = sdp.getMediaSections(pc._localDescription.sdp);
  3076. if (!end) {
  3077. sections[event.candidate.sdpMLineIndex] +=
  3078. 'a=' + event.candidate.candidate + '\r\n';
  3079. } else {
  3080. sections[event.candidate.sdpMLineIndex] +=
  3081. 'a=end-of-candidates\r\n';
  3082. }
  3083. pc._localDescription.sdp =
  3084. sdp.getDescription(pc._localDescription.sdp) +
  3085. sections.join('');
  3086. var complete = pc.transceivers.every(function(transceiver) {
  3087. return transceiver.iceGatherer &&
  3088. transceiver.iceGatherer.state === 'completed';
  3089. });
  3090. if (pc.iceGatheringState !== 'gathering') {
  3091. pc.iceGatheringState = 'gathering';
  3092. pc._emitGatheringStateChange();
  3093. }
  3094. // Emit candidate. Also emit null candidate when all gatherers are
  3095. // complete.
  3096. if (!end) {
  3097. pc._dispatchEvent('icecandidate', event);
  3098. }
  3099. if (complete) {
  3100. pc._dispatchEvent('icecandidate', new Event('icecandidate'));
  3101. pc.iceGatheringState = 'complete';
  3102. pc._emitGatheringStateChange();
  3103. }
  3104. };
  3105. // emit already gathered candidates.
  3106. window.setTimeout(function() {
  3107. bufferedCandidateEvents.forEach(function(e) {
  3108. iceGatherer.onlocalcandidate(e);
  3109. });
  3110. }, 0);
  3111. };
  3112. // Create ICE transport and DTLS transport.
  3113. RTCPeerConnection.prototype._createIceAndDtlsTransports = function() {
  3114. var pc = this;
  3115. var iceTransport = new window.RTCIceTransport(null);
  3116. iceTransport.onicestatechange = function() {
  3117. pc._updateIceConnectionState();
  3118. pc._updateConnectionState();
  3119. };
  3120. var dtlsTransport = new window.RTCDtlsTransport(iceTransport);
  3121. dtlsTransport.ondtlsstatechange = function() {
  3122. pc._updateConnectionState();
  3123. };
  3124. dtlsTransport.onerror = function() {
  3125. // onerror does not set state to failed by itself.
  3126. Object.defineProperty(dtlsTransport, 'state', {
  3127. value: 'failed',
  3128. writable: true
  3129. });
  3130. pc._updateConnectionState();
  3131. };
  3132. return {
  3133. iceTransport: iceTransport,
  3134. dtlsTransport: dtlsTransport
  3135. };
  3136. };
  3137. // Destroy ICE gatherer, ICE transport and DTLS transport.
  3138. // Without triggering the callbacks.
  3139. RTCPeerConnection.prototype._disposeIceAndDtlsTransports = function(
  3140. sdpMLineIndex) {
  3141. var iceGatherer = this.transceivers[sdpMLineIndex].iceGatherer;
  3142. if (iceGatherer) {
  3143. delete iceGatherer.onlocalcandidate;
  3144. delete this.transceivers[sdpMLineIndex].iceGatherer;
  3145. }
  3146. var iceTransport = this.transceivers[sdpMLineIndex].iceTransport;
  3147. if (iceTransport) {
  3148. delete iceTransport.onicestatechange;
  3149. delete this.transceivers[sdpMLineIndex].iceTransport;
  3150. }
  3151. var dtlsTransport = this.transceivers[sdpMLineIndex].dtlsTransport;
  3152. if (dtlsTransport) {
  3153. delete dtlsTransport.ondtlsstatechange;
  3154. delete dtlsTransport.onerror;
  3155. delete this.transceivers[sdpMLineIndex].dtlsTransport;
  3156. }
  3157. };
  3158. // Start the RTP Sender and Receiver for a transceiver.
  3159. RTCPeerConnection.prototype._transceive = function(transceiver,
  3160. send, recv) {
  3161. var params = getCommonCapabilities(transceiver.localCapabilities,
  3162. transceiver.remoteCapabilities);
  3163. if (send && transceiver.rtpSender) {
  3164. params.encodings = transceiver.sendEncodingParameters;
  3165. params.rtcp = {
  3166. cname: sdp.localCName,
  3167. compound: transceiver.rtcpParameters.compound
  3168. };
  3169. if (transceiver.recvEncodingParameters.length) {
  3170. params.rtcp.ssrc = transceiver.recvEncodingParameters[0].ssrc;
  3171. }
  3172. transceiver.rtpSender.send(params);
  3173. }
  3174. if (recv && transceiver.rtpReceiver && params.codecs.length > 0) {
  3175. // remove RTX field in Edge 14942
  3176. if (transceiver.kind === 'video' &&
  3177. transceiver.recvEncodingParameters &&
  3178. edgeVersion < 15019) {
  3179. transceiver.recvEncodingParameters.forEach(function(p) {
  3180. delete p.rtx;
  3181. });
  3182. }
  3183. if (transceiver.recvEncodingParameters.length) {
  3184. params.encodings = transceiver.recvEncodingParameters;
  3185. } else {
  3186. params.encodings = [{}];
  3187. }
  3188. params.rtcp = {
  3189. compound: transceiver.rtcpParameters.compound
  3190. };
  3191. if (transceiver.rtcpParameters.cname) {
  3192. params.rtcp.cname = transceiver.rtcpParameters.cname;
  3193. }
  3194. if (transceiver.sendEncodingParameters.length) {
  3195. params.rtcp.ssrc = transceiver.sendEncodingParameters[0].ssrc;
  3196. }
  3197. transceiver.rtpReceiver.receive(params);
  3198. }
  3199. };
  3200. RTCPeerConnection.prototype.setLocalDescription = function(description) {
  3201. var pc = this;
  3202. // Note: pranswer is not supported.
  3203. if (['offer', 'answer'].indexOf(description.type) === -1) {
  3204. return Promise.reject(makeError('TypeError',
  3205. 'Unsupported type "' + description.type + '"'));
  3206. }
  3207. if (!isActionAllowedInSignalingState('setLocalDescription',
  3208. description.type, pc.signalingState) || pc._isClosed) {
  3209. return Promise.reject(makeError('InvalidStateError',
  3210. 'Can not set local ' + description.type +
  3211. ' in state ' + pc.signalingState));
  3212. }
  3213. var sections;
  3214. var sessionpart;
  3215. if (description.type === 'offer') {
  3216. // VERY limited support for SDP munging. Limited to:
  3217. // * changing the order of codecs
  3218. sections = sdp.splitSections(description.sdp);
  3219. sessionpart = sections.shift();
  3220. sections.forEach(function(mediaSection, sdpMLineIndex) {
  3221. var caps = sdp.parseRtpParameters(mediaSection);
  3222. pc.transceivers[sdpMLineIndex].localCapabilities = caps;
  3223. });
  3224. pc.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  3225. pc._gather(transceiver.mid, sdpMLineIndex);
  3226. });
  3227. } else if (description.type === 'answer') {
  3228. sections = sdp.splitSections(pc._remoteDescription.sdp);
  3229. sessionpart = sections.shift();
  3230. var isIceLite = sdp.matchPrefix(sessionpart,
  3231. 'a=ice-lite').length > 0;
  3232. sections.forEach(function(mediaSection, sdpMLineIndex) {
  3233. var transceiver = pc.transceivers[sdpMLineIndex];
  3234. var iceGatherer = transceiver.iceGatherer;
  3235. var iceTransport = transceiver.iceTransport;
  3236. var dtlsTransport = transceiver.dtlsTransport;
  3237. var localCapabilities = transceiver.localCapabilities;
  3238. var remoteCapabilities = transceiver.remoteCapabilities;
  3239. // treat bundle-only as not-rejected.
  3240. var rejected = sdp.isRejected(mediaSection) &&
  3241. sdp.matchPrefix(mediaSection, 'a=bundle-only').length === 0;
  3242. if (!rejected && !transceiver.rejected) {
  3243. var remoteIceParameters = sdp.getIceParameters(
  3244. mediaSection, sessionpart);
  3245. var remoteDtlsParameters = sdp.getDtlsParameters(
  3246. mediaSection, sessionpart);
  3247. if (isIceLite) {
  3248. remoteDtlsParameters.role = 'server';
  3249. }
  3250. if (!pc.usingBundle || sdpMLineIndex === 0) {
  3251. pc._gather(transceiver.mid, sdpMLineIndex);
  3252. if (iceTransport.state === 'new') {
  3253. iceTransport.start(iceGatherer, remoteIceParameters,
  3254. isIceLite ? 'controlling' : 'controlled');
  3255. }
  3256. if (dtlsTransport.state === 'new') {
  3257. dtlsTransport.start(remoteDtlsParameters);
  3258. }
  3259. }
  3260. // Calculate intersection of capabilities.
  3261. var params = getCommonCapabilities(localCapabilities,
  3262. remoteCapabilities);
  3263. // Start the RTCRtpSender. The RTCRtpReceiver for this
  3264. // transceiver has already been started in setRemoteDescription.
  3265. pc._transceive(transceiver,
  3266. params.codecs.length > 0,
  3267. false);
  3268. }
  3269. });
  3270. }
  3271. pc._localDescription = {
  3272. type: description.type,
  3273. sdp: description.sdp
  3274. };
  3275. if (description.type === 'offer') {
  3276. pc._updateSignalingState('have-local-offer');
  3277. } else {
  3278. pc._updateSignalingState('stable');
  3279. }
  3280. return Promise.resolve();
  3281. };
  3282. RTCPeerConnection.prototype.setRemoteDescription = function(description) {
  3283. var pc = this;
  3284. // Note: pranswer is not supported.
  3285. if (['offer', 'answer'].indexOf(description.type) === -1) {
  3286. return Promise.reject(makeError('TypeError',
  3287. 'Unsupported type "' + description.type + '"'));
  3288. }
  3289. if (!isActionAllowedInSignalingState('setRemoteDescription',
  3290. description.type, pc.signalingState) || pc._isClosed) {
  3291. return Promise.reject(makeError('InvalidStateError',
  3292. 'Can not set remote ' + description.type +
  3293. ' in state ' + pc.signalingState));
  3294. }
  3295. var streams = {};
  3296. pc.remoteStreams.forEach(function(stream) {
  3297. streams[stream.id] = stream;
  3298. });
  3299. var receiverList = [];
  3300. var sections = sdp.splitSections(description.sdp);
  3301. var sessionpart = sections.shift();
  3302. var isIceLite = sdp.matchPrefix(sessionpart,
  3303. 'a=ice-lite').length > 0;
  3304. var usingBundle = sdp.matchPrefix(sessionpart,
  3305. 'a=group:BUNDLE ').length > 0;
  3306. pc.usingBundle = usingBundle;
  3307. var iceOptions = sdp.matchPrefix(sessionpart,
  3308. 'a=ice-options:')[0];
  3309. if (iceOptions) {
  3310. pc.canTrickleIceCandidates = iceOptions.substr(14).split(' ')
  3311. .indexOf('trickle') >= 0;
  3312. } else {
  3313. pc.canTrickleIceCandidates = false;
  3314. }
  3315. sections.forEach(function(mediaSection, sdpMLineIndex) {
  3316. var lines = sdp.splitLines(mediaSection);
  3317. var kind = sdp.getKind(mediaSection);
  3318. // treat bundle-only as not-rejected.
  3319. var rejected = sdp.isRejected(mediaSection) &&
  3320. sdp.matchPrefix(mediaSection, 'a=bundle-only').length === 0;
  3321. var protocol = lines[0].substr(2).split(' ')[2];
  3322. var direction = sdp.getDirection(mediaSection, sessionpart);
  3323. var remoteMsid = sdp.parseMsid(mediaSection);
  3324. var mid = sdp.getMid(mediaSection) || sdp.generateIdentifier();
  3325. // Reject datachannels which are not implemented yet.
  3326. if (rejected || (kind === 'application' && (protocol === 'DTLS/SCTP' ||
  3327. protocol === 'UDP/DTLS/SCTP'))) {
  3328. // TODO: this is dangerous in the case where a non-rejected m-line
  3329. // becomes rejected.
  3330. pc.transceivers[sdpMLineIndex] = {
  3331. mid: mid,
  3332. kind: kind,
  3333. protocol: protocol,
  3334. rejected: true
  3335. };
  3336. return;
  3337. }
  3338. if (!rejected && pc.transceivers[sdpMLineIndex] &&
  3339. pc.transceivers[sdpMLineIndex].rejected) {
  3340. // recycle a rejected transceiver.
  3341. pc.transceivers[sdpMLineIndex] = pc._createTransceiver(kind, true);
  3342. }
  3343. var transceiver;
  3344. var iceGatherer;
  3345. var iceTransport;
  3346. var dtlsTransport;
  3347. var rtpReceiver;
  3348. var sendEncodingParameters;
  3349. var recvEncodingParameters;
  3350. var localCapabilities;
  3351. var track;
  3352. // FIXME: ensure the mediaSection has rtcp-mux set.
  3353. var remoteCapabilities = sdp.parseRtpParameters(mediaSection);
  3354. var remoteIceParameters;
  3355. var remoteDtlsParameters;
  3356. if (!rejected) {
  3357. remoteIceParameters = sdp.getIceParameters(mediaSection,
  3358. sessionpart);
  3359. remoteDtlsParameters = sdp.getDtlsParameters(mediaSection,
  3360. sessionpart);
  3361. remoteDtlsParameters.role = 'client';
  3362. }
  3363. recvEncodingParameters =
  3364. sdp.parseRtpEncodingParameters(mediaSection);
  3365. var rtcpParameters = sdp.parseRtcpParameters(mediaSection);
  3366. var isComplete = sdp.matchPrefix(mediaSection,
  3367. 'a=end-of-candidates', sessionpart).length > 0;
  3368. var cands = sdp.matchPrefix(mediaSection, 'a=candidate:')
  3369. .map(function(cand) {
  3370. return sdp.parseCandidate(cand);
  3371. })
  3372. .filter(function(cand) {
  3373. return cand.component === 1;
  3374. });
  3375. // Check if we can use BUNDLE and dispose transports.
  3376. if ((description.type === 'offer' || description.type === 'answer') &&
  3377. !rejected && usingBundle && sdpMLineIndex > 0 &&
  3378. pc.transceivers[sdpMLineIndex]) {
  3379. pc._disposeIceAndDtlsTransports(sdpMLineIndex);
  3380. pc.transceivers[sdpMLineIndex].iceGatherer =
  3381. pc.transceivers[0].iceGatherer;
  3382. pc.transceivers[sdpMLineIndex].iceTransport =
  3383. pc.transceivers[0].iceTransport;
  3384. pc.transceivers[sdpMLineIndex].dtlsTransport =
  3385. pc.transceivers[0].dtlsTransport;
  3386. if (pc.transceivers[sdpMLineIndex].rtpSender) {
  3387. pc.transceivers[sdpMLineIndex].rtpSender.setTransport(
  3388. pc.transceivers[0].dtlsTransport);
  3389. }
  3390. if (pc.transceivers[sdpMLineIndex].rtpReceiver) {
  3391. pc.transceivers[sdpMLineIndex].rtpReceiver.setTransport(
  3392. pc.transceivers[0].dtlsTransport);
  3393. }
  3394. }
  3395. if (description.type === 'offer' && !rejected) {
  3396. transceiver = pc.transceivers[sdpMLineIndex] ||
  3397. pc._createTransceiver(kind);
  3398. transceiver.mid = mid;
  3399. if (!transceiver.iceGatherer) {
  3400. transceiver.iceGatherer = pc._createIceGatherer(sdpMLineIndex,
  3401. usingBundle);
  3402. }
  3403. if (cands.length && transceiver.iceTransport.state === 'new') {
  3404. if (isComplete && (!usingBundle || sdpMLineIndex === 0)) {
  3405. transceiver.iceTransport.setRemoteCandidates(cands);
  3406. } else {
  3407. cands.forEach(function(candidate) {
  3408. maybeAddCandidate(transceiver.iceTransport, candidate);
  3409. });
  3410. }
  3411. }
  3412. localCapabilities = window.RTCRtpReceiver.getCapabilities(kind);
  3413. // filter RTX until additional stuff needed for RTX is implemented
  3414. // in adapter.js
  3415. if (edgeVersion < 15019) {
  3416. localCapabilities.codecs = localCapabilities.codecs.filter(
  3417. function(codec) {
  3418. return codec.name !== 'rtx';
  3419. });
  3420. }
  3421. sendEncodingParameters = transceiver.sendEncodingParameters || [{
  3422. ssrc: (2 * sdpMLineIndex + 2) * 1001
  3423. }];
  3424. // TODO: rewrite to use http://w3c.github.io/webrtc-pc/#set-associated-remote-streams
  3425. var isNewTrack = false;
  3426. if (direction === 'sendrecv' || direction === 'sendonly') {
  3427. isNewTrack = !transceiver.rtpReceiver;
  3428. rtpReceiver = transceiver.rtpReceiver ||
  3429. new window.RTCRtpReceiver(transceiver.dtlsTransport, kind);
  3430. if (isNewTrack) {
  3431. var stream;
  3432. track = rtpReceiver.track;
  3433. // FIXME: does not work with Plan B.
  3434. if (remoteMsid && remoteMsid.stream === '-');
  3435. else if (remoteMsid) {
  3436. if (!streams[remoteMsid.stream]) {
  3437. streams[remoteMsid.stream] = new window.MediaStream();
  3438. Object.defineProperty(streams[remoteMsid.stream], 'id', {
  3439. get: function() {
  3440. return remoteMsid.stream;
  3441. }
  3442. });
  3443. }
  3444. Object.defineProperty(track, 'id', {
  3445. get: function() {
  3446. return remoteMsid.track;
  3447. }
  3448. });
  3449. stream = streams[remoteMsid.stream];
  3450. } else {
  3451. if (!streams.default) {
  3452. streams.default = new window.MediaStream();
  3453. }
  3454. stream = streams.default;
  3455. }
  3456. if (stream) {
  3457. addTrackToStreamAndFireEvent(track, stream);
  3458. transceiver.associatedRemoteMediaStreams.push(stream);
  3459. }
  3460. receiverList.push([track, rtpReceiver, stream]);
  3461. }
  3462. } else if (transceiver.rtpReceiver && transceiver.rtpReceiver.track) {
  3463. transceiver.associatedRemoteMediaStreams.forEach(function(s) {
  3464. var nativeTrack = s.getTracks().find(function(t) {
  3465. return t.id === transceiver.rtpReceiver.track.id;
  3466. });
  3467. if (nativeTrack) {
  3468. removeTrackFromStreamAndFireEvent(nativeTrack, s);
  3469. }
  3470. });
  3471. transceiver.associatedRemoteMediaStreams = [];
  3472. }
  3473. transceiver.localCapabilities = localCapabilities;
  3474. transceiver.remoteCapabilities = remoteCapabilities;
  3475. transceiver.rtpReceiver = rtpReceiver;
  3476. transceiver.rtcpParameters = rtcpParameters;
  3477. transceiver.sendEncodingParameters = sendEncodingParameters;
  3478. transceiver.recvEncodingParameters = recvEncodingParameters;
  3479. // Start the RTCRtpReceiver now. The RTPSender is started in
  3480. // setLocalDescription.
  3481. pc._transceive(pc.transceivers[sdpMLineIndex],
  3482. false,
  3483. isNewTrack);
  3484. } else if (description.type === 'answer' && !rejected) {
  3485. transceiver = pc.transceivers[sdpMLineIndex];
  3486. iceGatherer = transceiver.iceGatherer;
  3487. iceTransport = transceiver.iceTransport;
  3488. dtlsTransport = transceiver.dtlsTransport;
  3489. rtpReceiver = transceiver.rtpReceiver;
  3490. sendEncodingParameters = transceiver.sendEncodingParameters;
  3491. localCapabilities = transceiver.localCapabilities;
  3492. pc.transceivers[sdpMLineIndex].recvEncodingParameters =
  3493. recvEncodingParameters;
  3494. pc.transceivers[sdpMLineIndex].remoteCapabilities =
  3495. remoteCapabilities;
  3496. pc.transceivers[sdpMLineIndex].rtcpParameters = rtcpParameters;
  3497. if (cands.length && iceTransport.state === 'new') {
  3498. if ((isIceLite || isComplete) &&
  3499. (!usingBundle || sdpMLineIndex === 0)) {
  3500. iceTransport.setRemoteCandidates(cands);
  3501. } else {
  3502. cands.forEach(function(candidate) {
  3503. maybeAddCandidate(transceiver.iceTransport, candidate);
  3504. });
  3505. }
  3506. }
  3507. if (!usingBundle || sdpMLineIndex === 0) {
  3508. if (iceTransport.state === 'new') {
  3509. iceTransport.start(iceGatherer, remoteIceParameters,
  3510. 'controlling');
  3511. }
  3512. if (dtlsTransport.state === 'new') {
  3513. dtlsTransport.start(remoteDtlsParameters);
  3514. }
  3515. }
  3516. // If the offer contained RTX but the answer did not,
  3517. // remove RTX from sendEncodingParameters.
  3518. var commonCapabilities = getCommonCapabilities(
  3519. transceiver.localCapabilities,
  3520. transceiver.remoteCapabilities);
  3521. var hasRtx = commonCapabilities.codecs.filter(function(c) {
  3522. return c.name.toLowerCase() === 'rtx';
  3523. }).length;
  3524. if (!hasRtx && transceiver.sendEncodingParameters[0].rtx) {
  3525. delete transceiver.sendEncodingParameters[0].rtx;
  3526. }
  3527. pc._transceive(transceiver,
  3528. direction === 'sendrecv' || direction === 'recvonly',
  3529. direction === 'sendrecv' || direction === 'sendonly');
  3530. // TODO: rewrite to use http://w3c.github.io/webrtc-pc/#set-associated-remote-streams
  3531. if (rtpReceiver &&
  3532. (direction === 'sendrecv' || direction === 'sendonly')) {
  3533. track = rtpReceiver.track;
  3534. if (remoteMsid) {
  3535. if (!streams[remoteMsid.stream]) {
  3536. streams[remoteMsid.stream] = new window.MediaStream();
  3537. }
  3538. addTrackToStreamAndFireEvent(track, streams[remoteMsid.stream]);
  3539. receiverList.push([track, rtpReceiver, streams[remoteMsid.stream]]);
  3540. } else {
  3541. if (!streams.default) {
  3542. streams.default = new window.MediaStream();
  3543. }
  3544. addTrackToStreamAndFireEvent(track, streams.default);
  3545. receiverList.push([track, rtpReceiver, streams.default]);
  3546. }
  3547. } else {
  3548. // FIXME: actually the receiver should be created later.
  3549. delete transceiver.rtpReceiver;
  3550. }
  3551. }
  3552. });
  3553. if (pc._dtlsRole === undefined) {
  3554. pc._dtlsRole = description.type === 'offer' ? 'active' : 'passive';
  3555. }
  3556. pc._remoteDescription = {
  3557. type: description.type,
  3558. sdp: description.sdp
  3559. };
  3560. if (description.type === 'offer') {
  3561. pc._updateSignalingState('have-remote-offer');
  3562. } else {
  3563. pc._updateSignalingState('stable');
  3564. }
  3565. Object.keys(streams).forEach(function(sid) {
  3566. var stream = streams[sid];
  3567. if (stream.getTracks().length) {
  3568. if (pc.remoteStreams.indexOf(stream) === -1) {
  3569. pc.remoteStreams.push(stream);
  3570. var event = new Event('addstream');
  3571. event.stream = stream;
  3572. window.setTimeout(function() {
  3573. pc._dispatchEvent('addstream', event);
  3574. });
  3575. }
  3576. receiverList.forEach(function(item) {
  3577. var track = item[0];
  3578. var receiver = item[1];
  3579. if (stream.id !== item[2].id) {
  3580. return;
  3581. }
  3582. fireAddTrack(pc, track, receiver, [stream]);
  3583. });
  3584. }
  3585. });
  3586. receiverList.forEach(function(item) {
  3587. if (item[2]) {
  3588. return;
  3589. }
  3590. fireAddTrack(pc, item[0], item[1], []);
  3591. });
  3592. // check whether addIceCandidate({}) was called within four seconds after
  3593. // setRemoteDescription.
  3594. window.setTimeout(function() {
  3595. if (!(pc && pc.transceivers)) {
  3596. return;
  3597. }
  3598. pc.transceivers.forEach(function(transceiver) {
  3599. if (transceiver.iceTransport &&
  3600. transceiver.iceTransport.state === 'new' &&
  3601. transceiver.iceTransport.getRemoteCandidates().length > 0) {
  3602. console.warn('Timeout for addRemoteCandidate. Consider sending ' +
  3603. 'an end-of-candidates notification');
  3604. transceiver.iceTransport.addRemoteCandidate({});
  3605. }
  3606. });
  3607. }, 4000);
  3608. return Promise.resolve();
  3609. };
  3610. RTCPeerConnection.prototype.close = function() {
  3611. this.transceivers.forEach(function(transceiver) {
  3612. /* not yet
  3613. if (transceiver.iceGatherer) {
  3614. transceiver.iceGatherer.close();
  3615. }
  3616. */
  3617. if (transceiver.iceTransport) {
  3618. transceiver.iceTransport.stop();
  3619. }
  3620. if (transceiver.dtlsTransport) {
  3621. transceiver.dtlsTransport.stop();
  3622. }
  3623. if (transceiver.rtpSender) {
  3624. transceiver.rtpSender.stop();
  3625. }
  3626. if (transceiver.rtpReceiver) {
  3627. transceiver.rtpReceiver.stop();
  3628. }
  3629. });
  3630. // FIXME: clean up tracks, local streams, remote streams, etc
  3631. this._isClosed = true;
  3632. this._updateSignalingState('closed');
  3633. };
  3634. // Update the signaling state.
  3635. RTCPeerConnection.prototype._updateSignalingState = function(newState) {
  3636. this.signalingState = newState;
  3637. var event = new Event('signalingstatechange');
  3638. this._dispatchEvent('signalingstatechange', event);
  3639. };
  3640. // Determine whether to fire the negotiationneeded event.
  3641. RTCPeerConnection.prototype._maybeFireNegotiationNeeded = function() {
  3642. var pc = this;
  3643. if (this.signalingState !== 'stable' || this.needNegotiation === true) {
  3644. return;
  3645. }
  3646. this.needNegotiation = true;
  3647. window.setTimeout(function() {
  3648. if (pc.needNegotiation) {
  3649. pc.needNegotiation = false;
  3650. var event = new Event('negotiationneeded');
  3651. pc._dispatchEvent('negotiationneeded', event);
  3652. }
  3653. }, 0);
  3654. };
  3655. // Update the ice connection state.
  3656. RTCPeerConnection.prototype._updateIceConnectionState = function() {
  3657. var newState;
  3658. var states = {
  3659. 'new': 0,
  3660. closed: 0,
  3661. checking: 0,
  3662. connected: 0,
  3663. completed: 0,
  3664. disconnected: 0,
  3665. failed: 0
  3666. };
  3667. this.transceivers.forEach(function(transceiver) {
  3668. if (transceiver.iceTransport && !transceiver.rejected) {
  3669. states[transceiver.iceTransport.state]++;
  3670. }
  3671. });
  3672. newState = 'new';
  3673. if (states.failed > 0) {
  3674. newState = 'failed';
  3675. } else if (states.checking > 0) {
  3676. newState = 'checking';
  3677. } else if (states.disconnected > 0) {
  3678. newState = 'disconnected';
  3679. } else if (states.new > 0) {
  3680. newState = 'new';
  3681. } else if (states.connected > 0) {
  3682. newState = 'connected';
  3683. } else if (states.completed > 0) {
  3684. newState = 'completed';
  3685. }
  3686. if (newState !== this.iceConnectionState) {
  3687. this.iceConnectionState = newState;
  3688. var event = new Event('iceconnectionstatechange');
  3689. this._dispatchEvent('iceconnectionstatechange', event);
  3690. }
  3691. };
  3692. // Update the connection state.
  3693. RTCPeerConnection.prototype._updateConnectionState = function() {
  3694. var newState;
  3695. var states = {
  3696. 'new': 0,
  3697. closed: 0,
  3698. connecting: 0,
  3699. connected: 0,
  3700. completed: 0,
  3701. disconnected: 0,
  3702. failed: 0
  3703. };
  3704. this.transceivers.forEach(function(transceiver) {
  3705. if (transceiver.iceTransport && transceiver.dtlsTransport &&
  3706. !transceiver.rejected) {
  3707. states[transceiver.iceTransport.state]++;
  3708. states[transceiver.dtlsTransport.state]++;
  3709. }
  3710. });
  3711. // ICETransport.completed and connected are the same for this purpose.
  3712. states.connected += states.completed;
  3713. newState = 'new';
  3714. if (states.failed > 0) {
  3715. newState = 'failed';
  3716. } else if (states.connecting > 0) {
  3717. newState = 'connecting';
  3718. } else if (states.disconnected > 0) {
  3719. newState = 'disconnected';
  3720. } else if (states.new > 0) {
  3721. newState = 'new';
  3722. } else if (states.connected > 0) {
  3723. newState = 'connected';
  3724. }
  3725. if (newState !== this.connectionState) {
  3726. this.connectionState = newState;
  3727. var event = new Event('connectionstatechange');
  3728. this._dispatchEvent('connectionstatechange', event);
  3729. }
  3730. };
  3731. RTCPeerConnection.prototype.createOffer = function() {
  3732. var pc = this;
  3733. if (pc._isClosed) {
  3734. return Promise.reject(makeError('InvalidStateError',
  3735. 'Can not call createOffer after close'));
  3736. }
  3737. var numAudioTracks = pc.transceivers.filter(function(t) {
  3738. return t.kind === 'audio';
  3739. }).length;
  3740. var numVideoTracks = pc.transceivers.filter(function(t) {
  3741. return t.kind === 'video';
  3742. }).length;
  3743. // Determine number of audio and video tracks we need to send/recv.
  3744. var offerOptions = arguments[0];
  3745. if (offerOptions) {
  3746. // Reject Chrome legacy constraints.
  3747. if (offerOptions.mandatory || offerOptions.optional) {
  3748. throw new TypeError(
  3749. 'Legacy mandatory/optional constraints not supported.');
  3750. }
  3751. if (offerOptions.offerToReceiveAudio !== undefined) {
  3752. if (offerOptions.offerToReceiveAudio === true) {
  3753. numAudioTracks = 1;
  3754. } else if (offerOptions.offerToReceiveAudio === false) {
  3755. numAudioTracks = 0;
  3756. } else {
  3757. numAudioTracks = offerOptions.offerToReceiveAudio;
  3758. }
  3759. }
  3760. if (offerOptions.offerToReceiveVideo !== undefined) {
  3761. if (offerOptions.offerToReceiveVideo === true) {
  3762. numVideoTracks = 1;
  3763. } else if (offerOptions.offerToReceiveVideo === false) {
  3764. numVideoTracks = 0;
  3765. } else {
  3766. numVideoTracks = offerOptions.offerToReceiveVideo;
  3767. }
  3768. }
  3769. }
  3770. pc.transceivers.forEach(function(transceiver) {
  3771. if (transceiver.kind === 'audio') {
  3772. numAudioTracks--;
  3773. if (numAudioTracks < 0) {
  3774. transceiver.wantReceive = false;
  3775. }
  3776. } else if (transceiver.kind === 'video') {
  3777. numVideoTracks--;
  3778. if (numVideoTracks < 0) {
  3779. transceiver.wantReceive = false;
  3780. }
  3781. }
  3782. });
  3783. // Create M-lines for recvonly streams.
  3784. while (numAudioTracks > 0 || numVideoTracks > 0) {
  3785. if (numAudioTracks > 0) {
  3786. pc._createTransceiver('audio');
  3787. numAudioTracks--;
  3788. }
  3789. if (numVideoTracks > 0) {
  3790. pc._createTransceiver('video');
  3791. numVideoTracks--;
  3792. }
  3793. }
  3794. var sdp$1 = sdp.writeSessionBoilerplate(pc._sdpSessionId,
  3795. pc._sdpSessionVersion++);
  3796. pc.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  3797. // For each track, create an ice gatherer, ice transport,
  3798. // dtls transport, potentially rtpsender and rtpreceiver.
  3799. var track = transceiver.track;
  3800. var kind = transceiver.kind;
  3801. var mid = transceiver.mid || sdp.generateIdentifier();
  3802. transceiver.mid = mid;
  3803. if (!transceiver.iceGatherer) {
  3804. transceiver.iceGatherer = pc._createIceGatherer(sdpMLineIndex,
  3805. pc.usingBundle);
  3806. }
  3807. var localCapabilities = window.RTCRtpSender.getCapabilities(kind);
  3808. // filter RTX until additional stuff needed for RTX is implemented
  3809. // in adapter.js
  3810. if (edgeVersion < 15019) {
  3811. localCapabilities.codecs = localCapabilities.codecs.filter(
  3812. function(codec) {
  3813. return codec.name !== 'rtx';
  3814. });
  3815. }
  3816. localCapabilities.codecs.forEach(function(codec) {
  3817. // work around https://bugs.chromium.org/p/webrtc/issues/detail?id=6552
  3818. // by adding level-asymmetry-allowed=1
  3819. if (codec.name === 'H264' &&
  3820. codec.parameters['level-asymmetry-allowed'] === undefined) {
  3821. codec.parameters['level-asymmetry-allowed'] = '1';
  3822. }
  3823. // for subsequent offers, we might have to re-use the payload
  3824. // type of the last offer.
  3825. if (transceiver.remoteCapabilities &&
  3826. transceiver.remoteCapabilities.codecs) {
  3827. transceiver.remoteCapabilities.codecs.forEach(function(remoteCodec) {
  3828. if (codec.name.toLowerCase() === remoteCodec.name
  3829. .toLowerCase() &&
  3830. codec.clockRate === remoteCodec.clockRate) {
  3831. codec.preferredPayloadType = remoteCodec.payloadType;
  3832. }
  3833. });
  3834. }
  3835. });
  3836. localCapabilities.headerExtensions.forEach(function(hdrExt) {
  3837. var remoteExtensions = transceiver.remoteCapabilities &&
  3838. transceiver.remoteCapabilities.headerExtensions || [];
  3839. remoteExtensions.forEach(function(rHdrExt) {
  3840. if (hdrExt.uri === rHdrExt.uri) {
  3841. hdrExt.id = rHdrExt.id;
  3842. }
  3843. });
  3844. });
  3845. // generate an ssrc now, to be used later in rtpSender.send
  3846. var sendEncodingParameters = transceiver.sendEncodingParameters || [{
  3847. ssrc: (2 * sdpMLineIndex + 1) * 1001
  3848. }];
  3849. if (track) {
  3850. // add RTX
  3851. if (edgeVersion >= 15019 && kind === 'video' &&
  3852. !sendEncodingParameters[0].rtx) {
  3853. sendEncodingParameters[0].rtx = {
  3854. ssrc: sendEncodingParameters[0].ssrc + 1
  3855. };
  3856. }
  3857. }
  3858. if (transceiver.wantReceive) {
  3859. transceiver.rtpReceiver = new window.RTCRtpReceiver(
  3860. transceiver.dtlsTransport, kind);
  3861. }
  3862. transceiver.localCapabilities = localCapabilities;
  3863. transceiver.sendEncodingParameters = sendEncodingParameters;
  3864. });
  3865. // always offer BUNDLE and dispose on return if not supported.
  3866. if (pc._config.bundlePolicy !== 'max-compat') {
  3867. sdp$1 += 'a=group:BUNDLE ' + pc.transceivers.map(function(t) {
  3868. return t.mid;
  3869. }).join(' ') + '\r\n';
  3870. }
  3871. sdp$1 += 'a=ice-options:trickle\r\n';
  3872. pc.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  3873. sdp$1 += writeMediaSection(transceiver, transceiver.localCapabilities,
  3874. 'offer', transceiver.stream, pc._dtlsRole);
  3875. sdp$1 += 'a=rtcp-rsize\r\n';
  3876. if (transceiver.iceGatherer && pc.iceGatheringState !== 'new' &&
  3877. (sdpMLineIndex === 0 || !pc.usingBundle)) {
  3878. transceiver.iceGatherer.getLocalCandidates().forEach(function(cand) {
  3879. cand.component = 1;
  3880. sdp$1 += 'a=' + sdp.writeCandidate(cand) + '\r\n';
  3881. });
  3882. if (transceiver.iceGatherer.state === 'completed') {
  3883. sdp$1 += 'a=end-of-candidates\r\n';
  3884. }
  3885. }
  3886. });
  3887. var desc = new window.RTCSessionDescription({
  3888. type: 'offer',
  3889. sdp: sdp$1
  3890. });
  3891. return Promise.resolve(desc);
  3892. };
  3893. RTCPeerConnection.prototype.createAnswer = function() {
  3894. var pc = this;
  3895. if (pc._isClosed) {
  3896. return Promise.reject(makeError('InvalidStateError',
  3897. 'Can not call createAnswer after close'));
  3898. }
  3899. if (!(pc.signalingState === 'have-remote-offer' ||
  3900. pc.signalingState === 'have-local-pranswer')) {
  3901. return Promise.reject(makeError('InvalidStateError',
  3902. 'Can not call createAnswer in signalingState ' + pc.signalingState));
  3903. }
  3904. var sdp$1 = sdp.writeSessionBoilerplate(pc._sdpSessionId,
  3905. pc._sdpSessionVersion++);
  3906. if (pc.usingBundle) {
  3907. sdp$1 += 'a=group:BUNDLE ' + pc.transceivers.map(function(t) {
  3908. return t.mid;
  3909. }).join(' ') + '\r\n';
  3910. }
  3911. sdp$1 += 'a=ice-options:trickle\r\n';
  3912. var mediaSectionsInOffer = sdp.getMediaSections(
  3913. pc._remoteDescription.sdp).length;
  3914. pc.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  3915. if (sdpMLineIndex + 1 > mediaSectionsInOffer) {
  3916. return;
  3917. }
  3918. if (transceiver.rejected) {
  3919. if (transceiver.kind === 'application') {
  3920. if (transceiver.protocol === 'DTLS/SCTP') { // legacy fmt
  3921. sdp$1 += 'm=application 0 DTLS/SCTP 5000\r\n';
  3922. } else {
  3923. sdp$1 += 'm=application 0 ' + transceiver.protocol +
  3924. ' webrtc-datachannel\r\n';
  3925. }
  3926. } else if (transceiver.kind === 'audio') {
  3927. sdp$1 += 'm=audio 0 UDP/TLS/RTP/SAVPF 0\r\n' +
  3928. 'a=rtpmap:0 PCMU/8000\r\n';
  3929. } else if (transceiver.kind === 'video') {
  3930. sdp$1 += 'm=video 0 UDP/TLS/RTP/SAVPF 120\r\n' +
  3931. 'a=rtpmap:120 VP8/90000\r\n';
  3932. }
  3933. sdp$1 += 'c=IN IP4 0.0.0.0\r\n' +
  3934. 'a=inactive\r\n' +
  3935. 'a=mid:' + transceiver.mid + '\r\n';
  3936. return;
  3937. }
  3938. // FIXME: look at direction.
  3939. if (transceiver.stream) {
  3940. var localTrack;
  3941. if (transceiver.kind === 'audio') {
  3942. localTrack = transceiver.stream.getAudioTracks()[0];
  3943. } else if (transceiver.kind === 'video') {
  3944. localTrack = transceiver.stream.getVideoTracks()[0];
  3945. }
  3946. if (localTrack) {
  3947. // add RTX
  3948. if (edgeVersion >= 15019 && transceiver.kind === 'video' &&
  3949. !transceiver.sendEncodingParameters[0].rtx) {
  3950. transceiver.sendEncodingParameters[0].rtx = {
  3951. ssrc: transceiver.sendEncodingParameters[0].ssrc + 1
  3952. };
  3953. }
  3954. }
  3955. }
  3956. // Calculate intersection of capabilities.
  3957. var commonCapabilities = getCommonCapabilities(
  3958. transceiver.localCapabilities,
  3959. transceiver.remoteCapabilities);
  3960. var hasRtx = commonCapabilities.codecs.filter(function(c) {
  3961. return c.name.toLowerCase() === 'rtx';
  3962. }).length;
  3963. if (!hasRtx && transceiver.sendEncodingParameters[0].rtx) {
  3964. delete transceiver.sendEncodingParameters[0].rtx;
  3965. }
  3966. sdp$1 += writeMediaSection(transceiver, commonCapabilities,
  3967. 'answer', transceiver.stream, pc._dtlsRole);
  3968. if (transceiver.rtcpParameters &&
  3969. transceiver.rtcpParameters.reducedSize) {
  3970. sdp$1 += 'a=rtcp-rsize\r\n';
  3971. }
  3972. });
  3973. var desc = new window.RTCSessionDescription({
  3974. type: 'answer',
  3975. sdp: sdp$1
  3976. });
  3977. return Promise.resolve(desc);
  3978. };
  3979. RTCPeerConnection.prototype.addIceCandidate = function(candidate) {
  3980. var pc = this;
  3981. var sections;
  3982. if (candidate && !(candidate.sdpMLineIndex !== undefined ||
  3983. candidate.sdpMid)) {
  3984. return Promise.reject(new TypeError('sdpMLineIndex or sdpMid required'));
  3985. }
  3986. // TODO: needs to go into ops queue.
  3987. return new Promise(function(resolve, reject) {
  3988. if (!pc._remoteDescription) {
  3989. return reject(makeError('InvalidStateError',
  3990. 'Can not add ICE candidate without a remote description'));
  3991. } else if (!candidate || candidate.candidate === '') {
  3992. for (var j = 0; j < pc.transceivers.length; j++) {
  3993. if (pc.transceivers[j].rejected) {
  3994. continue;
  3995. }
  3996. pc.transceivers[j].iceTransport.addRemoteCandidate({});
  3997. sections = sdp.getMediaSections(pc._remoteDescription.sdp);
  3998. sections[j] += 'a=end-of-candidates\r\n';
  3999. pc._remoteDescription.sdp =
  4000. sdp.getDescription(pc._remoteDescription.sdp) +
  4001. sections.join('');
  4002. if (pc.usingBundle) {
  4003. break;
  4004. }
  4005. }
  4006. } else {
  4007. var sdpMLineIndex = candidate.sdpMLineIndex;
  4008. if (candidate.sdpMid) {
  4009. for (var i = 0; i < pc.transceivers.length; i++) {
  4010. if (pc.transceivers[i].mid === candidate.sdpMid) {
  4011. sdpMLineIndex = i;
  4012. break;
  4013. }
  4014. }
  4015. }
  4016. var transceiver = pc.transceivers[sdpMLineIndex];
  4017. if (transceiver) {
  4018. if (transceiver.rejected) {
  4019. return resolve();
  4020. }
  4021. var cand = Object.keys(candidate.candidate).length > 0 ?
  4022. sdp.parseCandidate(candidate.candidate) : {};
  4023. // Ignore Chrome's invalid candidates since Edge does not like them.
  4024. if (cand.protocol === 'tcp' && (cand.port === 0 || cand.port === 9)) {
  4025. return resolve();
  4026. }
  4027. // Ignore RTCP candidates, we assume RTCP-MUX.
  4028. if (cand.component && cand.component !== 1) {
  4029. return resolve();
  4030. }
  4031. // when using bundle, avoid adding candidates to the wrong
  4032. // ice transport. And avoid adding candidates added in the SDP.
  4033. if (sdpMLineIndex === 0 || (sdpMLineIndex > 0 &&
  4034. transceiver.iceTransport !== pc.transceivers[0].iceTransport)) {
  4035. if (!maybeAddCandidate(transceiver.iceTransport, cand)) {
  4036. return reject(makeError('OperationError',
  4037. 'Can not add ICE candidate'));
  4038. }
  4039. }
  4040. // update the remoteDescription.
  4041. var candidateString = candidate.candidate.trim();
  4042. if (candidateString.indexOf('a=') === 0) {
  4043. candidateString = candidateString.substr(2);
  4044. }
  4045. sections = sdp.getMediaSections(pc._remoteDescription.sdp);
  4046. sections[sdpMLineIndex] += 'a=' +
  4047. (cand.type ? candidateString : 'end-of-candidates') +
  4048. '\r\n';
  4049. pc._remoteDescription.sdp =
  4050. sdp.getDescription(pc._remoteDescription.sdp) +
  4051. sections.join('');
  4052. } else {
  4053. return reject(makeError('OperationError',
  4054. 'Can not add ICE candidate'));
  4055. }
  4056. }
  4057. resolve();
  4058. });
  4059. };
  4060. RTCPeerConnection.prototype.getStats = function(selector) {
  4061. if (selector && selector instanceof window.MediaStreamTrack) {
  4062. var senderOrReceiver = null;
  4063. this.transceivers.forEach(function(transceiver) {
  4064. if (transceiver.rtpSender &&
  4065. transceiver.rtpSender.track === selector) {
  4066. senderOrReceiver = transceiver.rtpSender;
  4067. } else if (transceiver.rtpReceiver &&
  4068. transceiver.rtpReceiver.track === selector) {
  4069. senderOrReceiver = transceiver.rtpReceiver;
  4070. }
  4071. });
  4072. if (!senderOrReceiver) {
  4073. throw makeError('InvalidAccessError', 'Invalid selector.');
  4074. }
  4075. return senderOrReceiver.getStats();
  4076. }
  4077. var promises = [];
  4078. this.transceivers.forEach(function(transceiver) {
  4079. ['rtpSender', 'rtpReceiver', 'iceGatherer', 'iceTransport',
  4080. 'dtlsTransport'
  4081. ].forEach(function(method) {
  4082. if (transceiver[method]) {
  4083. promises.push(transceiver[method].getStats());
  4084. }
  4085. });
  4086. });
  4087. return Promise.all(promises).then(function(allStats) {
  4088. var results = new Map();
  4089. allStats.forEach(function(stats) {
  4090. stats.forEach(function(stat) {
  4091. results.set(stat.id, stat);
  4092. });
  4093. });
  4094. return results;
  4095. });
  4096. };
  4097. // fix low-level stat names and return Map instead of object.
  4098. var ortcObjects = ['RTCRtpSender', 'RTCRtpReceiver', 'RTCIceGatherer',
  4099. 'RTCIceTransport', 'RTCDtlsTransport'
  4100. ];
  4101. ortcObjects.forEach(function(ortcObjectName) {
  4102. var obj = window[ortcObjectName];
  4103. if (obj && obj.prototype && obj.prototype.getStats) {
  4104. var nativeGetstats = obj.prototype.getStats;
  4105. obj.prototype.getStats = function() {
  4106. return nativeGetstats.apply(this)
  4107. .then(function(nativeStats) {
  4108. var mapStats = new Map();
  4109. Object.keys(nativeStats).forEach(function(id) {
  4110. nativeStats[id].type = fixStatsType(nativeStats[id]);
  4111. mapStats.set(id, nativeStats[id]);
  4112. });
  4113. return mapStats;
  4114. });
  4115. };
  4116. }
  4117. });
  4118. // legacy callback shims. Should be moved to adapter.js some days.
  4119. var methods = ['createOffer', 'createAnswer'];
  4120. methods.forEach(function(method) {
  4121. var nativeMethod = RTCPeerConnection.prototype[method];
  4122. RTCPeerConnection.prototype[method] = function() {
  4123. var args = arguments;
  4124. if (typeof args[0] === 'function' ||
  4125. typeof args[1] === 'function') { // legacy
  4126. return nativeMethod.apply(this, [arguments[2]])
  4127. .then(function(description) {
  4128. if (typeof args[0] === 'function') {
  4129. args[0].apply(null, [description]);
  4130. }
  4131. }, function(error) {
  4132. if (typeof args[1] === 'function') {
  4133. args[1].apply(null, [error]);
  4134. }
  4135. });
  4136. }
  4137. return nativeMethod.apply(this, arguments);
  4138. };
  4139. });
  4140. methods = ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate'];
  4141. methods.forEach(function(method) {
  4142. var nativeMethod = RTCPeerConnection.prototype[method];
  4143. RTCPeerConnection.prototype[method] = function() {
  4144. var args = arguments;
  4145. if (typeof args[1] === 'function' ||
  4146. typeof args[2] === 'function') { // legacy
  4147. return nativeMethod.apply(this, arguments)
  4148. .then(function() {
  4149. if (typeof args[1] === 'function') {
  4150. args[1].apply(null);
  4151. }
  4152. }, function(error) {
  4153. if (typeof args[2] === 'function') {
  4154. args[2].apply(null, [error]);
  4155. }
  4156. });
  4157. }
  4158. return nativeMethod.apply(this, arguments);
  4159. };
  4160. });
  4161. // getStats is special. It doesn't have a spec legacy method yet we support
  4162. // getStats(something, cb) without error callbacks.
  4163. ['getStats'].forEach(function(method) {
  4164. var nativeMethod = RTCPeerConnection.prototype[method];
  4165. RTCPeerConnection.prototype[method] = function() {
  4166. var args = arguments;
  4167. if (typeof args[1] === 'function') {
  4168. return nativeMethod.apply(this, arguments)
  4169. .then(function() {
  4170. if (typeof args[1] === 'function') {
  4171. args[1].apply(null);
  4172. }
  4173. });
  4174. }
  4175. return nativeMethod.apply(this, arguments);
  4176. };
  4177. });
  4178. return RTCPeerConnection;
  4179. };
  4180. /*
  4181. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  4182. *
  4183. * Use of this source code is governed by a BSD-style license
  4184. * that can be found in the LICENSE file in the root of the source
  4185. * tree.
  4186. */
  4187. function shimGetUserMedia$2(window) {
  4188. const navigator = window && window.navigator;
  4189. const shimError_ = function(e) {
  4190. return {
  4191. name: {
  4192. PermissionDeniedError: 'NotAllowedError'
  4193. } [e.name] || e.name,
  4194. message: e.message,
  4195. constraint: e.constraint,
  4196. toString() {
  4197. return this.name;
  4198. }
  4199. };
  4200. };
  4201. // getUserMedia error shim.
  4202. const origGetUserMedia = navigator.mediaDevices.getUserMedia.
  4203. bind(navigator.mediaDevices);
  4204. navigator.mediaDevices.getUserMedia = function(c) {
  4205. return origGetUserMedia(c).catch(e => Promise.reject(shimError_(e)));
  4206. };
  4207. }
  4208. /*
  4209. * Copyright (c) 2018 The adapter.js project authors. All Rights Reserved.
  4210. *
  4211. * Use of this source code is governed by a BSD-style license
  4212. * that can be found in the LICENSE file in the root of the source
  4213. * tree.
  4214. */
  4215. function shimGetDisplayMedia$1(window) {
  4216. if (!('getDisplayMedia' in window.navigator)) {
  4217. return;
  4218. }
  4219. if (!(window.navigator.mediaDevices)) {
  4220. return;
  4221. }
  4222. if (window.navigator.mediaDevices &&
  4223. 'getDisplayMedia' in window.navigator.mediaDevices) {
  4224. return;
  4225. }
  4226. window.navigator.mediaDevices.getDisplayMedia =
  4227. window.navigator.getDisplayMedia.bind(window.navigator);
  4228. }
  4229. /*
  4230. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  4231. *
  4232. * Use of this source code is governed by a BSD-style license
  4233. * that can be found in the LICENSE file in the root of the source
  4234. * tree.
  4235. */
  4236. function shimPeerConnection$1(window, browserDetails) {
  4237. if (window.RTCIceGatherer) {
  4238. if (!window.RTCIceCandidate) {
  4239. window.RTCIceCandidate = function RTCIceCandidate(args) {
  4240. return args;
  4241. };
  4242. }
  4243. if (!window.RTCSessionDescription) {
  4244. window.RTCSessionDescription = function RTCSessionDescription(args) {
  4245. return args;
  4246. };
  4247. }
  4248. // this adds an additional event listener to MediaStrackTrack that signals
  4249. // when a tracks enabled property was changed. Workaround for a bug in
  4250. // addStream, see below. No longer required in 15025+
  4251. if (browserDetails.version < 15025) {
  4252. const origMSTEnabled = Object.getOwnPropertyDescriptor(
  4253. window.MediaStreamTrack.prototype, 'enabled');
  4254. Object.defineProperty(window.MediaStreamTrack.prototype, 'enabled', {
  4255. set(value) {
  4256. origMSTEnabled.set.call(this, value);
  4257. const ev = new Event('enabled');
  4258. ev.enabled = value;
  4259. this.dispatchEvent(ev);
  4260. }
  4261. });
  4262. }
  4263. }
  4264. // ORTC defines the DTMF sender a bit different.
  4265. // https://github.com/w3c/ortc/issues/714
  4266. if (window.RTCRtpSender && !('dtmf' in window.RTCRtpSender.prototype)) {
  4267. Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', {
  4268. get() {
  4269. if (this._dtmf === undefined) {
  4270. if (this.track.kind === 'audio') {
  4271. this._dtmf = new window.RTCDtmfSender(this);
  4272. } else if (this.track.kind === 'video') {
  4273. this._dtmf = null;
  4274. }
  4275. }
  4276. return this._dtmf;
  4277. }
  4278. });
  4279. }
  4280. // Edge currently only implements the RTCDtmfSender, not the
  4281. // RTCDTMFSender alias. See http://draft.ortc.org/#rtcdtmfsender2*
  4282. if (window.RTCDtmfSender && !window.RTCDTMFSender) {
  4283. window.RTCDTMFSender = window.RTCDtmfSender;
  4284. }
  4285. const RTCPeerConnectionShim = rtcpeerconnection(window,
  4286. browserDetails.version);
  4287. window.RTCPeerConnection = function RTCPeerConnection(config) {
  4288. if (config && config.iceServers) {
  4289. config.iceServers = filterIceServers$1(config.iceServers,
  4290. browserDetails.version);
  4291. log$1('ICE servers after filtering:', config.iceServers);
  4292. }
  4293. return new RTCPeerConnectionShim(config);
  4294. };
  4295. window.RTCPeerConnection.prototype = RTCPeerConnectionShim.prototype;
  4296. }
  4297. function shimReplaceTrack(window) {
  4298. // ORTC has replaceTrack -- https://github.com/w3c/ortc/issues/614
  4299. if (window.RTCRtpSender &&
  4300. !('replaceTrack' in window.RTCRtpSender.prototype)) {
  4301. window.RTCRtpSender.prototype.replaceTrack =
  4302. window.RTCRtpSender.prototype.setTrack;
  4303. }
  4304. }
  4305. var edgeShim = /*#__PURE__*/ Object.freeze({
  4306. __proto__: null,
  4307. shimPeerConnection: shimPeerConnection$1,
  4308. shimReplaceTrack: shimReplaceTrack,
  4309. shimGetUserMedia: shimGetUserMedia$2,
  4310. shimGetDisplayMedia: shimGetDisplayMedia$1
  4311. });
  4312. /*
  4313. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  4314. *
  4315. * Use of this source code is governed by a BSD-style license
  4316. * that can be found in the LICENSE file in the root of the source
  4317. * tree.
  4318. */
  4319. function shimGetUserMedia$1(window, browserDetails) {
  4320. const navigator = window && window.navigator;
  4321. const MediaStreamTrack = window && window.MediaStreamTrack;
  4322. navigator.getUserMedia = function(constraints, onSuccess, onError) {
  4323. // Replace Firefox 44+'s deprecation warning with unprefixed version.
  4324. deprecated('navigator.getUserMedia',
  4325. 'navigator.mediaDevices.getUserMedia');
  4326. navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);
  4327. };
  4328. if (!(browserDetails.version > 55 &&
  4329. 'autoGainControl' in navigator.mediaDevices.getSupportedConstraints())) {
  4330. const remap = function(obj, a, b) {
  4331. if (a in obj && !(b in obj)) {
  4332. obj[b] = obj[a];
  4333. delete obj[a];
  4334. }
  4335. };
  4336. const nativeGetUserMedia = navigator.mediaDevices.getUserMedia.
  4337. bind(navigator.mediaDevices);
  4338. navigator.mediaDevices.getUserMedia = function(c) {
  4339. if (typeof c === 'object' && typeof c.audio === 'object') {
  4340. c = JSON.parse(JSON.stringify(c));
  4341. remap(c.audio, 'autoGainControl', 'mozAutoGainControl');
  4342. remap(c.audio, 'noiseSuppression', 'mozNoiseSuppression');
  4343. }
  4344. return nativeGetUserMedia(c);
  4345. };
  4346. if (MediaStreamTrack && MediaStreamTrack.prototype.getSettings) {
  4347. const nativeGetSettings = MediaStreamTrack.prototype.getSettings;
  4348. MediaStreamTrack.prototype.getSettings = function() {
  4349. const obj = nativeGetSettings.apply(this, arguments);
  4350. remap(obj, 'mozAutoGainControl', 'autoGainControl');
  4351. remap(obj, 'mozNoiseSuppression', 'noiseSuppression');
  4352. return obj;
  4353. };
  4354. }
  4355. if (MediaStreamTrack && MediaStreamTrack.prototype.applyConstraints) {
  4356. const nativeApplyConstraints =
  4357. MediaStreamTrack.prototype.applyConstraints;
  4358. MediaStreamTrack.prototype.applyConstraints = function(c) {
  4359. if (this.kind === 'audio' && typeof c === 'object') {
  4360. c = JSON.parse(JSON.stringify(c));
  4361. remap(c, 'autoGainControl', 'mozAutoGainControl');
  4362. remap(c, 'noiseSuppression', 'mozNoiseSuppression');
  4363. }
  4364. return nativeApplyConstraints.apply(this, [c]);
  4365. };
  4366. }
  4367. }
  4368. }
  4369. /*
  4370. * Copyright (c) 2018 The adapter.js project authors. All Rights Reserved.
  4371. *
  4372. * Use of this source code is governed by a BSD-style license
  4373. * that can be found in the LICENSE file in the root of the source
  4374. * tree.
  4375. */
  4376. function shimGetDisplayMedia(window, preferredMediaSource) {
  4377. if (window.navigator.mediaDevices &&
  4378. 'getDisplayMedia' in window.navigator.mediaDevices) {
  4379. return;
  4380. }
  4381. if (!(window.navigator.mediaDevices)) {
  4382. return;
  4383. }
  4384. window.navigator.mediaDevices.getDisplayMedia =
  4385. function getDisplayMedia(constraints) {
  4386. if (!(constraints && constraints.video)) {
  4387. const err = new DOMException('getDisplayMedia without video ' +
  4388. 'constraints is undefined');
  4389. err.name = 'NotFoundError';
  4390. // from https://heycam.github.io/webidl/#idl-DOMException-error-names
  4391. err.code = 8;
  4392. return Promise.reject(err);
  4393. }
  4394. if (constraints.video === true) {
  4395. constraints.video = {
  4396. mediaSource: preferredMediaSource
  4397. };
  4398. } else {
  4399. constraints.video.mediaSource = preferredMediaSource;
  4400. }
  4401. return window.navigator.mediaDevices.getUserMedia(constraints);
  4402. };
  4403. }
  4404. /*
  4405. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  4406. *
  4407. * Use of this source code is governed by a BSD-style license
  4408. * that can be found in the LICENSE file in the root of the source
  4409. * tree.
  4410. */
  4411. function shimOnTrack(window) {
  4412. if (typeof window === 'object' && window.RTCTrackEvent &&
  4413. ('receiver' in window.RTCTrackEvent.prototype) &&
  4414. !('transceiver' in window.RTCTrackEvent.prototype)) {
  4415. Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {
  4416. get() {
  4417. return {
  4418. receiver: this.receiver
  4419. };
  4420. }
  4421. });
  4422. }
  4423. }
  4424. function shimPeerConnection(window, browserDetails) {
  4425. if (typeof window !== 'object' ||
  4426. !(window.RTCPeerConnection || window.mozRTCPeerConnection)) {
  4427. return; // probably media.peerconnection.enabled=false in about:config
  4428. }
  4429. if (!window.RTCPeerConnection && window.mozRTCPeerConnection) {
  4430. // very basic support for old versions.
  4431. window.RTCPeerConnection = window.mozRTCPeerConnection;
  4432. }
  4433. if (browserDetails.version < 53) {
  4434. // shim away need for obsolete RTCIceCandidate/RTCSessionDescription.
  4435. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
  4436. .forEach(function(method) {
  4437. const nativeMethod = window.RTCPeerConnection.prototype[method];
  4438. const methodObj = {
  4439. [method]() {
  4440. arguments[0] = new((method === 'addIceCandidate') ?
  4441. window.RTCIceCandidate :
  4442. window.RTCSessionDescription)(arguments[0]);
  4443. return nativeMethod.apply(this, arguments);
  4444. }
  4445. };
  4446. window.RTCPeerConnection.prototype[method] = methodObj[method];
  4447. });
  4448. }
  4449. const modernStatsTypes = {
  4450. inboundrtp: 'inbound-rtp',
  4451. outboundrtp: 'outbound-rtp',
  4452. candidatepair: 'candidate-pair',
  4453. localcandidate: 'local-candidate',
  4454. remotecandidate: 'remote-candidate'
  4455. };
  4456. const nativeGetStats = window.RTCPeerConnection.prototype.getStats;
  4457. window.RTCPeerConnection.prototype.getStats = function getStats() {
  4458. const [selector, onSucc, onErr] = arguments;
  4459. return nativeGetStats.apply(this, [selector || null])
  4460. .then(stats => {
  4461. if (browserDetails.version < 53 && !onSucc) {
  4462. // Shim only promise getStats with spec-hyphens in type names
  4463. // Leave callback version alone; misc old uses of forEach before Map
  4464. try {
  4465. stats.forEach(stat => {
  4466. stat.type = modernStatsTypes[stat.type] || stat.type;
  4467. });
  4468. } catch (e) {
  4469. if (e.name !== 'TypeError') {
  4470. throw e;
  4471. }
  4472. // Avoid TypeError: "type" is read-only, in old versions. 34-43ish
  4473. stats.forEach((stat, i) => {
  4474. stats.set(i, Object.assign({}, stat, {
  4475. type: modernStatsTypes[stat.type] || stat.type
  4476. }));
  4477. });
  4478. }
  4479. }
  4480. return stats;
  4481. })
  4482. .then(onSucc, onErr);
  4483. };
  4484. }
  4485. function shimSenderGetStats(window) {
  4486. if (!(typeof window === 'object' && window.RTCPeerConnection &&
  4487. window.RTCRtpSender)) {
  4488. return;
  4489. }
  4490. if (window.RTCRtpSender && 'getStats' in window.RTCRtpSender.prototype) {
  4491. return;
  4492. }
  4493. const origGetSenders = window.RTCPeerConnection.prototype.getSenders;
  4494. if (origGetSenders) {
  4495. window.RTCPeerConnection.prototype.getSenders = function getSenders() {
  4496. const senders = origGetSenders.apply(this, []);
  4497. senders.forEach(sender => sender._pc = this);
  4498. return senders;
  4499. };
  4500. }
  4501. const origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  4502. if (origAddTrack) {
  4503. window.RTCPeerConnection.prototype.addTrack = function addTrack() {
  4504. const sender = origAddTrack.apply(this, arguments);
  4505. sender._pc = this;
  4506. return sender;
  4507. };
  4508. }
  4509. window.RTCRtpSender.prototype.getStats = function getStats() {
  4510. return this.track ? this._pc.getStats(this.track) :
  4511. Promise.resolve(new Map());
  4512. };
  4513. }
  4514. function shimReceiverGetStats(window) {
  4515. if (!(typeof window === 'object' && window.RTCPeerConnection &&
  4516. window.RTCRtpSender)) {
  4517. return;
  4518. }
  4519. if (window.RTCRtpSender && 'getStats' in window.RTCRtpReceiver.prototype) {
  4520. return;
  4521. }
  4522. const origGetReceivers = window.RTCPeerConnection.prototype.getReceivers;
  4523. if (origGetReceivers) {
  4524. window.RTCPeerConnection.prototype.getReceivers = function getReceivers() {
  4525. const receivers = origGetReceivers.apply(this, []);
  4526. receivers.forEach(receiver => receiver._pc = this);
  4527. return receivers;
  4528. };
  4529. }
  4530. wrapPeerConnectionEvent(window, 'track', e => {
  4531. e.receiver._pc = e.srcElement;
  4532. return e;
  4533. });
  4534. window.RTCRtpReceiver.prototype.getStats = function getStats() {
  4535. return this._pc.getStats(this.track);
  4536. };
  4537. }
  4538. function shimRemoveStream(window) {
  4539. if (!window.RTCPeerConnection ||
  4540. 'removeStream' in window.RTCPeerConnection.prototype) {
  4541. return;
  4542. }
  4543. window.RTCPeerConnection.prototype.removeStream =
  4544. function removeStream(stream) {
  4545. deprecated('removeStream', 'removeTrack');
  4546. this.getSenders().forEach(sender => {
  4547. if (sender.track && stream.getTracks().includes(sender.track)) {
  4548. this.removeTrack(sender);
  4549. }
  4550. });
  4551. };
  4552. }
  4553. function shimRTCDataChannel(window) {
  4554. // rename DataChannel to RTCDataChannel (native fix in FF60):
  4555. // https://bugzilla.mozilla.org/show_bug.cgi?id=1173851
  4556. if (window.DataChannel && !window.RTCDataChannel) {
  4557. window.RTCDataChannel = window.DataChannel;
  4558. }
  4559. }
  4560. function shimAddTransceiver(window) {
  4561. // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647
  4562. // Firefox ignores the init sendEncodings options passed to addTransceiver
  4563. // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918
  4564. if (!(typeof window === 'object' && window.RTCPeerConnection)) {
  4565. return;
  4566. }
  4567. const origAddTransceiver = window.RTCPeerConnection.prototype.addTransceiver;
  4568. if (origAddTransceiver) {
  4569. window.RTCPeerConnection.prototype.addTransceiver =
  4570. function addTransceiver() {
  4571. this.setParametersPromises = [];
  4572. const initParameters = arguments[1];
  4573. const shouldPerformCheck = initParameters &&
  4574. 'sendEncodings' in initParameters;
  4575. if (shouldPerformCheck) {
  4576. // If sendEncodings params are provided, validate grammar
  4577. initParameters.sendEncodings.forEach((encodingParam) => {
  4578. if ('rid' in encodingParam) {
  4579. const ridRegex = /^[a-z0-9]{0,16}$/i;
  4580. if (!ridRegex.test(encodingParam.rid)) {
  4581. throw new TypeError('Invalid RID value provided.');
  4582. }
  4583. }
  4584. if ('scaleResolutionDownBy' in encodingParam) {
  4585. if (!(parseFloat(encodingParam.scaleResolutionDownBy) >= 1.0)) {
  4586. throw new RangeError('scale_resolution_down_by must be >= 1.0');
  4587. }
  4588. }
  4589. if ('maxFramerate' in encodingParam) {
  4590. if (!(parseFloat(encodingParam.maxFramerate) >= 0)) {
  4591. throw new RangeError('max_framerate must be >= 0.0');
  4592. }
  4593. }
  4594. });
  4595. }
  4596. const transceiver = origAddTransceiver.apply(this, arguments);
  4597. if (shouldPerformCheck) {
  4598. // Check if the init options were applied. If not we do this in an
  4599. // asynchronous way and save the promise reference in a global object.
  4600. // This is an ugly hack, but at the same time is way more robust than
  4601. // checking the sender parameters before and after the createOffer
  4602. // Also note that after the createoffer we are not 100% sure that
  4603. // the params were asynchronously applied so we might miss the
  4604. // opportunity to recreate offer.
  4605. const {
  4606. sender
  4607. } = transceiver;
  4608. const params = sender.getParameters();
  4609. if (!('encodings' in params) ||
  4610. // Avoid being fooled by patched getParameters() below.
  4611. (params.encodings.length === 1 &&
  4612. Object.keys(params.encodings[0]).length === 0)) {
  4613. params.encodings = initParameters.sendEncodings;
  4614. sender.sendEncodings = initParameters.sendEncodings;
  4615. this.setParametersPromises.push(sender.setParameters(params)
  4616. .then(() => {
  4617. delete sender.sendEncodings;
  4618. }).catch(() => {
  4619. delete sender.sendEncodings;
  4620. })
  4621. );
  4622. }
  4623. }
  4624. return transceiver;
  4625. };
  4626. }
  4627. }
  4628. function shimGetParameters(window) {
  4629. if (!(typeof window === 'object' && window.RTCRtpSender)) {
  4630. return;
  4631. }
  4632. const origGetParameters = window.RTCRtpSender.prototype.getParameters;
  4633. if (origGetParameters) {
  4634. window.RTCRtpSender.prototype.getParameters =
  4635. function getParameters() {
  4636. const params = origGetParameters.apply(this, arguments);
  4637. if (!('encodings' in params)) {
  4638. params.encodings = [].concat(this.sendEncodings || [{}]);
  4639. }
  4640. return params;
  4641. };
  4642. }
  4643. }
  4644. function shimCreateOffer(window) {
  4645. // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647
  4646. // Firefox ignores the init sendEncodings options passed to addTransceiver
  4647. // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918
  4648. if (!(typeof window === 'object' && window.RTCPeerConnection)) {
  4649. return;
  4650. }
  4651. const origCreateOffer = window.RTCPeerConnection.prototype.createOffer;
  4652. window.RTCPeerConnection.prototype.createOffer = function createOffer() {
  4653. if (this.setParametersPromises && this.setParametersPromises.length) {
  4654. return Promise.all(this.setParametersPromises)
  4655. .then(() => {
  4656. return origCreateOffer.apply(this, arguments);
  4657. })
  4658. .finally(() => {
  4659. this.setParametersPromises = [];
  4660. });
  4661. }
  4662. return origCreateOffer.apply(this, arguments);
  4663. };
  4664. }
  4665. function shimCreateAnswer(window) {
  4666. // https://github.com/webrtcHacks/adapter/issues/998#issuecomment-516921647
  4667. // Firefox ignores the init sendEncodings options passed to addTransceiver
  4668. // https://bugzilla.mozilla.org/show_bug.cgi?id=1396918
  4669. if (!(typeof window === 'object' && window.RTCPeerConnection)) {
  4670. return;
  4671. }
  4672. const origCreateAnswer = window.RTCPeerConnection.prototype.createAnswer;
  4673. window.RTCPeerConnection.prototype.createAnswer = function createAnswer() {
  4674. if (this.setParametersPromises && this.setParametersPromises.length) {
  4675. return Promise.all(this.setParametersPromises)
  4676. .then(() => {
  4677. return origCreateAnswer.apply(this, arguments);
  4678. })
  4679. .finally(() => {
  4680. this.setParametersPromises = [];
  4681. });
  4682. }
  4683. return origCreateAnswer.apply(this, arguments);
  4684. };
  4685. }
  4686. var firefoxShim = /*#__PURE__*/ Object.freeze({
  4687. __proto__: null,
  4688. shimOnTrack: shimOnTrack,
  4689. shimPeerConnection: shimPeerConnection,
  4690. shimSenderGetStats: shimSenderGetStats,
  4691. shimReceiverGetStats: shimReceiverGetStats,
  4692. shimRemoveStream: shimRemoveStream,
  4693. shimRTCDataChannel: shimRTCDataChannel,
  4694. shimAddTransceiver: shimAddTransceiver,
  4695. shimGetParameters: shimGetParameters,
  4696. shimCreateOffer: shimCreateOffer,
  4697. shimCreateAnswer: shimCreateAnswer,
  4698. shimGetUserMedia: shimGetUserMedia$1,
  4699. shimGetDisplayMedia: shimGetDisplayMedia
  4700. });
  4701. /*
  4702. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  4703. *
  4704. * Use of this source code is governed by a BSD-style license
  4705. * that can be found in the LICENSE file in the root of the source
  4706. * tree.
  4707. */
  4708. function shimLocalStreamsAPI(window) {
  4709. if (typeof window !== 'object' || !window.RTCPeerConnection) {
  4710. return;
  4711. }
  4712. if (!('getLocalStreams' in window.RTCPeerConnection.prototype)) {
  4713. window.RTCPeerConnection.prototype.getLocalStreams =
  4714. function getLocalStreams() {
  4715. if (!this._localStreams) {
  4716. this._localStreams = [];
  4717. }
  4718. return this._localStreams;
  4719. };
  4720. }
  4721. if (!('addStream' in window.RTCPeerConnection.prototype)) {
  4722. const _addTrack = window.RTCPeerConnection.prototype.addTrack;
  4723. window.RTCPeerConnection.prototype.addStream = function addStream(stream) {
  4724. if (!this._localStreams) {
  4725. this._localStreams = [];
  4726. }
  4727. if (!this._localStreams.includes(stream)) {
  4728. this._localStreams.push(stream);
  4729. }
  4730. // Try to emulate Chrome's behaviour of adding in audio-video order.
  4731. // Safari orders by track id.
  4732. stream.getAudioTracks().forEach(track => _addTrack.call(this, track,
  4733. stream));
  4734. stream.getVideoTracks().forEach(track => _addTrack.call(this, track,
  4735. stream));
  4736. };
  4737. window.RTCPeerConnection.prototype.addTrack =
  4738. function addTrack(track, ...streams) {
  4739. if (streams) {
  4740. streams.forEach((stream) => {
  4741. if (!this._localStreams) {
  4742. this._localStreams = [stream];
  4743. } else if (!this._localStreams.includes(stream)) {
  4744. this._localStreams.push(stream);
  4745. }
  4746. });
  4747. }
  4748. return _addTrack.apply(this, arguments);
  4749. };
  4750. }
  4751. if (!('removeStream' in window.RTCPeerConnection.prototype)) {
  4752. window.RTCPeerConnection.prototype.removeStream =
  4753. function removeStream(stream) {
  4754. if (!this._localStreams) {
  4755. this._localStreams = [];
  4756. }
  4757. const index = this._localStreams.indexOf(stream);
  4758. if (index === -1) {
  4759. return;
  4760. }
  4761. this._localStreams.splice(index, 1);
  4762. const tracks = stream.getTracks();
  4763. this.getSenders().forEach(sender => {
  4764. if (tracks.includes(sender.track)) {
  4765. this.removeTrack(sender);
  4766. }
  4767. });
  4768. };
  4769. }
  4770. }
  4771. function shimRemoteStreamsAPI(window) {
  4772. if (typeof window !== 'object' || !window.RTCPeerConnection) {
  4773. return;
  4774. }
  4775. if (!('getRemoteStreams' in window.RTCPeerConnection.prototype)) {
  4776. window.RTCPeerConnection.prototype.getRemoteStreams =
  4777. function getRemoteStreams() {
  4778. return this._remoteStreams ? this._remoteStreams : [];
  4779. };
  4780. }
  4781. if (!('onaddstream' in window.RTCPeerConnection.prototype)) {
  4782. Object.defineProperty(window.RTCPeerConnection.prototype, 'onaddstream', {
  4783. get() {
  4784. return this._onaddstream;
  4785. },
  4786. set(f) {
  4787. if (this._onaddstream) {
  4788. this.removeEventListener('addstream', this._onaddstream);
  4789. this.removeEventListener('track', this._onaddstreampoly);
  4790. }
  4791. this.addEventListener('addstream', this._onaddstream = f);
  4792. this.addEventListener('track', this._onaddstreampoly = (e) => {
  4793. e.streams.forEach(stream => {
  4794. if (!this._remoteStreams) {
  4795. this._remoteStreams = [];
  4796. }
  4797. if (this._remoteStreams.includes(stream)) {
  4798. return;
  4799. }
  4800. this._remoteStreams.push(stream);
  4801. const event = new Event('addstream');
  4802. event.stream = stream;
  4803. this.dispatchEvent(event);
  4804. });
  4805. });
  4806. }
  4807. });
  4808. const origSetRemoteDescription =
  4809. window.RTCPeerConnection.prototype.setRemoteDescription;
  4810. window.RTCPeerConnection.prototype.setRemoteDescription =
  4811. function setRemoteDescription() {
  4812. const pc = this;
  4813. if (!this._onaddstreampoly) {
  4814. this.addEventListener('track', this._onaddstreampoly = function(e) {
  4815. e.streams.forEach(stream => {
  4816. if (!pc._remoteStreams) {
  4817. pc._remoteStreams = [];
  4818. }
  4819. if (pc._remoteStreams.indexOf(stream) >= 0) {
  4820. return;
  4821. }
  4822. pc._remoteStreams.push(stream);
  4823. const event = new Event('addstream');
  4824. event.stream = stream;
  4825. pc.dispatchEvent(event);
  4826. });
  4827. });
  4828. }
  4829. return origSetRemoteDescription.apply(pc, arguments);
  4830. };
  4831. }
  4832. }
  4833. function shimCallbacksAPI(window) {
  4834. if (typeof window !== 'object' || !window.RTCPeerConnection) {
  4835. return;
  4836. }
  4837. const prototype = window.RTCPeerConnection.prototype;
  4838. const origCreateOffer = prototype.createOffer;
  4839. const origCreateAnswer = prototype.createAnswer;
  4840. const setLocalDescription = prototype.setLocalDescription;
  4841. const setRemoteDescription = prototype.setRemoteDescription;
  4842. const addIceCandidate = prototype.addIceCandidate;
  4843. prototype.createOffer =
  4844. function createOffer(successCallback, failureCallback) {
  4845. const options = (arguments.length >= 2) ? arguments[2] : arguments[0];
  4846. const promise = origCreateOffer.apply(this, [options]);
  4847. if (!failureCallback) {
  4848. return promise;
  4849. }
  4850. promise.then(successCallback, failureCallback);
  4851. return Promise.resolve();
  4852. };
  4853. prototype.createAnswer =
  4854. function createAnswer(successCallback, failureCallback) {
  4855. const options = (arguments.length >= 2) ? arguments[2] : arguments[0];
  4856. const promise = origCreateAnswer.apply(this, [options]);
  4857. if (!failureCallback) {
  4858. return promise;
  4859. }
  4860. promise.then(successCallback, failureCallback);
  4861. return Promise.resolve();
  4862. };
  4863. let withCallback = function(description, successCallback, failureCallback) {
  4864. const promise = setLocalDescription.apply(this, [description]);
  4865. if (!failureCallback) {
  4866. return promise;
  4867. }
  4868. promise.then(successCallback, failureCallback);
  4869. return Promise.resolve();
  4870. };
  4871. prototype.setLocalDescription = withCallback;
  4872. withCallback = function(description, successCallback, failureCallback) {
  4873. const promise = setRemoteDescription.apply(this, [description]);
  4874. if (!failureCallback) {
  4875. return promise;
  4876. }
  4877. promise.then(successCallback, failureCallback);
  4878. return Promise.resolve();
  4879. };
  4880. prototype.setRemoteDescription = withCallback;
  4881. withCallback = function(candidate, successCallback, failureCallback) {
  4882. const promise = addIceCandidate.apply(this, [candidate]);
  4883. if (!failureCallback) {
  4884. return promise;
  4885. }
  4886. promise.then(successCallback, failureCallback);
  4887. return Promise.resolve();
  4888. };
  4889. prototype.addIceCandidate = withCallback;
  4890. }
  4891. function shimGetUserMedia(window) {
  4892. const navigator = window && window.navigator;
  4893. if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
  4894. // shim not needed in Safari 12.1
  4895. const mediaDevices = navigator.mediaDevices;
  4896. const _getUserMedia = mediaDevices.getUserMedia.bind(mediaDevices);
  4897. navigator.mediaDevices.getUserMedia = (constraints) => {
  4898. return _getUserMedia(shimConstraints(constraints));
  4899. };
  4900. }
  4901. if (!navigator.getUserMedia && navigator.mediaDevices &&
  4902. navigator.mediaDevices.getUserMedia) {
  4903. navigator.getUserMedia = function getUserMedia(constraints, cb, errcb) {
  4904. navigator.mediaDevices.getUserMedia(constraints)
  4905. .then(cb, errcb);
  4906. }.bind(navigator);
  4907. }
  4908. }
  4909. function shimConstraints(constraints) {
  4910. if (constraints && constraints.video !== undefined) {
  4911. return Object.assign({},
  4912. constraints, {
  4913. video: compactObject(constraints.video)
  4914. }
  4915. );
  4916. }
  4917. return constraints;
  4918. }
  4919. function shimRTCIceServerUrls(window) {
  4920. if (!window.RTCPeerConnection) {
  4921. return;
  4922. }
  4923. // migrate from non-spec RTCIceServer.url to RTCIceServer.urls
  4924. const OrigPeerConnection = window.RTCPeerConnection;
  4925. window.RTCPeerConnection =
  4926. function RTCPeerConnection(pcConfig, pcConstraints) {
  4927. if (pcConfig && pcConfig.iceServers) {
  4928. const newIceServers = [];
  4929. for (let i = 0; i < pcConfig.iceServers.length; i++) {
  4930. let server = pcConfig.iceServers[i];
  4931. if (!server.hasOwnProperty('urls') &&
  4932. server.hasOwnProperty('url')) {
  4933. deprecated('RTCIceServer.url', 'RTCIceServer.urls');
  4934. server = JSON.parse(JSON.stringify(server));
  4935. server.urls = server.url;
  4936. delete server.url;
  4937. newIceServers.push(server);
  4938. } else {
  4939. newIceServers.push(pcConfig.iceServers[i]);
  4940. }
  4941. }
  4942. pcConfig.iceServers = newIceServers;
  4943. }
  4944. return new OrigPeerConnection(pcConfig, pcConstraints);
  4945. };
  4946. window.RTCPeerConnection.prototype = OrigPeerConnection.prototype;
  4947. // wrap static methods. Currently just generateCertificate.
  4948. if ('generateCertificate' in OrigPeerConnection) {
  4949. Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
  4950. get() {
  4951. return OrigPeerConnection.generateCertificate;
  4952. }
  4953. });
  4954. }
  4955. }
  4956. function shimTrackEventTransceiver(window) {
  4957. // Add event.transceiver member over deprecated event.receiver
  4958. if (typeof window === 'object' && window.RTCTrackEvent &&
  4959. 'receiver' in window.RTCTrackEvent.prototype &&
  4960. !('transceiver' in window.RTCTrackEvent.prototype)) {
  4961. Object.defineProperty(window.RTCTrackEvent.prototype, 'transceiver', {
  4962. get() {
  4963. return {
  4964. receiver: this.receiver
  4965. };
  4966. }
  4967. });
  4968. }
  4969. }
  4970. function shimCreateOfferLegacy(window) {
  4971. const origCreateOffer = window.RTCPeerConnection.prototype.createOffer;
  4972. window.RTCPeerConnection.prototype.createOffer =
  4973. function createOffer(offerOptions) {
  4974. if (offerOptions) {
  4975. if (typeof offerOptions.offerToReceiveAudio !== 'undefined') {
  4976. // support bit values
  4977. offerOptions.offerToReceiveAudio = !!offerOptions.offerToReceiveAudio;
  4978. }
  4979. const audioTransceiver = this.getTransceivers().find(transceiver =>
  4980. transceiver.receiver.track.kind === 'audio');
  4981. if (offerOptions.offerToReceiveAudio === false && audioTransceiver) {
  4982. if (audioTransceiver.direction === 'sendrecv') {
  4983. if (audioTransceiver.setDirection) {
  4984. audioTransceiver.setDirection('sendonly');
  4985. } else {
  4986. audioTransceiver.direction = 'sendonly';
  4987. }
  4988. } else if (audioTransceiver.direction === 'recvonly') {
  4989. if (audioTransceiver.setDirection) {
  4990. audioTransceiver.setDirection('inactive');
  4991. } else {
  4992. audioTransceiver.direction = 'inactive';
  4993. }
  4994. }
  4995. } else if (offerOptions.offerToReceiveAudio === true &&
  4996. !audioTransceiver) {
  4997. this.addTransceiver('audio');
  4998. }
  4999. if (typeof offerOptions.offerToReceiveVideo !== 'undefined') {
  5000. // support bit values
  5001. offerOptions.offerToReceiveVideo = !!offerOptions.offerToReceiveVideo;
  5002. }
  5003. const videoTransceiver = this.getTransceivers().find(transceiver =>
  5004. transceiver.receiver.track.kind === 'video');
  5005. if (offerOptions.offerToReceiveVideo === false && videoTransceiver) {
  5006. if (videoTransceiver.direction === 'sendrecv') {
  5007. if (videoTransceiver.setDirection) {
  5008. videoTransceiver.setDirection('sendonly');
  5009. } else {
  5010. videoTransceiver.direction = 'sendonly';
  5011. }
  5012. } else if (videoTransceiver.direction === 'recvonly') {
  5013. if (videoTransceiver.setDirection) {
  5014. videoTransceiver.setDirection('inactive');
  5015. } else {
  5016. videoTransceiver.direction = 'inactive';
  5017. }
  5018. }
  5019. } else if (offerOptions.offerToReceiveVideo === true &&
  5020. !videoTransceiver) {
  5021. this.addTransceiver('video');
  5022. }
  5023. }
  5024. return origCreateOffer.apply(this, arguments);
  5025. };
  5026. }
  5027. function shimAudioContext(window) {
  5028. if (typeof window !== 'object' || window.AudioContext) {
  5029. return;
  5030. }
  5031. window.AudioContext = window.webkitAudioContext;
  5032. }
  5033. var safariShim = /*#__PURE__*/ Object.freeze({
  5034. __proto__: null,
  5035. shimLocalStreamsAPI: shimLocalStreamsAPI,
  5036. shimRemoteStreamsAPI: shimRemoteStreamsAPI,
  5037. shimCallbacksAPI: shimCallbacksAPI,
  5038. shimGetUserMedia: shimGetUserMedia,
  5039. shimConstraints: shimConstraints,
  5040. shimRTCIceServerUrls: shimRTCIceServerUrls,
  5041. shimTrackEventTransceiver: shimTrackEventTransceiver,
  5042. shimCreateOfferLegacy: shimCreateOfferLegacy,
  5043. shimAudioContext: shimAudioContext
  5044. });
  5045. /*
  5046. * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
  5047. *
  5048. * Use of this source code is governed by a BSD-style license
  5049. * that can be found in the LICENSE file in the root of the source
  5050. * tree.
  5051. */
  5052. function shimRTCIceCandidate(window) {
  5053. // foundation is arbitrarily chosen as an indicator for full support for
  5054. // https://w3c.github.io/webrtc-pc/#rtcicecandidate-interface
  5055. if (!window.RTCIceCandidate || (window.RTCIceCandidate && 'foundation' in
  5056. window.RTCIceCandidate.prototype)) {
  5057. return;
  5058. }
  5059. const NativeRTCIceCandidate = window.RTCIceCandidate;
  5060. window.RTCIceCandidate = function RTCIceCandidate(args) {
  5061. // Remove the a= which shouldn't be part of the candidate string.
  5062. if (typeof args === 'object' && args.candidate &&
  5063. args.candidate.indexOf('a=') === 0) {
  5064. args = JSON.parse(JSON.stringify(args));
  5065. args.candidate = args.candidate.substr(2);
  5066. }
  5067. if (args.candidate && args.candidate.length) {
  5068. // Augment the native candidate with the parsed fields.
  5069. const nativeCandidate = new NativeRTCIceCandidate(args);
  5070. const parsedCandidate = sdp.parseCandidate(args.candidate);
  5071. const augmentedCandidate = Object.assign(nativeCandidate,
  5072. parsedCandidate);
  5073. // Add a serializer that does not serialize the extra attributes.
  5074. augmentedCandidate.toJSON = function toJSON() {
  5075. return {
  5076. candidate: augmentedCandidate.candidate,
  5077. sdpMid: augmentedCandidate.sdpMid,
  5078. sdpMLineIndex: augmentedCandidate.sdpMLineIndex,
  5079. usernameFragment: augmentedCandidate.usernameFragment,
  5080. };
  5081. };
  5082. return augmentedCandidate;
  5083. }
  5084. return new NativeRTCIceCandidate(args);
  5085. };
  5086. window.RTCIceCandidate.prototype = NativeRTCIceCandidate.prototype;
  5087. // Hook up the augmented candidate in onicecandidate and
  5088. // addEventListener('icecandidate', ...)
  5089. wrapPeerConnectionEvent(window, 'icecandidate', e => {
  5090. if (e.candidate) {
  5091. Object.defineProperty(e, 'candidate', {
  5092. value: new window.RTCIceCandidate(e.candidate),
  5093. writable: 'false'
  5094. });
  5095. }
  5096. return e;
  5097. });
  5098. }
  5099. function shimMaxMessageSize(window, browserDetails) {
  5100. if (!window.RTCPeerConnection) {
  5101. return;
  5102. }
  5103. if (!('sctp' in window.RTCPeerConnection.prototype)) {
  5104. Object.defineProperty(window.RTCPeerConnection.prototype, 'sctp', {
  5105. get() {
  5106. return typeof this._sctp === 'undefined' ? null : this._sctp;
  5107. }
  5108. });
  5109. }
  5110. const sctpInDescription = function(description) {
  5111. if (!description || !description.sdp) {
  5112. return false;
  5113. }
  5114. const sections = sdp.splitSections(description.sdp);
  5115. sections.shift();
  5116. return sections.some(mediaSection => {
  5117. const mLine = sdp.parseMLine(mediaSection);
  5118. return mLine && mLine.kind === 'application' &&
  5119. mLine.protocol.indexOf('SCTP') !== -1;
  5120. });
  5121. };
  5122. const getRemoteFirefoxVersion = function(description) {
  5123. // TODO: Is there a better solution for detecting Firefox?
  5124. const match = description.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);
  5125. if (match === null || match.length < 2) {
  5126. return -1;
  5127. }
  5128. const version = parseInt(match[1], 10);
  5129. // Test for NaN (yes, this is ugly)
  5130. return version !== version ? -1 : version;
  5131. };
  5132. const getCanSendMaxMessageSize = function(remoteIsFirefox) {
  5133. // Every implementation we know can send at least 64 KiB.
  5134. // Note: Although Chrome is technically able to send up to 256 KiB, the
  5135. // data does not reach the other peer reliably.
  5136. // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=8419
  5137. let canSendMaxMessageSize = 65536;
  5138. if (browserDetails.browser === 'firefox') {
  5139. if (browserDetails.version < 57) {
  5140. if (remoteIsFirefox === -1) {
  5141. // FF < 57 will send in 16 KiB chunks using the deprecated PPID
  5142. // fragmentation.
  5143. canSendMaxMessageSize = 16384;
  5144. } else {
  5145. // However, other FF (and RAWRTC) can reassemble PPID-fragmented
  5146. // messages. Thus, supporting ~2 GiB when sending.
  5147. canSendMaxMessageSize = 2147483637;
  5148. }
  5149. } else if (browserDetails.version < 60) {
  5150. // Currently, all FF >= 57 will reset the remote maximum message size
  5151. // to the default value when a data channel is created at a later
  5152. // stage. :(
  5153. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831
  5154. canSendMaxMessageSize =
  5155. browserDetails.version === 57 ? 65535 : 65536;
  5156. } else {
  5157. // FF >= 60 supports sending ~2 GiB
  5158. canSendMaxMessageSize = 2147483637;
  5159. }
  5160. }
  5161. return canSendMaxMessageSize;
  5162. };
  5163. const getMaxMessageSize = function(description, remoteIsFirefox) {
  5164. // Note: 65536 bytes is the default value from the SDP spec. Also,
  5165. // every implementation we know supports receiving 65536 bytes.
  5166. let maxMessageSize = 65536;
  5167. // FF 57 has a slightly incorrect default remote max message size, so
  5168. // we need to adjust it here to avoid a failure when sending.
  5169. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1425697
  5170. if (browserDetails.browser === 'firefox' &&
  5171. browserDetails.version === 57) {
  5172. maxMessageSize = 65535;
  5173. }
  5174. const match = sdp.matchPrefix(description.sdp,
  5175. 'a=max-message-size:');
  5176. if (match.length > 0) {
  5177. maxMessageSize = parseInt(match[0].substr(19), 10);
  5178. } else if (browserDetails.browser === 'firefox' &&
  5179. remoteIsFirefox !== -1) {
  5180. // If the maximum message size is not present in the remote SDP and
  5181. // both local and remote are Firefox, the remote peer can receive
  5182. // ~2 GiB.
  5183. maxMessageSize = 2147483637;
  5184. }
  5185. return maxMessageSize;
  5186. };
  5187. const origSetRemoteDescription =
  5188. window.RTCPeerConnection.prototype.setRemoteDescription;
  5189. window.RTCPeerConnection.prototype.setRemoteDescription =
  5190. function setRemoteDescription() {
  5191. this._sctp = null;
  5192. // Chrome decided to not expose .sctp in plan-b mode.
  5193. // As usual, adapter.js has to do an 'ugly worakaround'
  5194. // to cover up the mess.
  5195. if (browserDetails.browser === 'chrome' && browserDetails.version >= 76) {
  5196. const {
  5197. sdpSemantics
  5198. } = this.getConfiguration();
  5199. if (sdpSemantics === 'plan-b') {
  5200. Object.defineProperty(this, 'sctp', {
  5201. get() {
  5202. return typeof this._sctp === 'undefined' ? null : this._sctp;
  5203. },
  5204. enumerable: true,
  5205. configurable: true,
  5206. });
  5207. }
  5208. }
  5209. if (sctpInDescription(arguments[0])) {
  5210. // Check if the remote is FF.
  5211. const isFirefox = getRemoteFirefoxVersion(arguments[0]);
  5212. // Get the maximum message size the local peer is capable of sending
  5213. const canSendMMS = getCanSendMaxMessageSize(isFirefox);
  5214. // Get the maximum message size of the remote peer.
  5215. const remoteMMS = getMaxMessageSize(arguments[0], isFirefox);
  5216. // Determine final maximum message size
  5217. let maxMessageSize;
  5218. if (canSendMMS === 0 && remoteMMS === 0) {
  5219. maxMessageSize = Number.POSITIVE_INFINITY;
  5220. } else if (canSendMMS === 0 || remoteMMS === 0) {
  5221. maxMessageSize = Math.max(canSendMMS, remoteMMS);
  5222. } else {
  5223. maxMessageSize = Math.min(canSendMMS, remoteMMS);
  5224. }
  5225. // Create a dummy RTCSctpTransport object and the 'maxMessageSize'
  5226. // attribute.
  5227. const sctp = {};
  5228. Object.defineProperty(sctp, 'maxMessageSize', {
  5229. get() {
  5230. return maxMessageSize;
  5231. }
  5232. });
  5233. this._sctp = sctp;
  5234. }
  5235. return origSetRemoteDescription.apply(this, arguments);
  5236. };
  5237. }
  5238. function shimSendThrowTypeError(window) {
  5239. if (!(window.RTCPeerConnection &&
  5240. 'createDataChannel' in window.RTCPeerConnection.prototype)) {
  5241. return;
  5242. }
  5243. // Note: Although Firefox >= 57 has a native implementation, the maximum
  5244. // message size can be reset for all data channels at a later stage.
  5245. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=1426831
  5246. function wrapDcSend(dc, pc) {
  5247. const origDataChannelSend = dc.send;
  5248. dc.send = function send() {
  5249. const data = arguments[0];
  5250. const length = data.length || data.size || data.byteLength;
  5251. if (dc.readyState === 'open' &&
  5252. pc.sctp && length > pc.sctp.maxMessageSize) {
  5253. throw new TypeError('Message too large (can send a maximum of ' +
  5254. pc.sctp.maxMessageSize + ' bytes)');
  5255. }
  5256. return origDataChannelSend.apply(dc, arguments);
  5257. };
  5258. }
  5259. const origCreateDataChannel =
  5260. window.RTCPeerConnection.prototype.createDataChannel;
  5261. window.RTCPeerConnection.prototype.createDataChannel =
  5262. function createDataChannel() {
  5263. const dataChannel = origCreateDataChannel.apply(this, arguments);
  5264. wrapDcSend(dataChannel, this);
  5265. return dataChannel;
  5266. };
  5267. wrapPeerConnectionEvent(window, 'datachannel', e => {
  5268. wrapDcSend(e.channel, e.target);
  5269. return e;
  5270. });
  5271. }
  5272. /* shims RTCConnectionState by pretending it is the same as iceConnectionState.
  5273. * See https://bugs.chromium.org/p/webrtc/issues/detail?id=6145#c12
  5274. * for why this is a valid hack in Chrome. In Firefox it is slightly incorrect
  5275. * since DTLS failures would be hidden. See
  5276. * https://bugzilla.mozilla.org/show_bug.cgi?id=1265827
  5277. * for the Firefox tracking bug.
  5278. */
  5279. function shimConnectionState(window) {
  5280. if (!window.RTCPeerConnection ||
  5281. 'connectionState' in window.RTCPeerConnection.prototype) {
  5282. return;
  5283. }
  5284. const proto = window.RTCPeerConnection.prototype;
  5285. Object.defineProperty(proto, 'connectionState', {
  5286. get() {
  5287. return {
  5288. completed: 'connected',
  5289. checking: 'connecting'
  5290. } [this.iceConnectionState] || this.iceConnectionState;
  5291. },
  5292. enumerable: true,
  5293. configurable: true
  5294. });
  5295. Object.defineProperty(proto, 'onconnectionstatechange', {
  5296. get() {
  5297. return this._onconnectionstatechange || null;
  5298. },
  5299. set(cb) {
  5300. if (this._onconnectionstatechange) {
  5301. this.removeEventListener('connectionstatechange',
  5302. this._onconnectionstatechange);
  5303. delete this._onconnectionstatechange;
  5304. }
  5305. if (cb) {
  5306. this.addEventListener('connectionstatechange',
  5307. this._onconnectionstatechange = cb);
  5308. }
  5309. },
  5310. enumerable: true,
  5311. configurable: true
  5312. });
  5313. ['setLocalDescription', 'setRemoteDescription'].forEach((method) => {
  5314. const origMethod = proto[method];
  5315. proto[method] = function() {
  5316. if (!this._connectionstatechangepoly) {
  5317. this._connectionstatechangepoly = e => {
  5318. const pc = e.target;
  5319. if (pc._lastConnectionState !== pc.connectionState) {
  5320. pc._lastConnectionState = pc.connectionState;
  5321. const newEvent = new Event('connectionstatechange', e);
  5322. pc.dispatchEvent(newEvent);
  5323. }
  5324. return e;
  5325. };
  5326. this.addEventListener('iceconnectionstatechange',
  5327. this._connectionstatechangepoly);
  5328. }
  5329. return origMethod.apply(this, arguments);
  5330. };
  5331. });
  5332. }
  5333. function removeExtmapAllowMixed(window, browserDetails) {
  5334. /* remove a=extmap-allow-mixed for webrtc.org < M71 */
  5335. if (!window.RTCPeerConnection) {
  5336. return;
  5337. }
  5338. if (browserDetails.browser === 'chrome' && browserDetails.version >= 71) {
  5339. return;
  5340. }
  5341. if (browserDetails.browser === 'safari' && browserDetails.version >= 605) {
  5342. return;
  5343. }
  5344. const nativeSRD = window.RTCPeerConnection.prototype.setRemoteDescription;
  5345. window.RTCPeerConnection.prototype.setRemoteDescription =
  5346. function setRemoteDescription(desc) {
  5347. if (desc && desc.sdp && desc.sdp.indexOf('\na=extmap-allow-mixed') !== -1) {
  5348. const sdp = desc.sdp.split('\n').filter((line) => {
  5349. return line.trim() !== 'a=extmap-allow-mixed';
  5350. }).join('\n');
  5351. // Safari enforces read-only-ness of RTCSessionDescription fields.
  5352. if (window.RTCSessionDescription &&
  5353. desc instanceof window.RTCSessionDescription) {
  5354. arguments[0] = new window.RTCSessionDescription({
  5355. type: desc.type,
  5356. sdp,
  5357. });
  5358. } else {
  5359. desc.sdp = sdp;
  5360. }
  5361. }
  5362. return nativeSRD.apply(this, arguments);
  5363. };
  5364. }
  5365. function shimAddIceCandidateNullOrEmpty(window, browserDetails) {
  5366. // Support for addIceCandidate(null or undefined)
  5367. // as well as addIceCandidate({candidate: "", ...})
  5368. // https://bugs.chromium.org/p/chromium/issues/detail?id=978582
  5369. // Note: must be called before other polyfills which change the signature.
  5370. if (!(window.RTCPeerConnection && window.RTCPeerConnection.prototype)) {
  5371. return;
  5372. }
  5373. const nativeAddIceCandidate =
  5374. window.RTCPeerConnection.prototype.addIceCandidate;
  5375. if (!nativeAddIceCandidate || nativeAddIceCandidate.length === 0) {
  5376. return;
  5377. }
  5378. window.RTCPeerConnection.prototype.addIceCandidate =
  5379. function addIceCandidate() {
  5380. if (!arguments[0]) {
  5381. if (arguments[1]) {
  5382. arguments[1].apply(null);
  5383. }
  5384. return Promise.resolve();
  5385. }
  5386. // Firefox 68+ emits and processes {candidate: "", ...}, ignore
  5387. // in older versions.
  5388. // Native support for ignoring exists for Chrome M77+.
  5389. // Safari ignores as well, exact version unknown but works in the same
  5390. // version that also ignores addIceCandidate(null).
  5391. if (((browserDetails.browser === 'chrome' && browserDetails.version < 78) ||
  5392. (browserDetails.browser === 'firefox' &&
  5393. browserDetails.version < 68) ||
  5394. (browserDetails.browser === 'safari')) &&
  5395. arguments[0] && arguments[0].candidate === '') {
  5396. return Promise.resolve();
  5397. }
  5398. return nativeAddIceCandidate.apply(this, arguments);
  5399. };
  5400. }
  5401. var commonShim = /*#__PURE__*/ Object.freeze({
  5402. __proto__: null,
  5403. shimRTCIceCandidate: shimRTCIceCandidate,
  5404. shimMaxMessageSize: shimMaxMessageSize,
  5405. shimSendThrowTypeError: shimSendThrowTypeError,
  5406. shimConnectionState: shimConnectionState,
  5407. removeExtmapAllowMixed: removeExtmapAllowMixed,
  5408. shimAddIceCandidateNullOrEmpty: shimAddIceCandidateNullOrEmpty
  5409. });
  5410. /*
  5411. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  5412. *
  5413. * Use of this source code is governed by a BSD-style license
  5414. * that can be found in the LICENSE file in the root of the source
  5415. * tree.
  5416. */
  5417. // Shimming starts here.
  5418. function adapterFactory({
  5419. window
  5420. } = {}, options = {
  5421. shimChrome: true,
  5422. shimFirefox: true,
  5423. shimEdge: true,
  5424. shimSafari: true,
  5425. }) {
  5426. // Utils.
  5427. const logging = log$1;
  5428. const browserDetails = detectBrowser(window);
  5429. const adapter = {
  5430. browserDetails,
  5431. commonShim,
  5432. extractVersion: extractVersion,
  5433. disableLog: disableLog,
  5434. disableWarnings: disableWarnings
  5435. };
  5436. // Shim browser if found.
  5437. switch (browserDetails.browser) {
  5438. case 'chrome':
  5439. if (!chromeShim || !shimPeerConnection$2 ||
  5440. !options.shimChrome) {
  5441. logging('Chrome shim is not included in this adapter release.');
  5442. return adapter;
  5443. }
  5444. if (browserDetails.version === null) {
  5445. logging('Chrome shim can not determine version, not shimming.');
  5446. return adapter;
  5447. }
  5448. logging('adapter.js shimming chrome.');
  5449. // Export to the adapter global object visible in the browser.
  5450. adapter.browserShim = chromeShim;
  5451. // Must be called before shimPeerConnection.
  5452. shimAddIceCandidateNullOrEmpty(window, browserDetails);
  5453. shimGetUserMedia$3(window, browserDetails);
  5454. shimMediaStream(window);
  5455. shimPeerConnection$2(window, browserDetails);
  5456. shimOnTrack$1(window);
  5457. shimAddTrackRemoveTrack(window, browserDetails);
  5458. shimGetSendersWithDtmf(window);
  5459. shimGetStats(window);
  5460. shimSenderReceiverGetStats(window);
  5461. fixNegotiationNeeded(window, browserDetails);
  5462. shimRTCIceCandidate(window);
  5463. shimConnectionState(window);
  5464. shimMaxMessageSize(window, browserDetails);
  5465. shimSendThrowTypeError(window);
  5466. removeExtmapAllowMixed(window, browserDetails);
  5467. break;
  5468. case 'firefox':
  5469. if (!firefoxShim || !shimPeerConnection ||
  5470. !options.shimFirefox) {
  5471. logging('Firefox shim is not included in this adapter release.');
  5472. return adapter;
  5473. }
  5474. logging('adapter.js shimming firefox.');
  5475. // Export to the adapter global object visible in the browser.
  5476. adapter.browserShim = firefoxShim;
  5477. // Must be called before shimPeerConnection.
  5478. shimAddIceCandidateNullOrEmpty(window, browserDetails);
  5479. shimGetUserMedia$1(window, browserDetails);
  5480. shimPeerConnection(window, browserDetails);
  5481. shimOnTrack(window);
  5482. shimRemoveStream(window);
  5483. shimSenderGetStats(window);
  5484. shimReceiverGetStats(window);
  5485. shimRTCDataChannel(window);
  5486. shimAddTransceiver(window);
  5487. shimGetParameters(window);
  5488. shimCreateOffer(window);
  5489. shimCreateAnswer(window);
  5490. shimRTCIceCandidate(window);
  5491. shimConnectionState(window);
  5492. shimMaxMessageSize(window, browserDetails);
  5493. shimSendThrowTypeError(window);
  5494. break;
  5495. case 'edge':
  5496. if (!edgeShim || !shimPeerConnection$1 || !options.shimEdge) {
  5497. logging('MS edge shim is not included in this adapter release.');
  5498. return adapter;
  5499. }
  5500. logging('adapter.js shimming edge.');
  5501. // Export to the adapter global object visible in the browser.
  5502. adapter.browserShim = edgeShim;
  5503. shimGetUserMedia$2(window);
  5504. shimGetDisplayMedia$1(window);
  5505. shimPeerConnection$1(window, browserDetails);
  5506. shimReplaceTrack(window);
  5507. // the edge shim implements the full RTCIceCandidate object.
  5508. shimMaxMessageSize(window, browserDetails);
  5509. shimSendThrowTypeError(window);
  5510. break;
  5511. case 'safari':
  5512. if (!safariShim || !options.shimSafari) {
  5513. logging('Safari shim is not included in this adapter release.');
  5514. return adapter;
  5515. }
  5516. logging('adapter.js shimming safari.');
  5517. // Export to the adapter global object visible in the browser.
  5518. adapter.browserShim = safariShim;
  5519. // Must be called before shimCallbackAPI.
  5520. shimAddIceCandidateNullOrEmpty(window, browserDetails);
  5521. shimRTCIceServerUrls(window);
  5522. shimCreateOfferLegacy(window);
  5523. shimCallbacksAPI(window);
  5524. shimLocalStreamsAPI(window);
  5525. shimRemoteStreamsAPI(window);
  5526. shimTrackEventTransceiver(window);
  5527. shimGetUserMedia(window);
  5528. shimAudioContext(window);
  5529. shimRTCIceCandidate(window);
  5530. shimMaxMessageSize(window, browserDetails);
  5531. shimSendThrowTypeError(window);
  5532. removeExtmapAllowMixed(window, browserDetails);
  5533. break;
  5534. default:
  5535. logging('Unsupported browser!');
  5536. break;
  5537. }
  5538. return adapter;
  5539. }
  5540. /*
  5541. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  5542. *
  5543. * Use of this source code is governed by a BSD-style license
  5544. * that can be found in the LICENSE file in the root of the source
  5545. * tree.
  5546. */
  5547. adapterFactory({
  5548. window: typeof window === 'undefined' ? undefined : window
  5549. });
  5550. /**
  5551. * @class AudioTrackConstraints
  5552. * @classDesc Constraints for creating an audio MediaStreamTrack.
  5553. * @memberof Owt.Base
  5554. * @constructor
  5555. * @param {Owt.Base.AudioSourceInfo} source Source info of this audio track.
  5556. */
  5557. class AudioTrackConstraints {
  5558. // eslint-disable-next-line require-jsdoc
  5559. constructor(source) {
  5560. if (!Object.values(AudioSourceInfo).some(v => v === source)) {
  5561. throw new TypeError('Invalid source.');
  5562. }
  5563. /**
  5564. * @member {string} source
  5565. * @memberof Owt.Base.AudioTrackConstraints
  5566. * @desc Values could be "mic", "screen-cast", "file" or "mixed".
  5567. * @instance
  5568. */
  5569. this.source = source;
  5570. /**
  5571. * @member {string} deviceId
  5572. * @memberof Owt.Base.AudioTrackConstraints
  5573. * @desc Do not provide deviceId if source is not "mic".
  5574. * @instance
  5575. * @see https://w3c.github.io/mediacapture-main/#def-constraint-deviceId
  5576. */
  5577. this.deviceId = undefined;
  5578. }
  5579. }
  5580. /**
  5581. * @class VideoTrackConstraints
  5582. * @classDesc Constraints for creating a video MediaStreamTrack.
  5583. * @memberof Owt.Base
  5584. * @constructor
  5585. * @param {Owt.Base.VideoSourceInfo} source Source info of this video track.
  5586. */
  5587. class VideoTrackConstraints {
  5588. // eslint-disable-next-line require-jsdoc
  5589. constructor(source) {
  5590. if (!Object.values(VideoSourceInfo).some(v => v === source)) {
  5591. throw new TypeError('Invalid source.');
  5592. }
  5593. /**
  5594. * @member {string} source
  5595. * @memberof Owt.Base.VideoTrackConstraints
  5596. * @desc Values could be "camera", "screen-cast", "file" or "mixed".
  5597. * @instance
  5598. */
  5599. this.source = source;
  5600. /**
  5601. * @member {string} deviceId
  5602. * @memberof Owt.Base.VideoTrackConstraints
  5603. * @desc Do not provide deviceId if source is not "camera".
  5604. * @instance
  5605. * @see https://w3c.github.io/mediacapture-main/#def-constraint-deviceId
  5606. */
  5607. this.deviceId = undefined;
  5608. /**
  5609. * @member {Owt.Base.Resolution} resolution
  5610. * @memberof Owt.Base.VideoTrackConstraints
  5611. * @instance
  5612. */
  5613. this.resolution = undefined;
  5614. /**
  5615. * @member {number} frameRate
  5616. * @memberof Owt.Base.VideoTrackConstraints
  5617. * @instance
  5618. */
  5619. this.frameRate = undefined;
  5620. }
  5621. }
  5622. /**
  5623. * @class StreamConstraints
  5624. * @classDesc Constraints for creating a MediaStream from screen mic and camera.
  5625. * @memberof Owt.Base
  5626. * @constructor
  5627. * @param {?Owt.Base.AudioTrackConstraints} audioConstraints
  5628. * @param {?Owt.Base.VideoTrackConstraints} videoConstraints
  5629. */
  5630. class StreamConstraints {
  5631. // eslint-disable-next-line require-jsdoc
  5632. constructor(audioConstraints = false, videoConstraints = false) {
  5633. /**
  5634. * @member {Owt.Base.MediaStreamTrackDeviceConstraintsForAudio} audio
  5635. * @memberof Owt.Base.MediaStreamDeviceConstraints
  5636. * @instance
  5637. */
  5638. this.audio = audioConstraints;
  5639. /**
  5640. * @member {Owt.Base.MediaStreamTrackDeviceConstraintsForVideo} Video
  5641. * @memberof Owt.Base.MediaStreamDeviceConstraints
  5642. * @instance
  5643. */
  5644. this.video = videoConstraints;
  5645. }
  5646. } // eslint-disable-next-line require-jsdoc
  5647. function isVideoConstrainsForScreenCast(constraints) {
  5648. return typeof constraints.video === 'object' && constraints.video.source === VideoSourceInfo.SCREENCAST;
  5649. }
  5650. /**
  5651. * @class MediaStreamFactory
  5652. * @classDesc A factory to create MediaStream. You can also create MediaStream by yourself.
  5653. * @memberof Owt.Base
  5654. */
  5655. class MediaStreamFactory {
  5656. /**
  5657. * @function createMediaStream
  5658. * @static
  5659. * @desc Create a MediaStream with given constraints. If you want to create a MediaStream for screen cast, please make sure both audio and video's source are "screen-cast".
  5660. * @memberof Owt.Base.MediaStreamFactory
  5661. * @return {Promise<MediaStream, Error>} Return a promise that is resolved when stream is successfully created, or rejected if one of the following error happened:
  5662. * - One or more parameters cannot be satisfied.
  5663. * - Specified device is busy.
  5664. * - Cannot obtain necessary permission or operation is canceled by user.
  5665. * - Video source is screen cast, while audio source is not.
  5666. * - Audio source is screen cast, while video source is disabled.
  5667. * @param {Owt.Base.StreamConstraints} constraints
  5668. */
  5669. static createMediaStream(constraints) {
  5670. if (typeof constraints !== 'object' || !constraints.audio && !constraints.video) {
  5671. return Promise.reject(new TypeError('Invalid constrains'));
  5672. }
  5673. if (!isVideoConstrainsForScreenCast(constraints) && typeof constraints.audio === 'object' && constraints
  5674. .audio.source === AudioSourceInfo.SCREENCAST) {
  5675. return Promise.reject(new TypeError('Cannot share screen without video.'));
  5676. }
  5677. if (isVideoConstrainsForScreenCast(constraints) && !isChrome() && !isFirefox()) {
  5678. return Promise.reject(new TypeError('Screen sharing only supports Chrome and Firefox.'));
  5679. }
  5680. if (isVideoConstrainsForScreenCast(constraints) && typeof constraints.audio === 'object' && constraints
  5681. .audio.source !== AudioSourceInfo.SCREENCAST) {
  5682. return Promise.reject(new TypeError('Cannot capture video from screen cast while capture audio from' +
  5683. ' other source.'));
  5684. } // Check and convert constraints.
  5685. if (!constraints.audio && !constraints.video) {
  5686. return Promise.reject(new TypeError('At least one of audio and video must be requested.'));
  5687. }
  5688. const mediaConstraints = Object.create({});
  5689. if (typeof constraints.audio === 'object' && constraints.audio.source === AudioSourceInfo.MIC) {
  5690. mediaConstraints.audio = Object.create({});
  5691. if (isEdge()) {
  5692. mediaConstraints.audio.deviceId = constraints.audio.deviceId;
  5693. } else {
  5694. mediaConstraints.audio.deviceId = {
  5695. exact: constraints.audio.deviceId
  5696. };
  5697. }
  5698. } else {
  5699. if (constraints.audio.source === AudioSourceInfo.SCREENCAST) {
  5700. mediaConstraints.audio = true;
  5701. } else {
  5702. mediaConstraints.audio = constraints.audio;
  5703. }
  5704. }
  5705. if (typeof constraints.video === 'object') {
  5706. mediaConstraints.video = Object.create({});
  5707. if (typeof constraints.video.frameRate === 'number') {
  5708. mediaConstraints.video.frameRate = constraints.video.frameRate;
  5709. }
  5710. if (constraints.video.resolution && constraints.video.resolution.width && constraints.video.resolution
  5711. .height) {
  5712. if (constraints.video.source === VideoSourceInfo.SCREENCAST) {
  5713. mediaConstraints.video.width = constraints.video.resolution.width;
  5714. mediaConstraints.video.height = constraints.video.resolution.height;
  5715. } else {
  5716. mediaConstraints.video.width = Object.create({});
  5717. mediaConstraints.video.width.exact = constraints.video.resolution.width;
  5718. mediaConstraints.video.height = Object.create({});
  5719. mediaConstraints.video.height.exact = constraints.video.resolution.height;
  5720. }
  5721. }
  5722. if (typeof constraints.video.deviceId === 'string') {
  5723. mediaConstraints.video.deviceId = {
  5724. exact: constraints.video.deviceId
  5725. };
  5726. }
  5727. if (isFirefox() && constraints.video.source === VideoSourceInfo.SCREENCAST) {
  5728. mediaConstraints.video.mediaSource = 'screen';
  5729. }
  5730. } else {
  5731. mediaConstraints.video = constraints.video;
  5732. }
  5733. if (isVideoConstrainsForScreenCast(constraints)) {
  5734. return navigator.mediaDevices.getDisplayMedia(mediaConstraints);
  5735. } else {
  5736. return navigator.mediaDevices.getUserMedia(mediaConstraints);
  5737. }
  5738. }
  5739. }
  5740. let logger;
  5741. let errorLogger;
  5742. function setLogger() {
  5743. /*eslint-disable */
  5744. logger = console.log;
  5745. errorLogger = console.error;
  5746. /*eslint-enable */
  5747. }
  5748. function log(message, ...optionalParams) {
  5749. if (logger) {
  5750. logger(message, ...optionalParams);
  5751. }
  5752. }
  5753. function error(message, ...optionalParams) {
  5754. if (errorLogger) {
  5755. errorLogger(message, ...optionalParams);
  5756. }
  5757. }
  5758. class Event$1 {
  5759. constructor(type) {
  5760. this.listener = {};
  5761. this.type = type | '';
  5762. }
  5763. on(event, fn) {
  5764. if (!this.listener[event]) {
  5765. this.listener[event] = [];
  5766. }
  5767. this.listener[event].push(fn);
  5768. return true;
  5769. }
  5770. off(event, fn) {
  5771. if (this.listener[event]) {
  5772. var index = this.listener[event].indexOf(fn);
  5773. if (index > -1) {
  5774. this.listener[event].splice(index, 1);
  5775. }
  5776. return true;
  5777. }
  5778. return false;
  5779. }
  5780. offAll() {
  5781. this.listener = {};
  5782. }
  5783. dispatch(event, data) {
  5784. if (this.listener[event]) {
  5785. this.listener[event].map(each => {
  5786. each.apply(null, [data]);
  5787. });
  5788. return true;
  5789. }
  5790. return false;
  5791. }
  5792. }
  5793. var bind = function bind(fn, thisArg) {
  5794. return function wrap() {
  5795. var args = new Array(arguments.length);
  5796. for (var i = 0; i < args.length; i++) {
  5797. args[i] = arguments[i];
  5798. }
  5799. return fn.apply(thisArg, args);
  5800. };
  5801. };
  5802. // utils is a library of generic helper functions non-specific to axios
  5803. var toString = Object.prototype.toString;
  5804. // eslint-disable-next-line func-names
  5805. var kindOf = (function(cache) {
  5806. // eslint-disable-next-line func-names
  5807. return function(thing) {
  5808. var str = toString.call(thing);
  5809. return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
  5810. };
  5811. })(Object.create(null));
  5812. function kindOfTest(type) {
  5813. type = type.toLowerCase();
  5814. return function isKindOf(thing) {
  5815. return kindOf(thing) === type;
  5816. };
  5817. }
  5818. /**
  5819. * Determine if a value is an Array
  5820. *
  5821. * @param {Object} val The value to test
  5822. * @returns {boolean} True if value is an Array, otherwise false
  5823. */
  5824. function isArray(val) {
  5825. return Array.isArray(val);
  5826. }
  5827. /**
  5828. * Determine if a value is undefined
  5829. *
  5830. * @param {Object} val The value to test
  5831. * @returns {boolean} True if the value is undefined, otherwise false
  5832. */
  5833. function isUndefined(val) {
  5834. return typeof val === 'undefined';
  5835. }
  5836. /**
  5837. * Determine if a value is a Buffer
  5838. *
  5839. * @param {Object} val The value to test
  5840. * @returns {boolean} True if value is a Buffer, otherwise false
  5841. */
  5842. function isBuffer(val) {
  5843. return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) &&
  5844. typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
  5845. }
  5846. /**
  5847. * Determine if a value is an ArrayBuffer
  5848. *
  5849. * @function
  5850. * @param {Object} val The value to test
  5851. * @returns {boolean} True if value is an ArrayBuffer, otherwise false
  5852. */
  5853. var isArrayBuffer = kindOfTest('ArrayBuffer');
  5854. /**
  5855. * Determine if a value is a view on an ArrayBuffer
  5856. *
  5857. * @param {Object} val The value to test
  5858. * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
  5859. */
  5860. function isArrayBufferView(val) {
  5861. var result;
  5862. if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
  5863. result = ArrayBuffer.isView(val);
  5864. } else {
  5865. result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));
  5866. }
  5867. return result;
  5868. }
  5869. /**
  5870. * Determine if a value is a String
  5871. *
  5872. * @param {Object} val The value to test
  5873. * @returns {boolean} True if value is a String, otherwise false
  5874. */
  5875. function isString(val) {
  5876. return typeof val === 'string';
  5877. }
  5878. /**
  5879. * Determine if a value is a Number
  5880. *
  5881. * @param {Object} val The value to test
  5882. * @returns {boolean} True if value is a Number, otherwise false
  5883. */
  5884. function isNumber(val) {
  5885. return typeof val === 'number';
  5886. }
  5887. /**
  5888. * Determine if a value is an Object
  5889. *
  5890. * @param {Object} val The value to test
  5891. * @returns {boolean} True if value is an Object, otherwise false
  5892. */
  5893. function isObject(val) {
  5894. return val !== null && typeof val === 'object';
  5895. }
  5896. /**
  5897. * Determine if a value is a plain Object
  5898. *
  5899. * @param {Object} val The value to test
  5900. * @return {boolean} True if value is a plain Object, otherwise false
  5901. */
  5902. function isPlainObject(val) {
  5903. if (kindOf(val) !== 'object') {
  5904. return false;
  5905. }
  5906. var prototype = Object.getPrototypeOf(val);
  5907. return prototype === null || prototype === Object.prototype;
  5908. }
  5909. /**
  5910. * Determine if a value is a Date
  5911. *
  5912. * @function
  5913. * @param {Object} val The value to test
  5914. * @returns {boolean} True if value is a Date, otherwise false
  5915. */
  5916. var isDate = kindOfTest('Date');
  5917. /**
  5918. * Determine if a value is a File
  5919. *
  5920. * @function
  5921. * @param {Object} val The value to test
  5922. * @returns {boolean} True if value is a File, otherwise false
  5923. */
  5924. var isFile = kindOfTest('File');
  5925. /**
  5926. * Determine if a value is a Blob
  5927. *
  5928. * @function
  5929. * @param {Object} val The value to test
  5930. * @returns {boolean} True if value is a Blob, otherwise false
  5931. */
  5932. var isBlob = kindOfTest('Blob');
  5933. /**
  5934. * Determine if a value is a FileList
  5935. *
  5936. * @function
  5937. * @param {Object} val The value to test
  5938. * @returns {boolean} True if value is a File, otherwise false
  5939. */
  5940. var isFileList = kindOfTest('FileList');
  5941. /**
  5942. * Determine if a value is a Function
  5943. *
  5944. * @param {Object} val The value to test
  5945. * @returns {boolean} True if value is a Function, otherwise false
  5946. */
  5947. function isFunction(val) {
  5948. return toString.call(val) === '[object Function]';
  5949. }
  5950. /**
  5951. * Determine if a value is a Stream
  5952. *
  5953. * @param {Object} val The value to test
  5954. * @returns {boolean} True if value is a Stream, otherwise false
  5955. */
  5956. function isStream(val) {
  5957. return isObject(val) && isFunction(val.pipe);
  5958. }
  5959. /**
  5960. * Determine if a value is a FormData
  5961. *
  5962. * @param {Object} thing The value to test
  5963. * @returns {boolean} True if value is an FormData, otherwise false
  5964. */
  5965. function isFormData(thing) {
  5966. var pattern = '[object FormData]';
  5967. return thing && (
  5968. (typeof FormData === 'function' && thing instanceof FormData) ||
  5969. toString.call(thing) === pattern ||
  5970. (isFunction(thing.toString) && thing.toString() === pattern)
  5971. );
  5972. }
  5973. /**
  5974. * Determine if a value is a URLSearchParams object
  5975. * @function
  5976. * @param {Object} val The value to test
  5977. * @returns {boolean} True if value is a URLSearchParams object, otherwise false
  5978. */
  5979. var isURLSearchParams = kindOfTest('URLSearchParams');
  5980. /**
  5981. * Trim excess whitespace off the beginning and end of a string
  5982. *
  5983. * @param {String} str The String to trim
  5984. * @returns {String} The String freed of excess whitespace
  5985. */
  5986. function trim(str) {
  5987. return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
  5988. }
  5989. /**
  5990. * Determine if we're running in a standard browser environment
  5991. *
  5992. * This allows axios to run in a web worker, and react-native.
  5993. * Both environments support XMLHttpRequest, but not fully standard globals.
  5994. *
  5995. * web workers:
  5996. * typeof window -> undefined
  5997. * typeof document -> undefined
  5998. *
  5999. * react-native:
  6000. * navigator.product -> 'ReactNative'
  6001. * nativescript
  6002. * navigator.product -> 'NativeScript' or 'NS'
  6003. */
  6004. function isStandardBrowserEnv() {
  6005. if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
  6006. navigator.product === 'NativeScript' ||
  6007. navigator.product === 'NS')) {
  6008. return false;
  6009. }
  6010. return (
  6011. typeof window !== 'undefined' &&
  6012. typeof document !== 'undefined'
  6013. );
  6014. }
  6015. /**
  6016. * Iterate over an Array or an Object invoking a function for each item.
  6017. *
  6018. * If `obj` is an Array callback will be called passing
  6019. * the value, index, and complete array for each item.
  6020. *
  6021. * If 'obj' is an Object callback will be called passing
  6022. * the value, key, and complete object for each property.
  6023. *
  6024. * @param {Object|Array} obj The object to iterate
  6025. * @param {Function} fn The callback to invoke for each item
  6026. */
  6027. function forEach(obj, fn) {
  6028. // Don't bother if no value provided
  6029. if (obj === null || typeof obj === 'undefined') {
  6030. return;
  6031. }
  6032. // Force an array if not already something iterable
  6033. if (typeof obj !== 'object') {
  6034. /*eslint no-param-reassign:0*/
  6035. obj = [obj];
  6036. }
  6037. if (isArray(obj)) {
  6038. // Iterate over array values
  6039. for (var i = 0, l = obj.length; i < l; i++) {
  6040. fn.call(null, obj[i], i, obj);
  6041. }
  6042. } else {
  6043. // Iterate over object keys
  6044. for (var key in obj) {
  6045. if (Object.prototype.hasOwnProperty.call(obj, key)) {
  6046. fn.call(null, obj[key], key, obj);
  6047. }
  6048. }
  6049. }
  6050. }
  6051. /**
  6052. * Accepts varargs expecting each argument to be an object, then
  6053. * immutably merges the properties of each object and returns result.
  6054. *
  6055. * When multiple objects contain the same key the later object in
  6056. * the arguments list will take precedence.
  6057. *
  6058. * Example:
  6059. *
  6060. * ```js
  6061. * var result = merge({foo: 123}, {foo: 456});
  6062. * console.log(result.foo); // outputs 456
  6063. * ```
  6064. *
  6065. * @param {Object} obj1 Object to merge
  6066. * @returns {Object} Result of all merge properties
  6067. */
  6068. function merge( /* obj1, obj2, obj3, ... */ ) {
  6069. var result = {};
  6070. function assignValue(val, key) {
  6071. if (isPlainObject(result[key]) && isPlainObject(val)) {
  6072. result[key] = merge(result[key], val);
  6073. } else if (isPlainObject(val)) {
  6074. result[key] = merge({}, val);
  6075. } else if (isArray(val)) {
  6076. result[key] = val.slice();
  6077. } else {
  6078. result[key] = val;
  6079. }
  6080. }
  6081. for (var i = 0, l = arguments.length; i < l; i++) {
  6082. forEach(arguments[i], assignValue);
  6083. }
  6084. return result;
  6085. }
  6086. /**
  6087. * Extends object a by mutably adding to it the properties of object b.
  6088. *
  6089. * @param {Object} a The object to be extended
  6090. * @param {Object} b The object to copy properties from
  6091. * @param {Object} thisArg The object to bind function to
  6092. * @return {Object} The resulting value of object a
  6093. */
  6094. function extend(a, b, thisArg) {
  6095. forEach(b, function assignValue(val, key) {
  6096. if (thisArg && typeof val === 'function') {
  6097. a[key] = bind(val, thisArg);
  6098. } else {
  6099. a[key] = val;
  6100. }
  6101. });
  6102. return a;
  6103. }
  6104. /**
  6105. * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
  6106. *
  6107. * @param {string} content with BOM
  6108. * @return {string} content value without BOM
  6109. */
  6110. function stripBOM(content) {
  6111. if (content.charCodeAt(0) === 0xFEFF) {
  6112. content = content.slice(1);
  6113. }
  6114. return content;
  6115. }
  6116. /**
  6117. * Inherit the prototype methods from one constructor into another
  6118. * @param {function} constructor
  6119. * @param {function} superConstructor
  6120. * @param {object} [props]
  6121. * @param {object} [descriptors]
  6122. */
  6123. function inherits(constructor, superConstructor, props, descriptors) {
  6124. constructor.prototype = Object.create(superConstructor.prototype, descriptors);
  6125. constructor.prototype.constructor = constructor;
  6126. props && Object.assign(constructor.prototype, props);
  6127. }
  6128. /**
  6129. * Resolve object with deep prototype chain to a flat object
  6130. * @param {Object} sourceObj source object
  6131. * @param {Object} [destObj]
  6132. * @param {Function} [filter]
  6133. * @returns {Object}
  6134. */
  6135. function toFlatObject(sourceObj, destObj, filter) {
  6136. var props;
  6137. var i;
  6138. var prop;
  6139. var merged = {};
  6140. destObj = destObj || {};
  6141. do {
  6142. props = Object.getOwnPropertyNames(sourceObj);
  6143. i = props.length;
  6144. while (i-- > 0) {
  6145. prop = props[i];
  6146. if (!merged[prop]) {
  6147. destObj[prop] = sourceObj[prop];
  6148. merged[prop] = true;
  6149. }
  6150. }
  6151. sourceObj = Object.getPrototypeOf(sourceObj);
  6152. } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
  6153. return destObj;
  6154. }
  6155. /*
  6156. * determines whether a string ends with the characters of a specified string
  6157. * @param {String} str
  6158. * @param {String} searchString
  6159. * @param {Number} [position= 0]
  6160. * @returns {boolean}
  6161. */
  6162. function endsWith(str, searchString, position) {
  6163. str = String(str);
  6164. if (position === undefined || position > str.length) {
  6165. position = str.length;
  6166. }
  6167. position -= searchString.length;
  6168. var lastIndex = str.indexOf(searchString, position);
  6169. return lastIndex !== -1 && lastIndex === position;
  6170. }
  6171. /**
  6172. * Returns new array from array like object
  6173. * @param {*} [thing]
  6174. * @returns {Array}
  6175. */
  6176. function toArray(thing) {
  6177. if (!thing) return null;
  6178. var i = thing.length;
  6179. if (isUndefined(i)) return null;
  6180. var arr = new Array(i);
  6181. while (i-- > 0) {
  6182. arr[i] = thing[i];
  6183. }
  6184. return arr;
  6185. }
  6186. // eslint-disable-next-line func-names
  6187. var isTypedArray = (function(TypedArray) {
  6188. // eslint-disable-next-line func-names
  6189. return function(thing) {
  6190. return TypedArray && thing instanceof TypedArray;
  6191. };
  6192. })(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array));
  6193. var utils = {
  6194. isArray: isArray,
  6195. isArrayBuffer: isArrayBuffer,
  6196. isBuffer: isBuffer,
  6197. isFormData: isFormData,
  6198. isArrayBufferView: isArrayBufferView,
  6199. isString: isString,
  6200. isNumber: isNumber,
  6201. isObject: isObject,
  6202. isPlainObject: isPlainObject,
  6203. isUndefined: isUndefined,
  6204. isDate: isDate,
  6205. isFile: isFile,
  6206. isBlob: isBlob,
  6207. isFunction: isFunction,
  6208. isStream: isStream,
  6209. isURLSearchParams: isURLSearchParams,
  6210. isStandardBrowserEnv: isStandardBrowserEnv,
  6211. forEach: forEach,
  6212. merge: merge,
  6213. extend: extend,
  6214. trim: trim,
  6215. stripBOM: stripBOM,
  6216. inherits: inherits,
  6217. toFlatObject: toFlatObject,
  6218. kindOf: kindOf,
  6219. kindOfTest: kindOfTest,
  6220. endsWith: endsWith,
  6221. toArray: toArray,
  6222. isTypedArray: isTypedArray,
  6223. isFileList: isFileList
  6224. };
  6225. function encode(val) {
  6226. return encodeURIComponent(val).
  6227. replace(/%3A/gi, ':').
  6228. replace(/%24/g, '$').
  6229. replace(/%2C/gi, ',').
  6230. replace(/%20/g, '+').
  6231. replace(/%5B/gi, '[').
  6232. replace(/%5D/gi, ']');
  6233. }
  6234. /**
  6235. * Build a URL by appending params to the end
  6236. *
  6237. * @param {string} url The base of the url (e.g., http://www.google.com)
  6238. * @param {object} [params] The params to be appended
  6239. * @returns {string} The formatted url
  6240. */
  6241. var buildURL = function buildURL(url, params, paramsSerializer) {
  6242. /*eslint no-param-reassign:0*/
  6243. if (!params) {
  6244. return url;
  6245. }
  6246. var serializedParams;
  6247. if (paramsSerializer) {
  6248. serializedParams = paramsSerializer(params);
  6249. } else if (utils.isURLSearchParams(params)) {
  6250. serializedParams = params.toString();
  6251. } else {
  6252. var parts = [];
  6253. utils.forEach(params, function serialize(val, key) {
  6254. if (val === null || typeof val === 'undefined') {
  6255. return;
  6256. }
  6257. if (utils.isArray(val)) {
  6258. key = key + '[]';
  6259. } else {
  6260. val = [val];
  6261. }
  6262. utils.forEach(val, function parseValue(v) {
  6263. if (utils.isDate(v)) {
  6264. v = v.toISOString();
  6265. } else if (utils.isObject(v)) {
  6266. v = JSON.stringify(v);
  6267. }
  6268. parts.push(encode(key) + '=' + encode(v));
  6269. });
  6270. });
  6271. serializedParams = parts.join('&');
  6272. }
  6273. if (serializedParams) {
  6274. var hashmarkIndex = url.indexOf('#');
  6275. if (hashmarkIndex !== -1) {
  6276. url = url.slice(0, hashmarkIndex);
  6277. }
  6278. url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
  6279. }
  6280. return url;
  6281. };
  6282. function InterceptorManager() {
  6283. this.handlers = [];
  6284. }
  6285. /**
  6286. * Add a new interceptor to the stack
  6287. *
  6288. * @param {Function} fulfilled The function to handle `then` for a `Promise`
  6289. * @param {Function} rejected The function to handle `reject` for a `Promise`
  6290. *
  6291. * @return {Number} An ID used to remove interceptor later
  6292. */
  6293. InterceptorManager.prototype.use = function use(fulfilled, rejected, options) {
  6294. this.handlers.push({
  6295. fulfilled: fulfilled,
  6296. rejected: rejected,
  6297. synchronous: options ? options.synchronous : false,
  6298. runWhen: options ? options.runWhen : null
  6299. });
  6300. return this.handlers.length - 1;
  6301. };
  6302. /**
  6303. * Remove an interceptor from the stack
  6304. *
  6305. * @param {Number} id The ID that was returned by `use`
  6306. */
  6307. InterceptorManager.prototype.eject = function eject(id) {
  6308. if (this.handlers[id]) {
  6309. this.handlers[id] = null;
  6310. }
  6311. };
  6312. /**
  6313. * Iterate over all the registered interceptors
  6314. *
  6315. * This method is particularly useful for skipping over any
  6316. * interceptors that may have become `null` calling `eject`.
  6317. *
  6318. * @param {Function} fn The function to call for each interceptor
  6319. */
  6320. InterceptorManager.prototype.forEach = function forEach(fn) {
  6321. utils.forEach(this.handlers, function forEachHandler(h) {
  6322. if (h !== null) {
  6323. fn(h);
  6324. }
  6325. });
  6326. };
  6327. var InterceptorManager_1 = InterceptorManager;
  6328. var normalizeHeaderName = function normalizeHeaderName(headers, normalizedName) {
  6329. utils.forEach(headers, function processHeader(value, name) {
  6330. if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
  6331. headers[normalizedName] = value;
  6332. delete headers[name];
  6333. }
  6334. });
  6335. };
  6336. /**
  6337. * Create an Error with the specified message, config, error code, request and response.
  6338. *
  6339. * @param {string} message The error message.
  6340. * @param {string} [code] The error code (for example, 'ECONNABORTED').
  6341. * @param {Object} [config] The config.
  6342. * @param {Object} [request] The request.
  6343. * @param {Object} [response] The response.
  6344. * @returns {Error} The created error.
  6345. */
  6346. function AxiosError(message, code, config, request, response) {
  6347. Error.call(this);
  6348. this.message = message;
  6349. this.name = 'AxiosError';
  6350. code && (this.code = code);
  6351. config && (this.config = config);
  6352. request && (this.request = request);
  6353. response && (this.response = response);
  6354. }
  6355. utils.inherits(AxiosError, Error, {
  6356. toJSON: function toJSON() {
  6357. return {
  6358. // Standard
  6359. message: this.message,
  6360. name: this.name,
  6361. // Microsoft
  6362. description: this.description,
  6363. number: this.number,
  6364. // Mozilla
  6365. fileName: this.fileName,
  6366. lineNumber: this.lineNumber,
  6367. columnNumber: this.columnNumber,
  6368. stack: this.stack,
  6369. // Axios
  6370. config: this.config,
  6371. code: this.code,
  6372. status: this.response && this.response.status ? this.response.status : null
  6373. };
  6374. }
  6375. });
  6376. var prototype = AxiosError.prototype;
  6377. var descriptors = {};
  6378. [
  6379. 'ERR_BAD_OPTION_VALUE',
  6380. 'ERR_BAD_OPTION',
  6381. 'ECONNABORTED',
  6382. 'ETIMEDOUT',
  6383. 'ERR_NETWORK',
  6384. 'ERR_FR_TOO_MANY_REDIRECTS',
  6385. 'ERR_DEPRECATED',
  6386. 'ERR_BAD_RESPONSE',
  6387. 'ERR_BAD_REQUEST',
  6388. 'ERR_CANCELED'
  6389. // eslint-disable-next-line func-names
  6390. ].forEach(function(code) {
  6391. descriptors[code] = {
  6392. value: code
  6393. };
  6394. });
  6395. Object.defineProperties(AxiosError, descriptors);
  6396. Object.defineProperty(prototype, 'isAxiosError', {
  6397. value: true
  6398. });
  6399. // eslint-disable-next-line func-names
  6400. AxiosError.from = function(error, code, config, request, response, customProps) {
  6401. var axiosError = Object.create(prototype);
  6402. utils.toFlatObject(error, axiosError, function filter(obj) {
  6403. return obj !== Error.prototype;
  6404. });
  6405. AxiosError.call(axiosError, error.message, code, config, request, response);
  6406. axiosError.name = error.name;
  6407. customProps && Object.assign(axiosError, customProps);
  6408. return axiosError;
  6409. };
  6410. var AxiosError_1 = AxiosError;
  6411. var transitional = {
  6412. silentJSONParsing: true,
  6413. forcedJSONParsing: true,
  6414. clarifyTimeoutError: false
  6415. };
  6416. /**
  6417. * Convert a data object to FormData
  6418. * @param {Object} obj
  6419. * @param {?Object} [formData]
  6420. * @returns {Object}
  6421. **/
  6422. function toFormData(obj, formData) {
  6423. // eslint-disable-next-line no-param-reassign
  6424. formData = formData || new FormData();
  6425. var stack = [];
  6426. function convertValue(value) {
  6427. if (value === null) return '';
  6428. if (utils.isDate(value)) {
  6429. return value.toISOString();
  6430. }
  6431. if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {
  6432. return typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);
  6433. }
  6434. return value;
  6435. }
  6436. function build(data, parentKey) {
  6437. if (utils.isPlainObject(data) || utils.isArray(data)) {
  6438. if (stack.indexOf(data) !== -1) {
  6439. throw Error('Circular reference detected in ' + parentKey);
  6440. }
  6441. stack.push(data);
  6442. utils.forEach(data, function each(value, key) {
  6443. if (utils.isUndefined(value)) return;
  6444. var fullKey = parentKey ? parentKey + '.' + key : key;
  6445. var arr;
  6446. if (value && !parentKey && typeof value === 'object') {
  6447. if (utils.endsWith(key, '{}')) {
  6448. // eslint-disable-next-line no-param-reassign
  6449. value = JSON.stringify(value);
  6450. } else if (utils.endsWith(key, '[]') && (arr = utils.toArray(value))) {
  6451. // eslint-disable-next-line func-names
  6452. arr.forEach(function(el) {
  6453. !utils.isUndefined(el) && formData.append(fullKey, convertValue(el));
  6454. });
  6455. return;
  6456. }
  6457. }
  6458. build(value, fullKey);
  6459. });
  6460. stack.pop();
  6461. } else {
  6462. formData.append(parentKey, convertValue(data));
  6463. }
  6464. }
  6465. build(obj);
  6466. return formData;
  6467. }
  6468. var toFormData_1 = toFormData;
  6469. /**
  6470. * Resolve or reject a Promise based on response status.
  6471. *
  6472. * @param {Function} resolve A function that resolves the promise.
  6473. * @param {Function} reject A function that rejects the promise.
  6474. * @param {object} response The response.
  6475. */
  6476. var settle = function settle(resolve, reject, response) {
  6477. var validateStatus = response.config.validateStatus;
  6478. if (!response.status || !validateStatus || validateStatus(response.status)) {
  6479. resolve(response);
  6480. } else {
  6481. reject(new AxiosError_1(
  6482. 'Request failed with status code ' + response.status,
  6483. [AxiosError_1.ERR_BAD_REQUEST, AxiosError_1.ERR_BAD_RESPONSE][Math.floor(response.status /
  6484. 100) - 4],
  6485. response.config,
  6486. response.request,
  6487. response
  6488. ));
  6489. }
  6490. };
  6491. var cookies = (
  6492. utils.isStandardBrowserEnv() ?
  6493. // Standard browser envs support document.cookie
  6494. (function standardBrowserEnv() {
  6495. return {
  6496. write: function write(name, value, expires, path, domain, secure) {
  6497. var cookie = [];
  6498. cookie.push(name + '=' + encodeURIComponent(value));
  6499. if (utils.isNumber(expires)) {
  6500. cookie.push('expires=' + new Date(expires).toGMTString());
  6501. }
  6502. if (utils.isString(path)) {
  6503. cookie.push('path=' + path);
  6504. }
  6505. if (utils.isString(domain)) {
  6506. cookie.push('domain=' + domain);
  6507. }
  6508. if (secure === true) {
  6509. cookie.push('secure');
  6510. }
  6511. document.cookie = cookie.join('; ');
  6512. },
  6513. read: function read(name) {
  6514. var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
  6515. return (match ? decodeURIComponent(match[3]) : null);
  6516. },
  6517. remove: function remove(name) {
  6518. this.write(name, '', Date.now() - 86400000);
  6519. }
  6520. };
  6521. })() :
  6522. // Non standard browser env (web workers, react-native) lack needed support.
  6523. (function nonStandardBrowserEnv() {
  6524. return {
  6525. write: function write() {},
  6526. read: function read() {
  6527. return null;
  6528. },
  6529. remove: function remove() {}
  6530. };
  6531. })()
  6532. );
  6533. /**
  6534. * Determines whether the specified URL is absolute
  6535. *
  6536. * @param {string} url The URL to test
  6537. * @returns {boolean} True if the specified URL is absolute, otherwise false
  6538. */
  6539. var isAbsoluteURL = function isAbsoluteURL(url) {
  6540. // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
  6541. // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
  6542. // by any combination of letters, digits, plus, period, or hyphen.
  6543. return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
  6544. };
  6545. /**
  6546. * Creates a new URL by combining the specified URLs
  6547. *
  6548. * @param {string} baseURL The base URL
  6549. * @param {string} relativeURL The relative URL
  6550. * @returns {string} The combined URL
  6551. */
  6552. var combineURLs = function combineURLs(baseURL, relativeURL) {
  6553. return relativeURL ?
  6554. baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') :
  6555. baseURL;
  6556. };
  6557. /**
  6558. * Creates a new URL by combining the baseURL with the requestedURL,
  6559. * only when the requestedURL is not already an absolute URL.
  6560. * If the requestURL is absolute, this function returns the requestedURL untouched.
  6561. *
  6562. * @param {string} baseURL The base URL
  6563. * @param {string} requestedURL Absolute or relative URL to combine
  6564. * @returns {string} The combined full path
  6565. */
  6566. var buildFullPath = function buildFullPath(baseURL, requestedURL) {
  6567. if (baseURL && !isAbsoluteURL(requestedURL)) {
  6568. return combineURLs(baseURL, requestedURL);
  6569. }
  6570. return requestedURL;
  6571. };
  6572. // Headers whose duplicates are ignored by node
  6573. // c.f. https://nodejs.org/api/http.html#http_message_headers
  6574. var ignoreDuplicateOf = [
  6575. 'age', 'authorization', 'content-length', 'content-type', 'etag',
  6576. 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
  6577. 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
  6578. 'referer', 'retry-after', 'user-agent'
  6579. ];
  6580. /**
  6581. * Parse headers into an object
  6582. *
  6583. * ```
  6584. * Date: Wed, 27 Aug 2014 08:58:49 GMT
  6585. * Content-Type: application/json
  6586. * Connection: keep-alive
  6587. * Transfer-Encoding: chunked
  6588. * ```
  6589. *
  6590. * @param {String} headers Headers needing to be parsed
  6591. * @returns {Object} Headers parsed into an object
  6592. */
  6593. var parseHeaders = function parseHeaders(headers) {
  6594. var parsed = {};
  6595. var key;
  6596. var val;
  6597. var i;
  6598. if (!headers) {
  6599. return parsed;
  6600. }
  6601. utils.forEach(headers.split('\n'), function parser(line) {
  6602. i = line.indexOf(':');
  6603. key = utils.trim(line.substr(0, i)).toLowerCase();
  6604. val = utils.trim(line.substr(i + 1));
  6605. if (key) {
  6606. if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
  6607. return;
  6608. }
  6609. if (key === 'set-cookie') {
  6610. parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
  6611. } else {
  6612. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  6613. }
  6614. }
  6615. });
  6616. return parsed;
  6617. };
  6618. var isURLSameOrigin = (
  6619. utils.isStandardBrowserEnv() ?
  6620. // Standard browser envs have full support of the APIs needed to test
  6621. // whether the request URL is of the same origin as current location.
  6622. (function standardBrowserEnv() {
  6623. var msie = /(msie|trident)/i.test(navigator.userAgent);
  6624. var urlParsingNode = document.createElement('a');
  6625. var originURL;
  6626. /**
  6627. * Parse a URL to discover it's components
  6628. *
  6629. * @param {String} url The URL to be parsed
  6630. * @returns {Object}
  6631. */
  6632. function resolveURL(url) {
  6633. var href = url;
  6634. if (msie) {
  6635. // IE needs attribute set twice to normalize properties
  6636. urlParsingNode.setAttribute('href', href);
  6637. href = urlParsingNode.href;
  6638. }
  6639. urlParsingNode.setAttribute('href', href);
  6640. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  6641. return {
  6642. href: urlParsingNode.href,
  6643. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  6644. host: urlParsingNode.host,
  6645. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  6646. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  6647. hostname: urlParsingNode.hostname,
  6648. port: urlParsingNode.port,
  6649. pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
  6650. urlParsingNode.pathname : '/' + urlParsingNode.pathname
  6651. };
  6652. }
  6653. originURL = resolveURL(window.location.href);
  6654. /**
  6655. * Determine if a URL shares the same origin as the current location
  6656. *
  6657. * @param {String} requestURL The URL to test
  6658. * @returns {boolean} True if URL shares the same origin, otherwise false
  6659. */
  6660. return function isURLSameOrigin(requestURL) {
  6661. var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
  6662. return (parsed.protocol === originURL.protocol &&
  6663. parsed.host === originURL.host);
  6664. };
  6665. })() :
  6666. // Non standard browser envs (web workers, react-native) lack needed support.
  6667. (function nonStandardBrowserEnv() {
  6668. return function isURLSameOrigin() {
  6669. return true;
  6670. };
  6671. })()
  6672. );
  6673. /**
  6674. * A `CanceledError` is an object that is thrown when an operation is canceled.
  6675. *
  6676. * @class
  6677. * @param {string=} message The message.
  6678. */
  6679. function CanceledError(message) {
  6680. // eslint-disable-next-line no-eq-null,eqeqeq
  6681. AxiosError_1.call(this, message == null ? 'canceled' : message, AxiosError_1.ERR_CANCELED);
  6682. this.name = 'CanceledError';
  6683. }
  6684. utils.inherits(CanceledError, AxiosError_1, {
  6685. __CANCEL__: true
  6686. });
  6687. var CanceledError_1 = CanceledError;
  6688. var parseProtocol = function parseProtocol(url) {
  6689. var match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
  6690. return match && match[1] || '';
  6691. };
  6692. var xhr = function xhrAdapter(config) {
  6693. return new Promise(function dispatchXhrRequest(resolve, reject) {
  6694. var requestData = config.data;
  6695. var requestHeaders = config.headers;
  6696. var responseType = config.responseType;
  6697. var onCanceled;
  6698. function done() {
  6699. if (config.cancelToken) {
  6700. config.cancelToken.unsubscribe(onCanceled);
  6701. }
  6702. if (config.signal) {
  6703. config.signal.removeEventListener('abort', onCanceled);
  6704. }
  6705. }
  6706. if (utils.isFormData(requestData) && utils.isStandardBrowserEnv()) {
  6707. delete requestHeaders['Content-Type']; // Let the browser set it
  6708. }
  6709. var request = new XMLHttpRequest();
  6710. // HTTP basic authentication
  6711. if (config.auth) {
  6712. var username = config.auth.username || '';
  6713. var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
  6714. requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
  6715. }
  6716. var fullPath = buildFullPath(config.baseURL, config.url);
  6717. request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config
  6718. .paramsSerializer), true);
  6719. // Set the request timeout in MS
  6720. request.timeout = config.timeout;
  6721. function onloadend() {
  6722. if (!request) {
  6723. return;
  6724. }
  6725. // Prepare the response
  6726. var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request
  6727. .getAllResponseHeaders()) : null;
  6728. var responseData = !responseType || responseType === 'text' || responseType === 'json' ?
  6729. request.responseText : request.response;
  6730. var response = {
  6731. data: responseData,
  6732. status: request.status,
  6733. statusText: request.statusText,
  6734. headers: responseHeaders,
  6735. config: config,
  6736. request: request
  6737. };
  6738. settle(function _resolve(value) {
  6739. resolve(value);
  6740. done();
  6741. }, function _reject(err) {
  6742. reject(err);
  6743. done();
  6744. }, response);
  6745. // Clean up request
  6746. request = null;
  6747. }
  6748. if ('onloadend' in request) {
  6749. // Use onloadend if available
  6750. request.onloadend = onloadend;
  6751. } else {
  6752. // Listen for ready state to emulate onloadend
  6753. request.onreadystatechange = function handleLoad() {
  6754. if (!request || request.readyState !== 4) {
  6755. return;
  6756. }
  6757. // The request errored out and we didn't get a response, this will be
  6758. // handled by onerror instead
  6759. // With one exception: request that using file: protocol, most browsers
  6760. // will return status as 0 even though it's a successful request
  6761. if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf(
  6762. 'file:') === 0)) {
  6763. return;
  6764. }
  6765. // readystate handler is calling before onerror or ontimeout handlers,
  6766. // so we should call onloadend on the next 'tick'
  6767. setTimeout(onloadend);
  6768. };
  6769. }
  6770. // Handle browser request cancellation (as opposed to a manual cancellation)
  6771. request.onabort = function handleAbort() {
  6772. if (!request) {
  6773. return;
  6774. }
  6775. reject(new AxiosError_1('Request aborted', AxiosError_1.ECONNABORTED, config, request));
  6776. // Clean up request
  6777. request = null;
  6778. };
  6779. // Handle low level network errors
  6780. request.onerror = function handleError() {
  6781. // Real errors are hidden from us by the browser
  6782. // onerror should only fire if it's a network error
  6783. reject(new AxiosError_1('Network Error', AxiosError_1.ERR_NETWORK, config, request,
  6784. request));
  6785. // Clean up request
  6786. request = null;
  6787. };
  6788. // Handle timeout
  6789. request.ontimeout = function handleTimeout() {
  6790. var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' :
  6791. 'timeout exceeded';
  6792. var transitional$1 = config.transitional || transitional;
  6793. if (config.timeoutErrorMessage) {
  6794. timeoutErrorMessage = config.timeoutErrorMessage;
  6795. }
  6796. reject(new AxiosError_1(
  6797. timeoutErrorMessage,
  6798. transitional$1.clarifyTimeoutError ? AxiosError_1.ETIMEDOUT : AxiosError_1
  6799. .ECONNABORTED,
  6800. config,
  6801. request));
  6802. // Clean up request
  6803. request = null;
  6804. };
  6805. // Add xsrf header
  6806. // This is only done if running in a standard browser environment.
  6807. // Specifically not if we're in a web worker, or react-native.
  6808. if (utils.isStandardBrowserEnv()) {
  6809. // Add xsrf header
  6810. var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
  6811. cookies.read(config.xsrfCookieName) :
  6812. undefined;
  6813. if (xsrfValue) {
  6814. requestHeaders[config.xsrfHeaderName] = xsrfValue;
  6815. }
  6816. }
  6817. // Add headers to the request
  6818. if ('setRequestHeader' in request) {
  6819. utils.forEach(requestHeaders, function setRequestHeader(val, key) {
  6820. if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
  6821. // Remove Content-Type if data is undefined
  6822. delete requestHeaders[key];
  6823. } else {
  6824. // Otherwise add header to the request
  6825. request.setRequestHeader(key, val);
  6826. }
  6827. });
  6828. }
  6829. // Add withCredentials to request if needed
  6830. if (!utils.isUndefined(config.withCredentials)) {
  6831. request.withCredentials = !!config.withCredentials;
  6832. }
  6833. // Add responseType to request if needed
  6834. if (responseType && responseType !== 'json') {
  6835. request.responseType = config.responseType;
  6836. }
  6837. // Handle progress if needed
  6838. if (typeof config.onDownloadProgress === 'function') {
  6839. request.addEventListener('progress', config.onDownloadProgress);
  6840. }
  6841. // Not all browsers support upload events
  6842. if (typeof config.onUploadProgress === 'function' && request.upload) {
  6843. request.upload.addEventListener('progress', config.onUploadProgress);
  6844. }
  6845. if (config.cancelToken || config.signal) {
  6846. // Handle cancellation
  6847. // eslint-disable-next-line func-names
  6848. onCanceled = function(cancel) {
  6849. if (!request) {
  6850. return;
  6851. }
  6852. reject(!cancel || (cancel && cancel.type) ? new CanceledError_1() : cancel);
  6853. request.abort();
  6854. request = null;
  6855. };
  6856. config.cancelToken && config.cancelToken.subscribe(onCanceled);
  6857. if (config.signal) {
  6858. config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
  6859. }
  6860. }
  6861. if (!requestData) {
  6862. requestData = null;
  6863. }
  6864. var protocol = parseProtocol(fullPath);
  6865. if (protocol && ['http', 'https', 'file'].indexOf(protocol) === -1) {
  6866. reject(new AxiosError_1('Unsupported protocol ' + protocol + ':', AxiosError_1.ERR_BAD_REQUEST,
  6867. config));
  6868. return;
  6869. }
  6870. // Send the request
  6871. request.send(requestData);
  6872. });
  6873. };
  6874. // eslint-disable-next-line strict
  6875. var _null = null;
  6876. var DEFAULT_CONTENT_TYPE = {
  6877. 'Content-Type': 'application/x-www-form-urlencoded'
  6878. };
  6879. function setContentTypeIfUnset(headers, value) {
  6880. if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
  6881. headers['Content-Type'] = value;
  6882. }
  6883. }
  6884. function getDefaultAdapter() {
  6885. var adapter;
  6886. if (typeof XMLHttpRequest !== 'undefined') {
  6887. // For browsers use XHR adapter
  6888. adapter = xhr;
  6889. } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
  6890. // For node use HTTP adapter
  6891. adapter = xhr;
  6892. }
  6893. return adapter;
  6894. }
  6895. function stringifySafely(rawValue, parser, encoder) {
  6896. if (utils.isString(rawValue)) {
  6897. try {
  6898. (parser || JSON.parse)(rawValue);
  6899. return utils.trim(rawValue);
  6900. } catch (e) {
  6901. if (e.name !== 'SyntaxError') {
  6902. throw e;
  6903. }
  6904. }
  6905. }
  6906. return (encoder || JSON.stringify)(rawValue);
  6907. }
  6908. var defaults = {
  6909. transitional: transitional,
  6910. adapter: getDefaultAdapter(),
  6911. transformRequest: [function transformRequest(data, headers) {
  6912. normalizeHeaderName(headers, 'Accept');
  6913. normalizeHeaderName(headers, 'Content-Type');
  6914. if (utils.isFormData(data) ||
  6915. utils.isArrayBuffer(data) ||
  6916. utils.isBuffer(data) ||
  6917. utils.isStream(data) ||
  6918. utils.isFile(data) ||
  6919. utils.isBlob(data)
  6920. ) {
  6921. return data;
  6922. }
  6923. if (utils.isArrayBufferView(data)) {
  6924. return data.buffer;
  6925. }
  6926. if (utils.isURLSearchParams(data)) {
  6927. setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
  6928. return data.toString();
  6929. }
  6930. var isObjectPayload = utils.isObject(data);
  6931. var contentType = headers && headers['Content-Type'];
  6932. var isFileList;
  6933. if ((isFileList = utils.isFileList(data)) || (isObjectPayload && contentType ===
  6934. 'multipart/form-data')) {
  6935. var _FormData = this.env && this.env.FormData;
  6936. return toFormData_1(isFileList ? {
  6937. 'files[]': data
  6938. } : data, _FormData && new _FormData());
  6939. } else if (isObjectPayload || contentType === 'application/json') {
  6940. setContentTypeIfUnset(headers, 'application/json');
  6941. return stringifySafely(data);
  6942. }
  6943. return data;
  6944. }],
  6945. transformResponse: [function transformResponse(data) {
  6946. var transitional = this.transitional || defaults.transitional;
  6947. var silentJSONParsing = transitional && transitional.silentJSONParsing;
  6948. var forcedJSONParsing = transitional && transitional.forcedJSONParsing;
  6949. var strictJSONParsing = !silentJSONParsing && this.responseType === 'json';
  6950. if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) {
  6951. try {
  6952. return JSON.parse(data);
  6953. } catch (e) {
  6954. if (strictJSONParsing) {
  6955. if (e.name === 'SyntaxError') {
  6956. throw AxiosError_1.from(e, AxiosError_1.ERR_BAD_RESPONSE, this, null, this
  6957. .response);
  6958. }
  6959. throw e;
  6960. }
  6961. }
  6962. }
  6963. return data;
  6964. }],
  6965. /**
  6966. * A timeout in milliseconds to abort a request. If set to 0 (default) a
  6967. * timeout is not created.
  6968. */
  6969. timeout: 0,
  6970. xsrfCookieName: 'XSRF-TOKEN',
  6971. xsrfHeaderName: 'X-XSRF-TOKEN',
  6972. maxContentLength: -1,
  6973. maxBodyLength: -1,
  6974. env: {
  6975. FormData: _null
  6976. },
  6977. validateStatus: function validateStatus(status) {
  6978. return status >= 200 && status < 300;
  6979. },
  6980. headers: {
  6981. common: {
  6982. 'Accept': 'application/json, text/plain, */*'
  6983. }
  6984. }
  6985. };
  6986. utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
  6987. defaults.headers[method] = {};
  6988. });
  6989. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  6990. defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
  6991. });
  6992. var defaults_1 = defaults;
  6993. /**
  6994. * Transform the data for a request or a response
  6995. *
  6996. * @param {Object|String} data The data to be transformed
  6997. * @param {Array} headers The headers for the request or response
  6998. * @param {Array|Function} fns A single function or Array of functions
  6999. * @returns {*} The resulting transformed data
  7000. */
  7001. var transformData = function transformData(data, headers, fns) {
  7002. var context = this || defaults_1;
  7003. /*eslint no-param-reassign:0*/
  7004. utils.forEach(fns, function transform(fn) {
  7005. data = fn.call(context, data, headers);
  7006. });
  7007. return data;
  7008. };
  7009. var isCancel = function isCancel(value) {
  7010. return !!(value && value.__CANCEL__);
  7011. };
  7012. /**
  7013. * Throws a `CanceledError` if cancellation has been requested.
  7014. */
  7015. function throwIfCancellationRequested(config) {
  7016. if (config.cancelToken) {
  7017. config.cancelToken.throwIfRequested();
  7018. }
  7019. if (config.signal && config.signal.aborted) {
  7020. throw new CanceledError_1();
  7021. }
  7022. }
  7023. /**
  7024. * Dispatch a request to the server using the configured adapter.
  7025. *
  7026. * @param {object} config The config that is to be used for the request
  7027. * @returns {Promise} The Promise to be fulfilled
  7028. */
  7029. var dispatchRequest = function dispatchRequest(config) {
  7030. throwIfCancellationRequested(config);
  7031. // Ensure headers exist
  7032. config.headers = config.headers || {};
  7033. // Transform request data
  7034. config.data = transformData.call(
  7035. config,
  7036. config.data,
  7037. config.headers,
  7038. config.transformRequest
  7039. );
  7040. // Flatten headers
  7041. config.headers = utils.merge(
  7042. config.headers.common || {},
  7043. config.headers[config.method] || {},
  7044. config.headers
  7045. );
  7046. utils.forEach(
  7047. ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
  7048. function cleanHeaderConfig(method) {
  7049. delete config.headers[method];
  7050. }
  7051. );
  7052. var adapter = config.adapter || defaults_1.adapter;
  7053. return adapter(config).then(function onAdapterResolution(response) {
  7054. throwIfCancellationRequested(config);
  7055. // Transform response data
  7056. response.data = transformData.call(
  7057. config,
  7058. response.data,
  7059. response.headers,
  7060. config.transformResponse
  7061. );
  7062. return response;
  7063. }, function onAdapterRejection(reason) {
  7064. if (!isCancel(reason)) {
  7065. throwIfCancellationRequested(config);
  7066. // Transform response data
  7067. if (reason && reason.response) {
  7068. reason.response.data = transformData.call(
  7069. config,
  7070. reason.response.data,
  7071. reason.response.headers,
  7072. config.transformResponse
  7073. );
  7074. }
  7075. }
  7076. return Promise.reject(reason);
  7077. });
  7078. };
  7079. /**
  7080. * Config-specific merge-function which creates a new config-object
  7081. * by merging two configuration objects together.
  7082. *
  7083. * @param {Object} config1
  7084. * @param {Object} config2
  7085. * @returns {Object} New object resulting from merging config2 to config1
  7086. */
  7087. var mergeConfig = function mergeConfig(config1, config2) {
  7088. // eslint-disable-next-line no-param-reassign
  7089. config2 = config2 || {};
  7090. var config = {};
  7091. function getMergedValue(target, source) {
  7092. if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
  7093. return utils.merge(target, source);
  7094. } else if (utils.isPlainObject(source)) {
  7095. return utils.merge({}, source);
  7096. } else if (utils.isArray(source)) {
  7097. return source.slice();
  7098. }
  7099. return source;
  7100. }
  7101. // eslint-disable-next-line consistent-return
  7102. function mergeDeepProperties(prop) {
  7103. if (!utils.isUndefined(config2[prop])) {
  7104. return getMergedValue(config1[prop], config2[prop]);
  7105. } else if (!utils.isUndefined(config1[prop])) {
  7106. return getMergedValue(undefined, config1[prop]);
  7107. }
  7108. }
  7109. // eslint-disable-next-line consistent-return
  7110. function valueFromConfig2(prop) {
  7111. if (!utils.isUndefined(config2[prop])) {
  7112. return getMergedValue(undefined, config2[prop]);
  7113. }
  7114. }
  7115. // eslint-disable-next-line consistent-return
  7116. function defaultToConfig2(prop) {
  7117. if (!utils.isUndefined(config2[prop])) {
  7118. return getMergedValue(undefined, config2[prop]);
  7119. } else if (!utils.isUndefined(config1[prop])) {
  7120. return getMergedValue(undefined, config1[prop]);
  7121. }
  7122. }
  7123. // eslint-disable-next-line consistent-return
  7124. function mergeDirectKeys(prop) {
  7125. if (prop in config2) {
  7126. return getMergedValue(config1[prop], config2[prop]);
  7127. } else if (prop in config1) {
  7128. return getMergedValue(undefined, config1[prop]);
  7129. }
  7130. }
  7131. var mergeMap = {
  7132. 'url': valueFromConfig2,
  7133. 'method': valueFromConfig2,
  7134. 'data': valueFromConfig2,
  7135. 'baseURL': defaultToConfig2,
  7136. 'transformRequest': defaultToConfig2,
  7137. 'transformResponse': defaultToConfig2,
  7138. 'paramsSerializer': defaultToConfig2,
  7139. 'timeout': defaultToConfig2,
  7140. 'timeoutMessage': defaultToConfig2,
  7141. 'withCredentials': defaultToConfig2,
  7142. 'adapter': defaultToConfig2,
  7143. 'responseType': defaultToConfig2,
  7144. 'xsrfCookieName': defaultToConfig2,
  7145. 'xsrfHeaderName': defaultToConfig2,
  7146. 'onUploadProgress': defaultToConfig2,
  7147. 'onDownloadProgress': defaultToConfig2,
  7148. 'decompress': defaultToConfig2,
  7149. 'maxContentLength': defaultToConfig2,
  7150. 'maxBodyLength': defaultToConfig2,
  7151. 'beforeRedirect': defaultToConfig2,
  7152. 'transport': defaultToConfig2,
  7153. 'httpAgent': defaultToConfig2,
  7154. 'httpsAgent': defaultToConfig2,
  7155. 'cancelToken': defaultToConfig2,
  7156. 'socketPath': defaultToConfig2,
  7157. 'responseEncoding': defaultToConfig2,
  7158. 'validateStatus': mergeDirectKeys
  7159. };
  7160. utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {
  7161. var merge = mergeMap[prop] || mergeDeepProperties;
  7162. var configValue = merge(prop);
  7163. (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
  7164. });
  7165. return config;
  7166. };
  7167. var data = {
  7168. "version": "0.27.2"
  7169. };
  7170. var VERSION = data.version;
  7171. var validators$1 = {};
  7172. // eslint-disable-next-line func-names
  7173. ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {
  7174. validators$1[type] = function validator(thing) {
  7175. return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
  7176. };
  7177. });
  7178. var deprecatedWarnings = {};
  7179. /**
  7180. * Transitional option validator
  7181. * @param {function|boolean?} validator - set to false if the transitional option has been removed
  7182. * @param {string?} version - deprecated version / removed since version
  7183. * @param {string?} message - some message with additional info
  7184. * @returns {function}
  7185. */
  7186. validators$1.transitional = function transitional(validator, version, message) {
  7187. function formatMessage(opt, desc) {
  7188. return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message :
  7189. '');
  7190. }
  7191. // eslint-disable-next-line func-names
  7192. return function(value, opt, opts) {
  7193. if (validator === false) {
  7194. throw new AxiosError_1(
  7195. formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
  7196. AxiosError_1.ERR_DEPRECATED
  7197. );
  7198. }
  7199. if (version && !deprecatedWarnings[opt]) {
  7200. deprecatedWarnings[opt] = true;
  7201. // eslint-disable-next-line no-console
  7202. console.warn(
  7203. formatMessage(
  7204. opt,
  7205. ' has been deprecated since v' + version + ' and will be removed in the near future'
  7206. )
  7207. );
  7208. }
  7209. return validator ? validator(value, opt, opts) : true;
  7210. };
  7211. };
  7212. /**
  7213. * Assert object's properties type
  7214. * @param {object} options
  7215. * @param {object} schema
  7216. * @param {boolean?} allowUnknown
  7217. */
  7218. function assertOptions(options, schema, allowUnknown) {
  7219. if (typeof options !== 'object') {
  7220. throw new AxiosError_1('options must be an object', AxiosError_1.ERR_BAD_OPTION_VALUE);
  7221. }
  7222. var keys = Object.keys(options);
  7223. var i = keys.length;
  7224. while (i-- > 0) {
  7225. var opt = keys[i];
  7226. var validator = schema[opt];
  7227. if (validator) {
  7228. var value = options[opt];
  7229. var result = value === undefined || validator(value, opt, options);
  7230. if (result !== true) {
  7231. throw new AxiosError_1('option ' + opt + ' must be ' + result, AxiosError_1.ERR_BAD_OPTION_VALUE);
  7232. }
  7233. continue;
  7234. }
  7235. if (allowUnknown !== true) {
  7236. throw new AxiosError_1('Unknown option ' + opt, AxiosError_1.ERR_BAD_OPTION);
  7237. }
  7238. }
  7239. }
  7240. var validator = {
  7241. assertOptions: assertOptions,
  7242. validators: validators$1
  7243. };
  7244. var validators = validator.validators;
  7245. /**
  7246. * Create a new instance of Axios
  7247. *
  7248. * @param {Object} instanceConfig The default config for the instance
  7249. */
  7250. function Axios(instanceConfig) {
  7251. this.defaults = instanceConfig;
  7252. this.interceptors = {
  7253. request: new InterceptorManager_1(),
  7254. response: new InterceptorManager_1()
  7255. };
  7256. }
  7257. /**
  7258. * Dispatch a request
  7259. *
  7260. * @param {Object} config The config specific for this request (merged with this.defaults)
  7261. */
  7262. Axios.prototype.request = function request(configOrUrl, config) {
  7263. /*eslint no-param-reassign:0*/
  7264. // Allow for axios('example/url'[, config]) a la fetch API
  7265. if (typeof configOrUrl === 'string') {
  7266. config = config || {};
  7267. config.url = configOrUrl;
  7268. } else {
  7269. config = configOrUrl || {};
  7270. }
  7271. config = mergeConfig(this.defaults, config);
  7272. // Set config.method
  7273. if (config.method) {
  7274. config.method = config.method.toLowerCase();
  7275. } else if (this.defaults.method) {
  7276. config.method = this.defaults.method.toLowerCase();
  7277. } else {
  7278. config.method = 'get';
  7279. }
  7280. var transitional = config.transitional;
  7281. if (transitional !== undefined) {
  7282. validator.assertOptions(transitional, {
  7283. silentJSONParsing: validators.transitional(validators.boolean),
  7284. forcedJSONParsing: validators.transitional(validators.boolean),
  7285. clarifyTimeoutError: validators.transitional(validators.boolean)
  7286. }, false);
  7287. }
  7288. // filter out skipped interceptors
  7289. var requestInterceptorChain = [];
  7290. var synchronousRequestInterceptors = true;
  7291. this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
  7292. if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
  7293. return;
  7294. }
  7295. synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
  7296. requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
  7297. });
  7298. var responseInterceptorChain = [];
  7299. this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
  7300. responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
  7301. });
  7302. var promise;
  7303. if (!synchronousRequestInterceptors) {
  7304. var chain = [dispatchRequest, undefined];
  7305. Array.prototype.unshift.apply(chain, requestInterceptorChain);
  7306. chain = chain.concat(responseInterceptorChain);
  7307. promise = Promise.resolve(config);
  7308. while (chain.length) {
  7309. promise = promise.then(chain.shift(), chain.shift());
  7310. }
  7311. return promise;
  7312. }
  7313. var newConfig = config;
  7314. while (requestInterceptorChain.length) {
  7315. var onFulfilled = requestInterceptorChain.shift();
  7316. var onRejected = requestInterceptorChain.shift();
  7317. try {
  7318. newConfig = onFulfilled(newConfig);
  7319. } catch (error) {
  7320. onRejected(error);
  7321. break;
  7322. }
  7323. }
  7324. try {
  7325. promise = dispatchRequest(newConfig);
  7326. } catch (error) {
  7327. return Promise.reject(error);
  7328. }
  7329. while (responseInterceptorChain.length) {
  7330. promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
  7331. }
  7332. return promise;
  7333. };
  7334. Axios.prototype.getUri = function getUri(config) {
  7335. config = mergeConfig(this.defaults, config);
  7336. var fullPath = buildFullPath(config.baseURL, config.url);
  7337. return buildURL(fullPath, config.params, config.paramsSerializer);
  7338. };
  7339. // Provide aliases for supported request methods
  7340. utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
  7341. /*eslint func-names:0*/
  7342. Axios.prototype[method] = function(url, config) {
  7343. return this.request(mergeConfig(config || {}, {
  7344. method: method,
  7345. url: url,
  7346. data: (config || {}).data
  7347. }));
  7348. };
  7349. });
  7350. utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
  7351. /*eslint func-names:0*/
  7352. function generateHTTPMethod(isForm) {
  7353. return function httpMethod(url, data, config) {
  7354. return this.request(mergeConfig(config || {}, {
  7355. method: method,
  7356. headers: isForm ? {
  7357. 'Content-Type': 'multipart/form-data'
  7358. } : {},
  7359. url: url,
  7360. data: data
  7361. }));
  7362. };
  7363. }
  7364. Axios.prototype[method] = generateHTTPMethod();
  7365. Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
  7366. });
  7367. var Axios_1 = Axios;
  7368. /**
  7369. * A `CancelToken` is an object that can be used to request cancellation of an operation.
  7370. *
  7371. * @class
  7372. * @param {Function} executor The executor function.
  7373. */
  7374. function CancelToken(executor) {
  7375. if (typeof executor !== 'function') {
  7376. throw new TypeError('executor must be a function.');
  7377. }
  7378. var resolvePromise;
  7379. this.promise = new Promise(function promiseExecutor(resolve) {
  7380. resolvePromise = resolve;
  7381. });
  7382. var token = this;
  7383. // eslint-disable-next-line func-names
  7384. this.promise.then(function(cancel) {
  7385. if (!token._listeners) return;
  7386. var i;
  7387. var l = token._listeners.length;
  7388. for (i = 0; i < l; i++) {
  7389. token._listeners[i](cancel);
  7390. }
  7391. token._listeners = null;
  7392. });
  7393. // eslint-disable-next-line func-names
  7394. this.promise.then = function(onfulfilled) {
  7395. var _resolve;
  7396. // eslint-disable-next-line func-names
  7397. var promise = new Promise(function(resolve) {
  7398. token.subscribe(resolve);
  7399. _resolve = resolve;
  7400. }).then(onfulfilled);
  7401. promise.cancel = function reject() {
  7402. token.unsubscribe(_resolve);
  7403. };
  7404. return promise;
  7405. };
  7406. executor(function cancel(message) {
  7407. if (token.reason) {
  7408. // Cancellation has already been requested
  7409. return;
  7410. }
  7411. token.reason = new CanceledError_1(message);
  7412. resolvePromise(token.reason);
  7413. });
  7414. }
  7415. /**
  7416. * Throws a `CanceledError` if cancellation has been requested.
  7417. */
  7418. CancelToken.prototype.throwIfRequested = function throwIfRequested() {
  7419. if (this.reason) {
  7420. throw this.reason;
  7421. }
  7422. };
  7423. /**
  7424. * Subscribe to the cancel signal
  7425. */
  7426. CancelToken.prototype.subscribe = function subscribe(listener) {
  7427. if (this.reason) {
  7428. listener(this.reason);
  7429. return;
  7430. }
  7431. if (this._listeners) {
  7432. this._listeners.push(listener);
  7433. } else {
  7434. this._listeners = [listener];
  7435. }
  7436. };
  7437. /**
  7438. * Unsubscribe from the cancel signal
  7439. */
  7440. CancelToken.prototype.unsubscribe = function unsubscribe(listener) {
  7441. if (!this._listeners) {
  7442. return;
  7443. }
  7444. var index = this._listeners.indexOf(listener);
  7445. if (index !== -1) {
  7446. this._listeners.splice(index, 1);
  7447. }
  7448. };
  7449. /**
  7450. * Returns an object that contains a new `CancelToken` and a function that, when called,
  7451. * cancels the `CancelToken`.
  7452. */
  7453. CancelToken.source = function source() {
  7454. var cancel;
  7455. var token = new CancelToken(function executor(c) {
  7456. cancel = c;
  7457. });
  7458. return {
  7459. token: token,
  7460. cancel: cancel
  7461. };
  7462. };
  7463. var CancelToken_1 = CancelToken;
  7464. /**
  7465. * Syntactic sugar for invoking a function and expanding an array for arguments.
  7466. *
  7467. * Common use case would be to use `Function.prototype.apply`.
  7468. *
  7469. * ```js
  7470. * function f(x, y, z) {}
  7471. * var args = [1, 2, 3];
  7472. * f.apply(null, args);
  7473. * ```
  7474. *
  7475. * With `spread` this example can be re-written.
  7476. *
  7477. * ```js
  7478. * spread(function(x, y, z) {})([1, 2, 3]);
  7479. * ```
  7480. *
  7481. * @param {Function} callback
  7482. * @returns {Function}
  7483. */
  7484. var spread = function spread(callback) {
  7485. return function wrap(arr) {
  7486. return callback.apply(null, arr);
  7487. };
  7488. };
  7489. /**
  7490. * Determines whether the payload is an error thrown by Axios
  7491. *
  7492. * @param {*} payload The value to test
  7493. * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
  7494. */
  7495. var isAxiosError = function isAxiosError(payload) {
  7496. return utils.isObject(payload) && (payload.isAxiosError === true);
  7497. };
  7498. /**
  7499. * Create an instance of Axios
  7500. *
  7501. * @param {Object} defaultConfig The default config for the instance
  7502. * @return {Axios} A new instance of Axios
  7503. */
  7504. function createInstance(defaultConfig) {
  7505. var context = new Axios_1(defaultConfig);
  7506. var instance = bind(Axios_1.prototype.request, context);
  7507. // Copy axios.prototype to instance
  7508. utils.extend(instance, Axios_1.prototype, context);
  7509. // Copy context to instance
  7510. utils.extend(instance, context);
  7511. // Factory for creating new instances
  7512. instance.create = function create(instanceConfig) {
  7513. return createInstance(mergeConfig(defaultConfig, instanceConfig));
  7514. };
  7515. return instance;
  7516. }
  7517. // Create the default instance to be exported
  7518. var axios$1 = createInstance(defaults_1);
  7519. // Expose Axios class to allow class inheritance
  7520. axios$1.Axios = Axios_1;
  7521. // Expose Cancel & CancelToken
  7522. axios$1.CanceledError = CanceledError_1;
  7523. axios$1.CancelToken = CancelToken_1;
  7524. axios$1.isCancel = isCancel;
  7525. axios$1.VERSION = data.version;
  7526. axios$1.toFormData = toFormData_1;
  7527. // Expose AxiosError class
  7528. axios$1.AxiosError = AxiosError_1;
  7529. // alias for CanceledError for backward compatibility
  7530. axios$1.Cancel = axios$1.CanceledError;
  7531. // Expose all/spread
  7532. axios$1.all = function all(promises) {
  7533. return Promise.all(promises);
  7534. };
  7535. axios$1.spread = spread;
  7536. // Expose isAxiosError
  7537. axios$1.isAxiosError = isAxiosError;
  7538. var axios_1 = axios$1;
  7539. // Allow use of default import syntax in TypeScript
  7540. var _default = axios$1;
  7541. axios_1.default = _default;
  7542. var axios = axios_1;
  7543. class RTCEndpoint extends Event$1 {
  7544. constructor(options) {
  7545. super('RTCPusherPlayer');
  7546. this.TAG = '[RTCPusherPlayer]';
  7547. let defaults = {
  7548. element: '',
  7549. // html video element
  7550. debug: false,
  7551. // if output debug log
  7552. zlmsdpUrl: '',
  7553. simulcast: false,
  7554. useCamera: true,
  7555. audioEnable: true,
  7556. videoEnable: true,
  7557. recvOnly: false,
  7558. resolution: {
  7559. w: 0,
  7560. h: 0
  7561. },
  7562. usedatachannel: false
  7563. };
  7564. this.options = Object.assign({}, defaults, options);
  7565. if (this.options.debug) {
  7566. setLogger();
  7567. }
  7568. this.e = {
  7569. onicecandidate: this._onIceCandidate.bind(this),
  7570. ontrack: this._onTrack.bind(this),
  7571. onicecandidateerror: this._onIceCandidateError.bind(this),
  7572. onconnectionstatechange: this._onconnectionstatechange.bind(this),
  7573. ondatachannelopen: this._onDataChannelOpen.bind(this),
  7574. ondatachannelmsg: this._onDataChannelMsg.bind(this),
  7575. ondatachannelerr: this._onDataChannelErr.bind(this),
  7576. ondatachannelclose: this._onDataChannelClose.bind(this)
  7577. };
  7578. this._remoteStream = null;
  7579. this._localStream = null;
  7580. this.pc = new RTCPeerConnection(null);
  7581. this.pc.onicecandidate = this.e.onicecandidate;
  7582. this.pc.onicecandidateerror = this.e.onicecandidateerror;
  7583. this.pc.ontrack = this.e.ontrack;
  7584. this.pc.onconnectionstatechange = this.e.onconnectionstatechange;
  7585. this.datachannel = null;
  7586. if (this.options.usedatachannel) {
  7587. this.datachannel = this.pc.createDataChannel('chat');
  7588. this.datachannel.onclose = this.e.ondatachannelclose;
  7589. this.datachannel.onerror = this.e.ondatachannelerr;
  7590. this.datachannel.onmessage = this.e.ondatachannelmsg;
  7591. this.datachannel.onopen = this.e.ondatachannelopen;
  7592. }
  7593. if (!this.options.recvOnly && (this.options.audioEnable || this.options.videoEnable)) this.start();
  7594. else this.receive();
  7595. }
  7596. receive() {
  7597. const AudioTransceiverInit = {
  7598. direction: 'recvonly',
  7599. sendEncodings: []
  7600. };
  7601. const VideoTransceiverInit = {
  7602. direction: 'recvonly',
  7603. sendEncodings: []
  7604. };
  7605. if (this.options.videoEnable) {
  7606. this.pc.addTransceiver('video', VideoTransceiverInit);
  7607. }
  7608. if (this.options.audioEnable) {
  7609. this.pc.addTransceiver('audio', AudioTransceiverInit);
  7610. }
  7611. this.pc.createOffer().then(desc => {
  7612. log(this.TAG, 'offer:', desc.sdp);
  7613. this.pc.setLocalDescription(desc).then(() => {
  7614. axios({
  7615. method: 'post',
  7616. url: this.options.zlmsdpUrl,
  7617. responseType: 'json',
  7618. data: desc.sdp,
  7619. headers: {
  7620. 'Content-Type': 'text/plain;charset=utf-8'
  7621. }
  7622. }).then(response => {
  7623. let ret = response.data; //JSON.parse(response.data);
  7624. if (ret.code != 0) {
  7625. // mean failed for offer/anwser exchange
  7626. this.dispatch(Events$1.WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED, ret);
  7627. return;
  7628. }
  7629. let anwser = {};
  7630. var re = this.replaceCandidate(ret.sdp);
  7631. anwser.sdp = re;
  7632. anwser.type = 'answer';
  7633. log(this.TAG, 'answer:', ret.sdp);
  7634. this.pc.setRemoteDescription(anwser).then(() => {
  7635. this.options.successCallback()
  7636. log(this.TAG, 'set remote sucess');
  7637. }).catch(e => {
  7638. error(this.TAG, e);
  7639. });
  7640. }).catch(err => {
  7641. clearInterval(heartBeatFlag)
  7642. ws.close()
  7643. });
  7644. });
  7645. }).catch(e => {
  7646. error(this.TAG, e);
  7647. });
  7648. }
  7649. splitSections(blob) {
  7650. var parts = blob.split('\nm=');
  7651. return parts.map(function(part, index) {
  7652. return (index > 0 ? 'm=' + part : part).trim() + '\r\n';
  7653. });
  7654. }
  7655. splitLines(blob) {
  7656. return blob.trim().split('\n').map(function(line) {
  7657. return line.trim();
  7658. });
  7659. }
  7660. matchPrefixExt(blob, prefix) {
  7661. return this.splitLines(blob).filter(function(line) {
  7662. return line.indexOf(prefix) === 0;
  7663. });
  7664. }
  7665. replaceCandidate(sdp) {
  7666. var sections = this.splitSections(sdp);
  7667. var cands;
  7668. sections.forEach(e => {
  7669. // console.log('==========eee',e)
  7670. cands = this.matchPrefixExt(e, 'a=candidate:');
  7671. // console.log(cands[0]);
  7672. });
  7673. // console.log("=======ip---------", window.cloudgame_sdk.extraData.remainingTimeData.data.extranetIp, window.cloudgame_sdk.extraData.remainingTimeData.data.extranetPort);
  7674. let aaa =
  7675. `a=candidate:udpcandidate 1 udp 120 typ host`;
  7676. var data = '';
  7677. // const deviceInline = CLOUD_GAME_SDK.getQueryVariable("deviceInline")
  7678. if (window.location.protocol === 'http:') {
  7679. data = sdp;
  7680. } else {
  7681. // data = sdp.replaceAll(cands[0], aaa);
  7682. // data = sdp.replace(/cands[0]/g, aaa);
  7683. data = sdp.replace(new RegExp(cands[0], 'g'), aaa);
  7684. }
  7685. // const data = sdp
  7686. return data
  7687. // console.log(sections);
  7688. }
  7689. start() {
  7690. let videoConstraints = false;
  7691. let audioConstraints = false;
  7692. if (this.options.useCamera) {
  7693. if (this.options.videoEnable) videoConstraints = new VideoTrackConstraints(VideoSourceInfo.CAMERA);
  7694. if (this.options.audioEnable) audioConstraints = new AudioTrackConstraints(AudioSourceInfo.MIC);
  7695. } else {
  7696. if (this.options.videoEnable) {
  7697. videoConstraints = new VideoTrackConstraints(VideoSourceInfo.SCREENCAST);
  7698. if (this.options.audioEnable) audioConstraints = new AudioTrackConstraints(AudioSourceInfo
  7699. .SCREENCAST);
  7700. } else {
  7701. if (this.options.audioEnable) audioConstraints = new AudioTrackConstraints(AudioSourceInfo.MIC);
  7702. else {
  7703. // error shared display media not only audio
  7704. error(this.TAG, 'error paramter');
  7705. }
  7706. }
  7707. }
  7708. if (this.options.resolution.w != 0 && this.options.resolution.h != 0 && typeof videoConstraints ==
  7709. 'object') {
  7710. videoConstraints.resolution = new Resolution(this.options.resolution.w, this.options.resolution.h);
  7711. }
  7712. MediaStreamFactory.createMediaStream(new StreamConstraints(audioConstraints, videoConstraints)).then(
  7713. stream => {
  7714. this._localStream = stream;
  7715. this.dispatch(Events$1.WEBRTC_ON_LOCAL_STREAM, stream);
  7716. const AudioTransceiverInit = {
  7717. direction: 'sendrecv',
  7718. sendEncodings: []
  7719. };
  7720. const VideoTransceiverInit = {
  7721. direction: 'sendrecv',
  7722. sendEncodings: []
  7723. };
  7724. if (this.options.simulcast && stream.getVideoTracks().length > 0) {
  7725. VideoTransceiverInit.sendEncodings = [{
  7726. rid: 'h',
  7727. active: true,
  7728. maxBitrate: 1000000
  7729. }, {
  7730. rid: 'm',
  7731. active: true,
  7732. maxBitrate: 500000,
  7733. scaleResolutionDownBy: 2
  7734. }, {
  7735. rid: 'l',
  7736. active: true,
  7737. maxBitrate: 200000,
  7738. scaleResolutionDownBy: 4
  7739. }];
  7740. }
  7741. if (this.options.audioEnable) {
  7742. if (stream.getAudioTracks().length > 0) {
  7743. this.pc.addTransceiver(stream.getAudioTracks()[0], AudioTransceiverInit);
  7744. } else {
  7745. AudioTransceiverInit.direction = 'recvonly';
  7746. this.pc.addTransceiver('audio', AudioTransceiverInit);
  7747. }
  7748. }
  7749. if (this.options.videoEnable) {
  7750. if (stream.getVideoTracks().length > 0) {
  7751. this.pc.addTransceiver(stream.getVideoTracks()[0], VideoTransceiverInit);
  7752. } else {
  7753. VideoTransceiverInit.direction = 'recvonly';
  7754. this.pc.addTransceiver('video', VideoTransceiverInit);
  7755. }
  7756. }
  7757. /*
  7758. stream.getTracks().forEach((track,idx)=>{
  7759. debug.log(this.TAG,track);
  7760. this.pc.addTrack(track);
  7761. });
  7762. */
  7763. this.pc.createOffer().then(desc => {
  7764. log(this.TAG, 'offer:', desc.sdp);
  7765. this.pc.setLocalDescription(desc).then(() => {
  7766. axios({
  7767. method: 'post',
  7768. url: this.options.zlmsdpUrl,
  7769. responseType: 'json',
  7770. data: desc.sdp,
  7771. headers: {
  7772. 'Content-Type': 'text/plain;charset=utf-8'
  7773. }
  7774. }).then(response => {
  7775. let ret = response.data; //JSON.parse(response.data);
  7776. if (ret.code != 0) {
  7777. // mean failed for offer/anwser exchange
  7778. this.dispatch(Events$1
  7779. .WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED, ret);
  7780. return;
  7781. }
  7782. let anwser = {};
  7783. anwser.sdp = ret.sdp;
  7784. anwser.type = 'answer';
  7785. log(this.TAG, 'answer:', ret.sdp);
  7786. this.pc.setRemoteDescription(anwser).then(() => {
  7787. log(this.TAG, 'set remote sucess');
  7788. }).catch(e => {
  7789. error(this.TAG, e);
  7790. });
  7791. });
  7792. });
  7793. }).catch(e => {
  7794. error(this.TAG, e);
  7795. });
  7796. }).catch(e => {
  7797. this.dispatch(Events$1.CAPTURE_STREAM_FAILED); //debug.error(this.TAG,e);
  7798. }); //const offerOptions = {};
  7799. /*
  7800. if (typeof this.pc.addTransceiver === 'function') {
  7801. // |direction| seems not working on Safari.
  7802. this.pc.addTransceiver('audio', { direction: 'recvonly' });
  7803. this.pc.addTransceiver('video', { direction: 'recvonly' });
  7804. } else {
  7805. offerOptions.offerToReceiveAudio = true;
  7806. offerOptions.offerToReceiveVideo = true;
  7807. }
  7808. */
  7809. }
  7810. _onIceCandidate(event) {
  7811. if (event.candidate) {
  7812. log('Remote ICE candidate: \n ' + event.candidate.candidate); // Send the candidate to the remote peer
  7813. }
  7814. }
  7815. _onTrack(event) {
  7816. if (this.options.element && event.streams && event.streams.length > 0) {
  7817. this.options.element.srcObject = event.streams[0];
  7818. this._remoteStream = event.streams[0];
  7819. this.dispatch(Events$1.WEBRTC_ON_REMOTE_STREAMS, event);
  7820. } else {
  7821. error('element pararm is failed');
  7822. }
  7823. }
  7824. _onIceCandidateError(event) {
  7825. this.dispatch(Events$1.WEBRTC_ICE_CANDIDATE_ERROR, event);
  7826. }
  7827. _onconnectionstatechange(event) {
  7828. this.dispatch(Events$1.WEBRTC_ON_CONNECTION_STATE_CHANGE, this.pc.connectionState);
  7829. }
  7830. _onDataChannelOpen(event) {
  7831. log(this.TAG, 'ondatachannel open:', event);
  7832. this.dispatch(Events$1.WEBRTC_ON_DATA_CHANNEL_OPEN, event);
  7833. }
  7834. _onDataChannelMsg(event) {
  7835. log(this.TAG, 'ondatachannel msg:', event);
  7836. this.dispatch(Events$1.WEBRTC_ON_DATA_CHANNEL_MSG, event);
  7837. }
  7838. _onDataChannelErr(event) {
  7839. log(this.TAG, 'ondatachannel err:', event);
  7840. this.dispatch(Events$1.WEBRTC_ON_DATA_CHANNEL_ERR, event);
  7841. }
  7842. _onDataChannelClose(event) {
  7843. log(this.TAG, 'ondatachannel close:', event);
  7844. this.dispatch(Events$1.WEBRTC_ON_DATA_CHANNEL_CLOSE, event);
  7845. }
  7846. sendMsg(data) {
  7847. if (this.datachannel != null) {
  7848. this.datachannel.send(data);
  7849. } else {
  7850. error(this.TAG, 'data channel is null');
  7851. }
  7852. }
  7853. closeDataChannel() {
  7854. if (this.datachannel) {
  7855. this.datachannel.close();
  7856. this.datachannel = null;
  7857. }
  7858. }
  7859. close() {
  7860. this.closeDataChannel();
  7861. if (this.pc) {
  7862. this.pc.close();
  7863. this.pc = null;
  7864. }
  7865. if (this.options) {
  7866. this.options = null;
  7867. }
  7868. if (this._localStream) {
  7869. this._localStream.getTracks().forEach((track, idx) => {
  7870. track.stop();
  7871. });
  7872. }
  7873. if (this._remoteStream) {
  7874. this._remoteStream.getTracks().forEach((track, idx) => {
  7875. track.stop();
  7876. });
  7877. }
  7878. }
  7879. get remoteStream() {
  7880. return this._remoteStream;
  7881. }
  7882. get localStream() {
  7883. return this._localStream;
  7884. }
  7885. }
  7886. console.log('build date:', BUILD_DATE);
  7887. console.log('version:', VERSION$1);
  7888. const Events = Events$1;
  7889. const Endpoint = RTCEndpoint;
  7890. //连接webrtc
  7891. class ZLMConnect {
  7892. constructor(option) {
  7893. this.token = option.token;
  7894. this.callback = option.callback;
  7895. this.url = option.url;
  7896. this.videoId = option.videoId;
  7897. this.rtcUrl = option.rtcUrl;
  7898. this.successCallback = option.successCallback;
  7899. }
  7900. stateCallBack(eventName, value, desc) {
  7901. let info = {
  7902. type:eventName,
  7903. val: value,
  7904. description:desc
  7905. };
  7906. this.callback(info);
  7907. }
  7908. connect() {
  7909. this.wsOnMessage = this.wsOnMessage.bind(this);
  7910. this.wsOnClose = this.wsOnClose.bind(this);
  7911. this.wsOpen = this.wsOpen.bind(this);
  7912. this.heartBeat = this.heartBeat.bind(this);
  7913. this.startPlay = this.startPlay.bind(this);
  7914. this.ws = new WebSocket(this.url);
  7915. ws = this.ws
  7916. this.ws.binaryType = 'arraybuffer';
  7917. this.ws.onmessage = this.wsOnMessage;
  7918. this.ws.onopen = this.wsOpen;
  7919. this.ws.onclose = this.wsOnClose;
  7920. //this.connectRtc();
  7921. }
  7922. pause() {
  7923. let videoElement = document.getElementById(this.videoId);
  7924. videoElement.pause();
  7925. console.log("webrtc暂停");
  7926. }
  7927. resume() {
  7928. let videoElement = document.getElementById(this.videoId);
  7929. videoElement.play();
  7930. console.log("webrtc继续播放");
  7931. }
  7932. connectRtc() {
  7933. this.player = new Endpoint(
  7934. {
  7935. element: document.getElementById(this.videoId),// video 标签
  7936. debug: true,// 是否打印日志
  7937. zlmsdpUrl:this.rtcUrl,//流地址
  7938. simulcast:false,
  7939. useCamera:false,
  7940. audioEnable:true,
  7941. videoEnable:true,
  7942. recvOnly:true,
  7943. usedatachannel:false,
  7944. successCallback: this.successCallback
  7945. });
  7946. this.player.on(Events.WEBRTC_ON_REMOTE_STREAMS,function(e)
  7947. {//获取到了远端流,可以播放
  7948. console.log('播放成功',e.streams);
  7949. });
  7950. this.player.on(Events.WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED,function(e)
  7951. {// offer anwser 交换失败
  7952. console.log('offer anwser 交换失败',e);
  7953. stop();
  7954. });
  7955. this.player.on(Events.WEBRTC_ON_CONNECTION_STATE_CHANGE,function(state)
  7956. {// RTC 状态变化 ,详情参考 https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/connectionState
  7957. console.log('当前状态==>',state);
  7958. });
  7959. this.player.on(Events.WEBRTC_ON_DATA_CHANNEL_OPEN,function(event)
  7960. {
  7961. console.log('rtc datachannel 打开 :',event);
  7962. });
  7963. this.player.on(Events.WEBRTC_ON_DATA_CHANNEL_MSG,function(event)
  7964. {
  7965. console.log('rtc datachannel 消息 :',event.data);
  7966. document.getElementById('msgrecv').value = event.data;
  7967. });
  7968. this.player.on(Events.WEBRTC_ON_DATA_CHANNEL_ERR,function(event)
  7969. {
  7970. console.log('rtc datachannel 错误 :',event);
  7971. });
  7972. this.player.on(Events.WEBRTC_ON_DATA_CHANNEL_CLOSE,function(event)
  7973. {
  7974. console.log('rtc datachannel 关闭 :',event);
  7975. });
  7976. let videoElement = document.getElementById(this.videoId);
  7977. videoElement.onplay = this.startPlay;
  7978. }
  7979. startPlay() {
  7980. this.stateCallBack("open", OPEN_SUCCESS, "拉流成功");
  7981. }
  7982. wsOnMessage(event) {
  7983. this.parseProto(event.data);
  7984. }
  7985. switchShapness(level) {
  7986. this.ws.send(makeSharpness(level));
  7987. }
  7988. parseProto (data) {
  7989. let input = new Uint8Array(data);
  7990. if(input[0] == Porto_Header_ID) {
  7991. if(input[23] == MultiLogin_ID) ;
  7992. if(input[23] == Authen_ID) {
  7993. if(CheckVerifyCode(input)) {
  7994. this.connectRtc();
  7995. }
  7996. else {
  7997. console.log("鉴权失败:" + input);
  7998. this.stateCallBack("verifyFailed", verify_Failed, "鉴权失败");
  7999. }
  8000. }
  8001. if(input[23] == ScreenDirection_ID) {
  8002. let direction = CheckScreenDirection(input.slice(24, 24 + 8));
  8003. if(direction == Vertica_ID) {
  8004. this.stateCallBack("screenChange", direction, "安卓卡竖屏");
  8005. }
  8006. if(direction == Landscape_ID) {
  8007. this.stateCallBack("screenChange", direction, "安卓卡横屏");
  8008. }
  8009. }
  8010. }
  8011. }
  8012. heartBeat() {
  8013. this.ws.send("ping");
  8014. }
  8015. wsOpen(event) {
  8016. let sn = "RK3923C1201900139";
  8017. let verifyBuffer = VerifyCode(sn, this.token);
  8018. this.ws.send(verifyBuffer);
  8019. let fps = setFps(20)
  8020. this.ws.send(fps)
  8021. this.heartBeatFlag = setInterval(this.heartBeat, 2000);
  8022. heartBeatFlag = this.heartBeatFlag
  8023. }
  8024. wsOnClose(event) {
  8025. this.stateCallBack("closeEvent", event.code, "WS关闭事件");
  8026. }
  8027. disconnect() {
  8028. if(this.player) {
  8029. this.player.close();
  8030. this.player = null;
  8031. }
  8032. clearInterval(this.heartBeatFlag);
  8033. this.ws.close();
  8034. let videoElement = document.getElementById(this.videoId);
  8035. videoElement.srcObject = null;
  8036. videoElement.load();
  8037. }
  8038. }
  8039. class RtcEngine {
  8040. constructor(options) {
  8041. this.callback = options.callback;
  8042. this.url = options.url;
  8043. this.token = options.token;
  8044. this.videoId = options.videoId;
  8045. this.rtcUrl = options.rtcUrl;
  8046. this.mode = options.mode;
  8047. this.debug = options.debug;
  8048. this.successCallback = options.successCallback;
  8049. }
  8050. checkSupportLevel() {
  8051. let isWebrtcSupported = DetectRTC.isWebRTCSupported;
  8052. let isMseSupported = !!window.MediaSource;
  8053. let isWasmSupported = false;
  8054. if(isWebrtcSupported) {
  8055. console.log("支持webrtc--yes");
  8056. }
  8057. if(isMseSupported) {
  8058. console.log("支持MSE--yes");
  8059. }
  8060. return {
  8061. webrtcSupported:isWebrtcSupported,
  8062. mseSupported:isMseSupported,
  8063. webCodecSupported:isMseSupported,
  8064. wasmSupported:isWasmSupported
  8065. }
  8066. }
  8067. getMode() {
  8068. return this.mode;
  8069. }
  8070. switchShapness(level) {
  8071. if(this.connector != undefined) {
  8072. this.connector.switchShapness(level);
  8073. }
  8074. }
  8075. //优先级webrtc > webcodec > mse > wasm
  8076. checkAndConnect() {
  8077. let supportLevel = this.checkSupportLevel();
  8078. if(supportLevel.webrtcSupported) {
  8079. this.connector = new ZLMConnect(this.rtcOption);
  8080. this.mode = "webrtc";
  8081. }
  8082. else
  8083. if(supportLevel.mseSupported) {
  8084. this.connector = new MseConnect(this.rtcOption);
  8085. this.mode = "mse";
  8086. }
  8087. else
  8088. if(supportLevel.webCodecSupported) {
  8089. this.mode = "webcodec";
  8090. console.log("暂时不支持webcodec");
  8091. }
  8092. else
  8093. if(supportLevel.wasmSupported) {
  8094. this.mode = "wasm";
  8095. console.log("暂时不支持wasm");
  8096. }
  8097. if(this.connector != undefined)
  8098. this.connector.connect();
  8099. }
  8100. connect() {
  8101. this.rtcOption = {
  8102. url:this.url,
  8103. token:this.token,
  8104. videoId:this.videoId,
  8105. callback:this.callback,
  8106. rtcUrl:this.rtcUrl,
  8107. debug:this.debug,
  8108. successCallback: this.successCallback
  8109. };
  8110. if(this.mode != undefined) {
  8111. switch(this.mode) {
  8112. case "mse":this.connector = new MseConnect(this.rtcOption);break;
  8113. case "webrtc":this.connector = new ZLMConnect(this.rtcOption);break;
  8114. default:console.log("暂时不支持的流媒体协议:" + this.mode);break;
  8115. }
  8116. if(this.connector != undefined)
  8117. this.connector.connect();
  8118. }
  8119. else {
  8120. this.checkAndConnect();
  8121. }
  8122. }
  8123. pause() {
  8124. if(this.connector.pause != undefined) {
  8125. this.connector.pause();
  8126. }
  8127. }
  8128. resume() {
  8129. if(this.connector.resume != undefined) {
  8130. this.connector.resume();
  8131. }
  8132. }
  8133. disconnect() {
  8134. this.connector.disconnect();
  8135. }
  8136. }
  8137. return RtcEngine;
  8138. }));