rtcEngine.min.js 267 KB

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