video.js 2.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530
  1. /**
  2. * @license
  3. * Video.js 7.21.4 <http://videojs.com/>
  4. * Copyright Brightcove, Inc. <https://www.brightcove.com/>
  5. * Available under Apache License Version 2.0
  6. * <https://github.com/videojs/video.js/blob/main/LICENSE>
  7. *
  8. * Includes vtt.js <https://github.com/mozilla/vtt.js>
  9. * Available under Apache License Version 2.0
  10. * <https://github.com/mozilla/vtt.js/blob/main/LICENSE>
  11. */
  12. (function (global, factory) {
  13. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  14. typeof define === 'function' && define.amd ? define(factory) :
  15. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.videojs = factory());
  16. }(this, (function () { 'use strict';
  17. var version$5 = "7.21.4";
  18. /**
  19. * An Object that contains lifecycle hooks as keys which point to an array
  20. * of functions that are run when a lifecycle is triggered
  21. *
  22. * @private
  23. */
  24. var hooks_ = {};
  25. /**
  26. * Get a list of hooks for a specific lifecycle
  27. *
  28. * @param {string} type
  29. * the lifecyle to get hooks from
  30. *
  31. * @param {Function|Function[]} [fn]
  32. * Optionally add a hook (or hooks) to the lifecycle that your are getting.
  33. *
  34. * @return {Array}
  35. * an array of hooks, or an empty array if there are none.
  36. */
  37. var hooks = function hooks(type, fn) {
  38. hooks_[type] = hooks_[type] || [];
  39. if (fn) {
  40. hooks_[type] = hooks_[type].concat(fn);
  41. }
  42. return hooks_[type];
  43. };
  44. /**
  45. * Add a function hook to a specific videojs lifecycle.
  46. *
  47. * @param {string} type
  48. * the lifecycle to hook the function to.
  49. *
  50. * @param {Function|Function[]}
  51. * The function or array of functions to attach.
  52. */
  53. var hook = function hook(type, fn) {
  54. hooks(type, fn);
  55. };
  56. /**
  57. * Remove a hook from a specific videojs lifecycle.
  58. *
  59. * @param {string} type
  60. * the lifecycle that the function hooked to
  61. *
  62. * @param {Function} fn
  63. * The hooked function to remove
  64. *
  65. * @return {boolean}
  66. * The function that was removed or undef
  67. */
  68. var removeHook = function removeHook(type, fn) {
  69. var index = hooks(type).indexOf(fn);
  70. if (index <= -1) {
  71. return false;
  72. }
  73. hooks_[type] = hooks_[type].slice();
  74. hooks_[type].splice(index, 1);
  75. return true;
  76. };
  77. /**
  78. * Add a function hook that will only run once to a specific videojs lifecycle.
  79. *
  80. * @param {string} type
  81. * the lifecycle to hook the function to.
  82. *
  83. * @param {Function|Function[]}
  84. * The function or array of functions to attach.
  85. */
  86. var hookOnce = function hookOnce(type, fn) {
  87. hooks(type, [].concat(fn).map(function (original) {
  88. var wrapper = function wrapper() {
  89. removeHook(type, wrapper);
  90. return original.apply(void 0, arguments);
  91. };
  92. return wrapper;
  93. }));
  94. };
  95. /**
  96. * @file fullscreen-api.js
  97. * @module fullscreen-api
  98. * @private
  99. */
  100. /**
  101. * Store the browser-specific methods for the fullscreen API.
  102. *
  103. * @type {Object}
  104. * @see [Specification]{@link https://fullscreen.spec.whatwg.org}
  105. * @see [Map Approach From Screenfull.js]{@link https://github.com/sindresorhus/screenfull.js}
  106. */
  107. var FullscreenApi = {
  108. prefixed: true
  109. }; // browser API methods
  110. var apiMap = [['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror', 'fullscreen'], // WebKit
  111. ['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror', '-webkit-full-screen'], // Mozilla
  112. ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror', '-moz-full-screen'], // Microsoft
  113. ['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError', '-ms-fullscreen']];
  114. var specApi = apiMap[0];
  115. var browserApi; // determine the supported set of functions
  116. for (var i = 0; i < apiMap.length; i++) {
  117. // check for exitFullscreen function
  118. if (apiMap[i][1] in document) {
  119. browserApi = apiMap[i];
  120. break;
  121. }
  122. } // map the browser API names to the spec API names
  123. if (browserApi) {
  124. for (var _i = 0; _i < browserApi.length; _i++) {
  125. FullscreenApi[specApi[_i]] = browserApi[_i];
  126. }
  127. FullscreenApi.prefixed = browserApi[0] !== specApi[0];
  128. }
  129. /**
  130. * @file create-logger.js
  131. * @module create-logger
  132. */
  133. // This is the private tracking variable for the logging history.
  134. var history = [];
  135. /**
  136. * Log messages to the console and history based on the type of message
  137. *
  138. * @private
  139. * @param {string} type
  140. * The name of the console method to use.
  141. *
  142. * @param {Array} args
  143. * The arguments to be passed to the matching console method.
  144. */
  145. var LogByTypeFactory = function LogByTypeFactory(name, log) {
  146. return function (type, level, args) {
  147. var lvl = log.levels[level];
  148. var lvlRegExp = new RegExp("^(" + lvl + ")$");
  149. if (type !== 'log') {
  150. // Add the type to the front of the message when it's not "log".
  151. args.unshift(type.toUpperCase() + ':');
  152. } // Add console prefix after adding to history.
  153. args.unshift(name + ':'); // Add a clone of the args at this point to history.
  154. if (history) {
  155. history.push([].concat(args)); // only store 1000 history entries
  156. var splice = history.length - 1000;
  157. history.splice(0, splice > 0 ? splice : 0);
  158. } // If there's no console then don't try to output messages, but they will
  159. // still be stored in history.
  160. if (!window.console) {
  161. return;
  162. } // Was setting these once outside of this function, but containing them
  163. // in the function makes it easier to test cases where console doesn't exist
  164. // when the module is executed.
  165. var fn = window.console[type];
  166. if (!fn && type === 'debug') {
  167. // Certain browsers don't have support for console.debug. For those, we
  168. // should default to the closest comparable log.
  169. fn = window.console.info || window.console.log;
  170. } // Bail out if there's no console or if this type is not allowed by the
  171. // current logging level.
  172. if (!fn || !lvl || !lvlRegExp.test(type)) {
  173. return;
  174. }
  175. fn[Array.isArray(args) ? 'apply' : 'call'](window.console, args);
  176. };
  177. };
  178. function createLogger$1(name) {
  179. // This is the private tracking variable for logging level.
  180. var level = 'info'; // the curried logByType bound to the specific log and history
  181. var logByType;
  182. /**
  183. * Logs plain debug messages. Similar to `console.log`.
  184. *
  185. * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
  186. * of our JSDoc template, we cannot properly document this as both a function
  187. * and a namespace, so its function signature is documented here.
  188. *
  189. * #### Arguments
  190. * ##### *args
  191. * Mixed[]
  192. *
  193. * Any combination of values that could be passed to `console.log()`.
  194. *
  195. * #### Return Value
  196. *
  197. * `undefined`
  198. *
  199. * @namespace
  200. * @param {Mixed[]} args
  201. * One or more messages or objects that should be logged.
  202. */
  203. var log = function log() {
  204. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  205. args[_key] = arguments[_key];
  206. }
  207. logByType('log', level, args);
  208. }; // This is the logByType helper that the logging methods below use
  209. logByType = LogByTypeFactory(name, log);
  210. /**
  211. * Create a new sublogger which chains the old name to the new name.
  212. *
  213. * For example, doing `videojs.log.createLogger('player')` and then using that logger will log the following:
  214. * ```js
  215. * mylogger('foo');
  216. * // > VIDEOJS: player: foo
  217. * ```
  218. *
  219. * @param {string} name
  220. * The name to add call the new logger
  221. * @return {Object}
  222. */
  223. log.createLogger = function (subname) {
  224. return createLogger$1(name + ': ' + subname);
  225. };
  226. /**
  227. * Enumeration of available logging levels, where the keys are the level names
  228. * and the values are `|`-separated strings containing logging methods allowed
  229. * in that logging level. These strings are used to create a regular expression
  230. * matching the function name being called.
  231. *
  232. * Levels provided by Video.js are:
  233. *
  234. * - `off`: Matches no calls. Any value that can be cast to `false` will have
  235. * this effect. The most restrictive.
  236. * - `all`: Matches only Video.js-provided functions (`debug`, `log`,
  237. * `log.warn`, and `log.error`).
  238. * - `debug`: Matches `log.debug`, `log`, `log.warn`, and `log.error` calls.
  239. * - `info` (default): Matches `log`, `log.warn`, and `log.error` calls.
  240. * - `warn`: Matches `log.warn` and `log.error` calls.
  241. * - `error`: Matches only `log.error` calls.
  242. *
  243. * @type {Object}
  244. */
  245. log.levels = {
  246. all: 'debug|log|warn|error',
  247. off: '',
  248. debug: 'debug|log|warn|error',
  249. info: 'log|warn|error',
  250. warn: 'warn|error',
  251. error: 'error',
  252. DEFAULT: level
  253. };
  254. /**
  255. * Get or set the current logging level.
  256. *
  257. * If a string matching a key from {@link module:log.levels} is provided, acts
  258. * as a setter.
  259. *
  260. * @param {string} [lvl]
  261. * Pass a valid level to set a new logging level.
  262. *
  263. * @return {string}
  264. * The current logging level.
  265. */
  266. log.level = function (lvl) {
  267. if (typeof lvl === 'string') {
  268. if (!log.levels.hasOwnProperty(lvl)) {
  269. throw new Error("\"" + lvl + "\" in not a valid log level");
  270. }
  271. level = lvl;
  272. }
  273. return level;
  274. };
  275. /**
  276. * Returns an array containing everything that has been logged to the history.
  277. *
  278. * This array is a shallow clone of the internal history record. However, its
  279. * contents are _not_ cloned; so, mutating objects inside this array will
  280. * mutate them in history.
  281. *
  282. * @return {Array}
  283. */
  284. log.history = function () {
  285. return history ? [].concat(history) : [];
  286. };
  287. /**
  288. * Allows you to filter the history by the given logger name
  289. *
  290. * @param {string} fname
  291. * The name to filter by
  292. *
  293. * @return {Array}
  294. * The filtered list to return
  295. */
  296. log.history.filter = function (fname) {
  297. return (history || []).filter(function (historyItem) {
  298. // if the first item in each historyItem includes `fname`, then it's a match
  299. return new RegExp(".*" + fname + ".*").test(historyItem[0]);
  300. });
  301. };
  302. /**
  303. * Clears the internal history tracking, but does not prevent further history
  304. * tracking.
  305. */
  306. log.history.clear = function () {
  307. if (history) {
  308. history.length = 0;
  309. }
  310. };
  311. /**
  312. * Disable history tracking if it is currently enabled.
  313. */
  314. log.history.disable = function () {
  315. if (history !== null) {
  316. history.length = 0;
  317. history = null;
  318. }
  319. };
  320. /**
  321. * Enable history tracking if it is currently disabled.
  322. */
  323. log.history.enable = function () {
  324. if (history === null) {
  325. history = [];
  326. }
  327. };
  328. /**
  329. * Logs error messages. Similar to `console.error`.
  330. *
  331. * @param {Mixed[]} args
  332. * One or more messages or objects that should be logged as an error
  333. */
  334. log.error = function () {
  335. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  336. args[_key2] = arguments[_key2];
  337. }
  338. return logByType('error', level, args);
  339. };
  340. /**
  341. * Logs warning messages. Similar to `console.warn`.
  342. *
  343. * @param {Mixed[]} args
  344. * One or more messages or objects that should be logged as a warning.
  345. */
  346. log.warn = function () {
  347. for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
  348. args[_key3] = arguments[_key3];
  349. }
  350. return logByType('warn', level, args);
  351. };
  352. /**
  353. * Logs debug messages. Similar to `console.debug`, but may also act as a comparable
  354. * log if `console.debug` is not available
  355. *
  356. * @param {Mixed[]} args
  357. * One or more messages or objects that should be logged as debug.
  358. */
  359. log.debug = function () {
  360. for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
  361. args[_key4] = arguments[_key4];
  362. }
  363. return logByType('debug', level, args);
  364. };
  365. return log;
  366. }
  367. /**
  368. * @file log.js
  369. * @module log
  370. */
  371. var log$1 = createLogger$1('VIDEOJS');
  372. var createLogger = log$1.createLogger;
  373. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  374. function createCommonjsModule(fn, module) {
  375. return module = { exports: {} }, fn(module, module.exports), module.exports;
  376. }
  377. var _extends_1 = createCommonjsModule(function (module) {
  378. function _extends() {
  379. module.exports = _extends = Object.assign || function (target) {
  380. for (var i = 1; i < arguments.length; i++) {
  381. var source = arguments[i];
  382. for (var key in source) {
  383. if (Object.prototype.hasOwnProperty.call(source, key)) {
  384. target[key] = source[key];
  385. }
  386. }
  387. }
  388. return target;
  389. };
  390. return _extends.apply(this, arguments);
  391. }
  392. module.exports = _extends;
  393. });
  394. /**
  395. * @file obj.js
  396. * @module obj
  397. */
  398. /**
  399. * @callback obj:EachCallback
  400. *
  401. * @param {Mixed} value
  402. * The current key for the object that is being iterated over.
  403. *
  404. * @param {string} key
  405. * The current key-value for object that is being iterated over
  406. */
  407. /**
  408. * @callback obj:ReduceCallback
  409. *
  410. * @param {Mixed} accum
  411. * The value that is accumulating over the reduce loop.
  412. *
  413. * @param {Mixed} value
  414. * The current key for the object that is being iterated over.
  415. *
  416. * @param {string} key
  417. * The current key-value for object that is being iterated over
  418. *
  419. * @return {Mixed}
  420. * The new accumulated value.
  421. */
  422. var toString$1 = Object.prototype.toString;
  423. /**
  424. * Get the keys of an Object
  425. *
  426. * @param {Object}
  427. * The Object to get the keys from
  428. *
  429. * @return {string[]}
  430. * An array of the keys from the object. Returns an empty array if the
  431. * object passed in was invalid or had no keys.
  432. *
  433. * @private
  434. */
  435. var keys = function keys(object) {
  436. return isObject$1(object) ? Object.keys(object) : [];
  437. };
  438. /**
  439. * Array-like iteration for objects.
  440. *
  441. * @param {Object} object
  442. * The object to iterate over
  443. *
  444. * @param {obj:EachCallback} fn
  445. * The callback function which is called for each key in the object.
  446. */
  447. function each(object, fn) {
  448. keys(object).forEach(function (key) {
  449. return fn(object[key], key);
  450. });
  451. }
  452. /**
  453. * Array-like reduce for objects.
  454. *
  455. * @param {Object} object
  456. * The Object that you want to reduce.
  457. *
  458. * @param {Function} fn
  459. * A callback function which is called for each key in the object. It
  460. * receives the accumulated value and the per-iteration value and key
  461. * as arguments.
  462. *
  463. * @param {Mixed} [initial = 0]
  464. * Starting value
  465. *
  466. * @return {Mixed}
  467. * The final accumulated value.
  468. */
  469. function reduce(object, fn, initial) {
  470. if (initial === void 0) {
  471. initial = 0;
  472. }
  473. return keys(object).reduce(function (accum, key) {
  474. return fn(accum, object[key], key);
  475. }, initial);
  476. }
  477. /**
  478. * Object.assign-style object shallow merge/extend.
  479. *
  480. * @param {Object} target
  481. * @param {Object} ...sources
  482. * @return {Object}
  483. */
  484. function assign$1(target) {
  485. for (var _len = arguments.length, sources = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  486. sources[_key - 1] = arguments[_key];
  487. }
  488. if (Object.assign) {
  489. return _extends_1.apply(void 0, [target].concat(sources));
  490. }
  491. sources.forEach(function (source) {
  492. if (!source) {
  493. return;
  494. }
  495. each(source, function (value, key) {
  496. target[key] = value;
  497. });
  498. });
  499. return target;
  500. }
  501. /**
  502. * Returns whether a value is an object of any kind - including DOM nodes,
  503. * arrays, regular expressions, etc. Not functions, though.
  504. *
  505. * This avoids the gotcha where using `typeof` on a `null` value
  506. * results in `'object'`.
  507. *
  508. * @param {Object} value
  509. * @return {boolean}
  510. */
  511. function isObject$1(value) {
  512. return !!value && typeof value === 'object';
  513. }
  514. /**
  515. * Returns whether an object appears to be a "plain" object - that is, a
  516. * direct instance of `Object`.
  517. *
  518. * @param {Object} value
  519. * @return {boolean}
  520. */
  521. function isPlain(value) {
  522. return isObject$1(value) && toString$1.call(value) === '[object Object]' && value.constructor === Object;
  523. }
  524. /**
  525. * @file computed-style.js
  526. * @module computed-style
  527. */
  528. /**
  529. * A safe getComputedStyle.
  530. *
  531. * This is needed because in Firefox, if the player is loaded in an iframe with
  532. * `display:none`, then `getComputedStyle` returns `null`, so, we do a
  533. * null-check to make sure that the player doesn't break in these cases.
  534. *
  535. * @function
  536. * @param {Element} el
  537. * The element you want the computed style of
  538. *
  539. * @param {string} prop
  540. * The property name you want
  541. *
  542. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  543. */
  544. function computedStyle(el, prop) {
  545. if (!el || !prop) {
  546. return '';
  547. }
  548. if (typeof window.getComputedStyle === 'function') {
  549. var computedStyleValue;
  550. try {
  551. computedStyleValue = window.getComputedStyle(el);
  552. } catch (e) {
  553. return '';
  554. }
  555. return computedStyleValue ? computedStyleValue.getPropertyValue(prop) || computedStyleValue[prop] : '';
  556. }
  557. return '';
  558. }
  559. /**
  560. * @file browser.js
  561. * @module browser
  562. */
  563. var USER_AGENT = window.navigator && window.navigator.userAgent || '';
  564. var webkitVersionMap = /AppleWebKit\/([\d.]+)/i.exec(USER_AGENT);
  565. var appleWebkitVersion = webkitVersionMap ? parseFloat(webkitVersionMap.pop()) : null;
  566. /**
  567. * Whether or not this device is an iPod.
  568. *
  569. * @static
  570. * @const
  571. * @type {Boolean}
  572. */
  573. var IS_IPOD = /iPod/i.test(USER_AGENT);
  574. /**
  575. * The detected iOS version - or `null`.
  576. *
  577. * @static
  578. * @const
  579. * @type {string|null}
  580. */
  581. var IOS_VERSION = function () {
  582. var match = USER_AGENT.match(/OS (\d+)_/i);
  583. if (match && match[1]) {
  584. return match[1];
  585. }
  586. return null;
  587. }();
  588. /**
  589. * Whether or not this is an Android device.
  590. *
  591. * @static
  592. * @const
  593. * @type {Boolean}
  594. */
  595. var IS_ANDROID = /Android/i.test(USER_AGENT);
  596. /**
  597. * The detected Android version - or `null`.
  598. *
  599. * @static
  600. * @const
  601. * @type {number|string|null}
  602. */
  603. var ANDROID_VERSION = function () {
  604. // This matches Android Major.Minor.Patch versions
  605. // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned
  606. var match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);
  607. if (!match) {
  608. return null;
  609. }
  610. var major = match[1] && parseFloat(match[1]);
  611. var minor = match[2] && parseFloat(match[2]);
  612. if (major && minor) {
  613. return parseFloat(match[1] + '.' + match[2]);
  614. } else if (major) {
  615. return major;
  616. }
  617. return null;
  618. }();
  619. /**
  620. * Whether or not this is a native Android browser.
  621. *
  622. * @static
  623. * @const
  624. * @type {Boolean}
  625. */
  626. var IS_NATIVE_ANDROID = IS_ANDROID && ANDROID_VERSION < 5 && appleWebkitVersion < 537;
  627. /**
  628. * Whether or not this is Mozilla Firefox.
  629. *
  630. * @static
  631. * @const
  632. * @type {Boolean}
  633. */
  634. var IS_FIREFOX = /Firefox/i.test(USER_AGENT);
  635. /**
  636. * Whether or not this is Microsoft Edge.
  637. *
  638. * @static
  639. * @const
  640. * @type {Boolean}
  641. */
  642. var IS_EDGE = /Edg/i.test(USER_AGENT);
  643. /**
  644. * Whether or not this is Google Chrome.
  645. *
  646. * This will also be `true` for Chrome on iOS, which will have different support
  647. * as it is actually Safari under the hood.
  648. *
  649. * @static
  650. * @const
  651. * @type {Boolean}
  652. */
  653. var IS_CHROME = !IS_EDGE && (/Chrome/i.test(USER_AGENT) || /CriOS/i.test(USER_AGENT));
  654. /**
  655. * The detected Google Chrome version - or `null`.
  656. *
  657. * @static
  658. * @const
  659. * @type {number|null}
  660. */
  661. var CHROME_VERSION = function () {
  662. var match = USER_AGENT.match(/(Chrome|CriOS)\/(\d+)/);
  663. if (match && match[2]) {
  664. return parseFloat(match[2]);
  665. }
  666. return null;
  667. }();
  668. /**
  669. * The detected Internet Explorer version - or `null`.
  670. *
  671. * @static
  672. * @const
  673. * @type {number|null}
  674. */
  675. var IE_VERSION = function () {
  676. var result = /MSIE\s(\d+)\.\d/.exec(USER_AGENT);
  677. var version = result && parseFloat(result[1]);
  678. if (!version && /Trident\/7.0/i.test(USER_AGENT) && /rv:11.0/.test(USER_AGENT)) {
  679. // IE 11 has a different user agent string than other IE versions
  680. version = 11.0;
  681. }
  682. return version;
  683. }();
  684. /**
  685. * Whether or not this is desktop Safari.
  686. *
  687. * @static
  688. * @const
  689. * @type {Boolean}
  690. */
  691. var IS_SAFARI = /Safari/i.test(USER_AGENT) && !IS_CHROME && !IS_ANDROID && !IS_EDGE;
  692. /**
  693. * Whether or not this is a Windows machine.
  694. *
  695. * @static
  696. * @const
  697. * @type {Boolean}
  698. */
  699. var IS_WINDOWS = /Windows/i.test(USER_AGENT);
  700. /**
  701. * Whether or not this device is touch-enabled.
  702. *
  703. * @static
  704. * @const
  705. * @type {Boolean}
  706. */
  707. var TOUCH_ENABLED = Boolean(isReal() && ('ontouchstart' in window || window.navigator.maxTouchPoints || window.DocumentTouch && window.document instanceof window.DocumentTouch));
  708. /**
  709. * Whether or not this device is an iPad.
  710. *
  711. * @static
  712. * @const
  713. * @type {Boolean}
  714. */
  715. var IS_IPAD = /iPad/i.test(USER_AGENT) || IS_SAFARI && TOUCH_ENABLED && !/iPhone/i.test(USER_AGENT);
  716. /**
  717. * Whether or not this device is an iPhone.
  718. *
  719. * @static
  720. * @const
  721. * @type {Boolean}
  722. */
  723. // The Facebook app's UIWebView identifies as both an iPhone and iPad, so
  724. // to identify iPhones, we need to exclude iPads.
  725. // http://artsy.github.io/blog/2012/10/18/the-perils-of-ios-user-agent-sniffing/
  726. var IS_IPHONE = /iPhone/i.test(USER_AGENT) && !IS_IPAD;
  727. /**
  728. * Whether or not this is an iOS device.
  729. *
  730. * @static
  731. * @const
  732. * @type {Boolean}
  733. */
  734. var IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD;
  735. /**
  736. * Whether or not this is any flavor of Safari - including iOS.
  737. *
  738. * @static
  739. * @const
  740. * @type {Boolean}
  741. */
  742. var IS_ANY_SAFARI = (IS_SAFARI || IS_IOS) && !IS_CHROME;
  743. var browser = /*#__PURE__*/Object.freeze({
  744. __proto__: null,
  745. IS_IPOD: IS_IPOD,
  746. IOS_VERSION: IOS_VERSION,
  747. IS_ANDROID: IS_ANDROID,
  748. ANDROID_VERSION: ANDROID_VERSION,
  749. IS_NATIVE_ANDROID: IS_NATIVE_ANDROID,
  750. IS_FIREFOX: IS_FIREFOX,
  751. IS_EDGE: IS_EDGE,
  752. IS_CHROME: IS_CHROME,
  753. CHROME_VERSION: CHROME_VERSION,
  754. IE_VERSION: IE_VERSION,
  755. IS_SAFARI: IS_SAFARI,
  756. IS_WINDOWS: IS_WINDOWS,
  757. TOUCH_ENABLED: TOUCH_ENABLED,
  758. IS_IPAD: IS_IPAD,
  759. IS_IPHONE: IS_IPHONE,
  760. IS_IOS: IS_IOS,
  761. IS_ANY_SAFARI: IS_ANY_SAFARI
  762. });
  763. /**
  764. * @file dom.js
  765. * @module dom
  766. */
  767. /**
  768. * Detect if a value is a string with any non-whitespace characters.
  769. *
  770. * @private
  771. * @param {string} str
  772. * The string to check
  773. *
  774. * @return {boolean}
  775. * Will be `true` if the string is non-blank, `false` otherwise.
  776. *
  777. */
  778. function isNonBlankString(str) {
  779. // we use str.trim as it will trim any whitespace characters
  780. // from the front or back of non-whitespace characters. aka
  781. // Any string that contains non-whitespace characters will
  782. // still contain them after `trim` but whitespace only strings
  783. // will have a length of 0, failing this check.
  784. return typeof str === 'string' && Boolean(str.trim());
  785. }
  786. /**
  787. * Throws an error if the passed string has whitespace. This is used by
  788. * class methods to be relatively consistent with the classList API.
  789. *
  790. * @private
  791. * @param {string} str
  792. * The string to check for whitespace.
  793. *
  794. * @throws {Error}
  795. * Throws an error if there is whitespace in the string.
  796. */
  797. function throwIfWhitespace(str) {
  798. // str.indexOf instead of regex because str.indexOf is faster performance wise.
  799. if (str.indexOf(' ') >= 0) {
  800. throw new Error('class has illegal whitespace characters');
  801. }
  802. }
  803. /**
  804. * Produce a regular expression for matching a className within an elements className.
  805. *
  806. * @private
  807. * @param {string} className
  808. * The className to generate the RegExp for.
  809. *
  810. * @return {RegExp}
  811. * The RegExp that will check for a specific `className` in an elements
  812. * className.
  813. */
  814. function classRegExp(className) {
  815. return new RegExp('(^|\\s)' + className + '($|\\s)');
  816. }
  817. /**
  818. * Whether the current DOM interface appears to be real (i.e. not simulated).
  819. *
  820. * @return {boolean}
  821. * Will be `true` if the DOM appears to be real, `false` otherwise.
  822. */
  823. function isReal() {
  824. // Both document and window will never be undefined thanks to `global`.
  825. return document === window.document;
  826. }
  827. /**
  828. * Determines, via duck typing, whether or not a value is a DOM element.
  829. *
  830. * @param {Mixed} value
  831. * The value to check.
  832. *
  833. * @return {boolean}
  834. * Will be `true` if the value is a DOM element, `false` otherwise.
  835. */
  836. function isEl(value) {
  837. return isObject$1(value) && value.nodeType === 1;
  838. }
  839. /**
  840. * Determines if the current DOM is embedded in an iframe.
  841. *
  842. * @return {boolean}
  843. * Will be `true` if the DOM is embedded in an iframe, `false`
  844. * otherwise.
  845. */
  846. function isInFrame() {
  847. // We need a try/catch here because Safari will throw errors when attempting
  848. // to get either `parent` or `self`
  849. try {
  850. return window.parent !== window.self;
  851. } catch (x) {
  852. return true;
  853. }
  854. }
  855. /**
  856. * Creates functions to query the DOM using a given method.
  857. *
  858. * @private
  859. * @param {string} method
  860. * The method to create the query with.
  861. *
  862. * @return {Function}
  863. * The query method
  864. */
  865. function createQuerier(method) {
  866. return function (selector, context) {
  867. if (!isNonBlankString(selector)) {
  868. return document[method](null);
  869. }
  870. if (isNonBlankString(context)) {
  871. context = document.querySelector(context);
  872. }
  873. var ctx = isEl(context) ? context : document;
  874. return ctx[method] && ctx[method](selector);
  875. };
  876. }
  877. /**
  878. * Creates an element and applies properties, attributes, and inserts content.
  879. *
  880. * @param {string} [tagName='div']
  881. * Name of tag to be created.
  882. *
  883. * @param {Object} [properties={}]
  884. * Element properties to be applied.
  885. *
  886. * @param {Object} [attributes={}]
  887. * Element attributes to be applied.
  888. *
  889. * @param {module:dom~ContentDescriptor} content
  890. * A content descriptor object.
  891. *
  892. * @return {Element}
  893. * The element that was created.
  894. */
  895. function createEl(tagName, properties, attributes, content) {
  896. if (tagName === void 0) {
  897. tagName = 'div';
  898. }
  899. if (properties === void 0) {
  900. properties = {};
  901. }
  902. if (attributes === void 0) {
  903. attributes = {};
  904. }
  905. var el = document.createElement(tagName);
  906. Object.getOwnPropertyNames(properties).forEach(function (propName) {
  907. var val = properties[propName]; // See #2176
  908. // We originally were accepting both properties and attributes in the
  909. // same object, but that doesn't work so well.
  910. if (propName.indexOf('aria-') !== -1 || propName === 'role' || propName === 'type') {
  911. log$1.warn('Setting attributes in the second argument of createEl()\n' + 'has been deprecated. Use the third argument instead.\n' + ("createEl(type, properties, attributes). Attempting to set " + propName + " to " + val + "."));
  912. el.setAttribute(propName, val); // Handle textContent since it's not supported everywhere and we have a
  913. // method for it.
  914. } else if (propName === 'textContent') {
  915. textContent(el, val);
  916. } else if (el[propName] !== val || propName === 'tabIndex') {
  917. el[propName] = val;
  918. }
  919. });
  920. Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
  921. el.setAttribute(attrName, attributes[attrName]);
  922. });
  923. if (content) {
  924. appendContent(el, content);
  925. }
  926. return el;
  927. }
  928. /**
  929. * Injects text into an element, replacing any existing contents entirely.
  930. *
  931. * @param {Element} el
  932. * The element to add text content into
  933. *
  934. * @param {string} text
  935. * The text content to add.
  936. *
  937. * @return {Element}
  938. * The element with added text content.
  939. */
  940. function textContent(el, text) {
  941. if (typeof el.textContent === 'undefined') {
  942. el.innerText = text;
  943. } else {
  944. el.textContent = text;
  945. }
  946. return el;
  947. }
  948. /**
  949. * Insert an element as the first child node of another
  950. *
  951. * @param {Element} child
  952. * Element to insert
  953. *
  954. * @param {Element} parent
  955. * Element to insert child into
  956. */
  957. function prependTo(child, parent) {
  958. if (parent.firstChild) {
  959. parent.insertBefore(child, parent.firstChild);
  960. } else {
  961. parent.appendChild(child);
  962. }
  963. }
  964. /**
  965. * Check if an element has a class name.
  966. *
  967. * @param {Element} element
  968. * Element to check
  969. *
  970. * @param {string} classToCheck
  971. * Class name to check for
  972. *
  973. * @return {boolean}
  974. * Will be `true` if the element has a class, `false` otherwise.
  975. *
  976. * @throws {Error}
  977. * Throws an error if `classToCheck` has white space.
  978. */
  979. function hasClass(element, classToCheck) {
  980. throwIfWhitespace(classToCheck);
  981. if (element.classList) {
  982. return element.classList.contains(classToCheck);
  983. }
  984. return classRegExp(classToCheck).test(element.className);
  985. }
  986. /**
  987. * Add a class name to an element.
  988. *
  989. * @param {Element} element
  990. * Element to add class name to.
  991. *
  992. * @param {string} classToAdd
  993. * Class name to add.
  994. *
  995. * @return {Element}
  996. * The DOM element with the added class name.
  997. */
  998. function addClass(element, classToAdd) {
  999. if (element.classList) {
  1000. element.classList.add(classToAdd); // Don't need to `throwIfWhitespace` here because `hasElClass` will do it
  1001. // in the case of classList not being supported.
  1002. } else if (!hasClass(element, classToAdd)) {
  1003. element.className = (element.className + ' ' + classToAdd).trim();
  1004. }
  1005. return element;
  1006. }
  1007. /**
  1008. * Remove a class name from an element.
  1009. *
  1010. * @param {Element} element
  1011. * Element to remove a class name from.
  1012. *
  1013. * @param {string} classToRemove
  1014. * Class name to remove
  1015. *
  1016. * @return {Element}
  1017. * The DOM element with class name removed.
  1018. */
  1019. function removeClass(element, classToRemove) {
  1020. // Protect in case the player gets disposed
  1021. if (!element) {
  1022. log$1.warn("removeClass was called with an element that doesn't exist");
  1023. return null;
  1024. }
  1025. if (element.classList) {
  1026. element.classList.remove(classToRemove);
  1027. } else {
  1028. throwIfWhitespace(classToRemove);
  1029. element.className = element.className.split(/\s+/).filter(function (c) {
  1030. return c !== classToRemove;
  1031. }).join(' ');
  1032. }
  1033. return element;
  1034. }
  1035. /**
  1036. * The callback definition for toggleClass.
  1037. *
  1038. * @callback module:dom~PredicateCallback
  1039. * @param {Element} element
  1040. * The DOM element of the Component.
  1041. *
  1042. * @param {string} classToToggle
  1043. * The `className` that wants to be toggled
  1044. *
  1045. * @return {boolean|undefined}
  1046. * If `true` is returned, the `classToToggle` will be added to the
  1047. * `element`. If `false`, the `classToToggle` will be removed from
  1048. * the `element`. If `undefined`, the callback will be ignored.
  1049. */
  1050. /**
  1051. * Adds or removes a class name to/from an element depending on an optional
  1052. * condition or the presence/absence of the class name.
  1053. *
  1054. * @param {Element} element
  1055. * The element to toggle a class name on.
  1056. *
  1057. * @param {string} classToToggle
  1058. * The class that should be toggled.
  1059. *
  1060. * @param {boolean|module:dom~PredicateCallback} [predicate]
  1061. * See the return value for {@link module:dom~PredicateCallback}
  1062. *
  1063. * @return {Element}
  1064. * The element with a class that has been toggled.
  1065. */
  1066. function toggleClass(element, classToToggle, predicate) {
  1067. // This CANNOT use `classList` internally because IE11 does not support the
  1068. // second parameter to the `classList.toggle()` method! Which is fine because
  1069. // `classList` will be used by the add/remove functions.
  1070. var has = hasClass(element, classToToggle);
  1071. if (typeof predicate === 'function') {
  1072. predicate = predicate(element, classToToggle);
  1073. }
  1074. if (typeof predicate !== 'boolean') {
  1075. predicate = !has;
  1076. } // If the necessary class operation matches the current state of the
  1077. // element, no action is required.
  1078. if (predicate === has) {
  1079. return;
  1080. }
  1081. if (predicate) {
  1082. addClass(element, classToToggle);
  1083. } else {
  1084. removeClass(element, classToToggle);
  1085. }
  1086. return element;
  1087. }
  1088. /**
  1089. * Apply attributes to an HTML element.
  1090. *
  1091. * @param {Element} el
  1092. * Element to add attributes to.
  1093. *
  1094. * @param {Object} [attributes]
  1095. * Attributes to be applied.
  1096. */
  1097. function setAttributes(el, attributes) {
  1098. Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
  1099. var attrValue = attributes[attrName];
  1100. if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) {
  1101. el.removeAttribute(attrName);
  1102. } else {
  1103. el.setAttribute(attrName, attrValue === true ? '' : attrValue);
  1104. }
  1105. });
  1106. }
  1107. /**
  1108. * Get an element's attribute values, as defined on the HTML tag.
  1109. *
  1110. * Attributes are not the same as properties. They're defined on the tag
  1111. * or with setAttribute.
  1112. *
  1113. * @param {Element} tag
  1114. * Element from which to get tag attributes.
  1115. *
  1116. * @return {Object}
  1117. * All attributes of the element. Boolean attributes will be `true` or
  1118. * `false`, others will be strings.
  1119. */
  1120. function getAttributes(tag) {
  1121. var obj = {}; // known boolean attributes
  1122. // we can check for matching boolean properties, but not all browsers
  1123. // and not all tags know about these attributes, so, we still want to check them manually
  1124. var knownBooleans = ',' + 'autoplay,controls,playsinline,loop,muted,default,defaultMuted' + ',';
  1125. if (tag && tag.attributes && tag.attributes.length > 0) {
  1126. var attrs = tag.attributes;
  1127. for (var i = attrs.length - 1; i >= 0; i--) {
  1128. var attrName = attrs[i].name;
  1129. var attrVal = attrs[i].value; // check for known booleans
  1130. // the matching element property will return a value for typeof
  1131. if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(',' + attrName + ',') !== -1) {
  1132. // the value of an included boolean attribute is typically an empty
  1133. // string ('') which would equal false if we just check for a false value.
  1134. // we also don't want support bad code like autoplay='false'
  1135. attrVal = attrVal !== null ? true : false;
  1136. }
  1137. obj[attrName] = attrVal;
  1138. }
  1139. }
  1140. return obj;
  1141. }
  1142. /**
  1143. * Get the value of an element's attribute.
  1144. *
  1145. * @param {Element} el
  1146. * A DOM element.
  1147. *
  1148. * @param {string} attribute
  1149. * Attribute to get the value of.
  1150. *
  1151. * @return {string}
  1152. * The value of the attribute.
  1153. */
  1154. function getAttribute(el, attribute) {
  1155. return el.getAttribute(attribute);
  1156. }
  1157. /**
  1158. * Set the value of an element's attribute.
  1159. *
  1160. * @param {Element} el
  1161. * A DOM element.
  1162. *
  1163. * @param {string} attribute
  1164. * Attribute to set.
  1165. *
  1166. * @param {string} value
  1167. * Value to set the attribute to.
  1168. */
  1169. function setAttribute(el, attribute, value) {
  1170. el.setAttribute(attribute, value);
  1171. }
  1172. /**
  1173. * Remove an element's attribute.
  1174. *
  1175. * @param {Element} el
  1176. * A DOM element.
  1177. *
  1178. * @param {string} attribute
  1179. * Attribute to remove.
  1180. */
  1181. function removeAttribute(el, attribute) {
  1182. el.removeAttribute(attribute);
  1183. }
  1184. /**
  1185. * Attempt to block the ability to select text.
  1186. */
  1187. function blockTextSelection() {
  1188. document.body.focus();
  1189. document.onselectstart = function () {
  1190. return false;
  1191. };
  1192. }
  1193. /**
  1194. * Turn off text selection blocking.
  1195. */
  1196. function unblockTextSelection() {
  1197. document.onselectstart = function () {
  1198. return true;
  1199. };
  1200. }
  1201. /**
  1202. * Identical to the native `getBoundingClientRect` function, but ensures that
  1203. * the method is supported at all (it is in all browsers we claim to support)
  1204. * and that the element is in the DOM before continuing.
  1205. *
  1206. * This wrapper function also shims properties which are not provided by some
  1207. * older browsers (namely, IE8).
  1208. *
  1209. * Additionally, some browsers do not support adding properties to a
  1210. * `ClientRect`/`DOMRect` object; so, we shallow-copy it with the standard
  1211. * properties (except `x` and `y` which are not widely supported). This helps
  1212. * avoid implementations where keys are non-enumerable.
  1213. *
  1214. * @param {Element} el
  1215. * Element whose `ClientRect` we want to calculate.
  1216. *
  1217. * @return {Object|undefined}
  1218. * Always returns a plain object - or `undefined` if it cannot.
  1219. */
  1220. function getBoundingClientRect(el) {
  1221. if (el && el.getBoundingClientRect && el.parentNode) {
  1222. var rect = el.getBoundingClientRect();
  1223. var result = {};
  1224. ['bottom', 'height', 'left', 'right', 'top', 'width'].forEach(function (k) {
  1225. if (rect[k] !== undefined) {
  1226. result[k] = rect[k];
  1227. }
  1228. });
  1229. if (!result.height) {
  1230. result.height = parseFloat(computedStyle(el, 'height'));
  1231. }
  1232. if (!result.width) {
  1233. result.width = parseFloat(computedStyle(el, 'width'));
  1234. }
  1235. return result;
  1236. }
  1237. }
  1238. /**
  1239. * Represents the position of a DOM element on the page.
  1240. *
  1241. * @typedef {Object} module:dom~Position
  1242. *
  1243. * @property {number} left
  1244. * Pixels to the left.
  1245. *
  1246. * @property {number} top
  1247. * Pixels from the top.
  1248. */
  1249. /**
  1250. * Get the position of an element in the DOM.
  1251. *
  1252. * Uses `getBoundingClientRect` technique from John Resig.
  1253. *
  1254. * @see http://ejohn.org/blog/getboundingclientrect-is-awesome/
  1255. *
  1256. * @param {Element} el
  1257. * Element from which to get offset.
  1258. *
  1259. * @return {module:dom~Position}
  1260. * The position of the element that was passed in.
  1261. */
  1262. function findPosition(el) {
  1263. if (!el || el && !el.offsetParent) {
  1264. return {
  1265. left: 0,
  1266. top: 0,
  1267. width: 0,
  1268. height: 0
  1269. };
  1270. }
  1271. var width = el.offsetWidth;
  1272. var height = el.offsetHeight;
  1273. var left = 0;
  1274. var top = 0;
  1275. while (el.offsetParent && el !== document[FullscreenApi.fullscreenElement]) {
  1276. left += el.offsetLeft;
  1277. top += el.offsetTop;
  1278. el = el.offsetParent;
  1279. }
  1280. return {
  1281. left: left,
  1282. top: top,
  1283. width: width,
  1284. height: height
  1285. };
  1286. }
  1287. /**
  1288. * Represents x and y coordinates for a DOM element or mouse pointer.
  1289. *
  1290. * @typedef {Object} module:dom~Coordinates
  1291. *
  1292. * @property {number} x
  1293. * x coordinate in pixels
  1294. *
  1295. * @property {number} y
  1296. * y coordinate in pixels
  1297. */
  1298. /**
  1299. * Get the pointer position within an element.
  1300. *
  1301. * The base on the coordinates are the bottom left of the element.
  1302. *
  1303. * @param {Element} el
  1304. * Element on which to get the pointer position on.
  1305. *
  1306. * @param {EventTarget~Event} event
  1307. * Event object.
  1308. *
  1309. * @return {module:dom~Coordinates}
  1310. * A coordinates object corresponding to the mouse position.
  1311. *
  1312. */
  1313. function getPointerPosition(el, event) {
  1314. var translated = {
  1315. x: 0,
  1316. y: 0
  1317. };
  1318. if (IS_IOS) {
  1319. var item = el;
  1320. while (item && item.nodeName.toLowerCase() !== 'html') {
  1321. var transform = computedStyle(item, 'transform');
  1322. if (/^matrix/.test(transform)) {
  1323. var values = transform.slice(7, -1).split(/,\s/).map(Number);
  1324. translated.x += values[4];
  1325. translated.y += values[5];
  1326. } else if (/^matrix3d/.test(transform)) {
  1327. var _values = transform.slice(9, -1).split(/,\s/).map(Number);
  1328. translated.x += _values[12];
  1329. translated.y += _values[13];
  1330. }
  1331. item = item.parentNode;
  1332. }
  1333. }
  1334. var position = {};
  1335. var boxTarget = findPosition(event.target);
  1336. var box = findPosition(el);
  1337. var boxW = box.width;
  1338. var boxH = box.height;
  1339. var offsetY = event.offsetY - (box.top - boxTarget.top);
  1340. var offsetX = event.offsetX - (box.left - boxTarget.left);
  1341. if (event.changedTouches) {
  1342. offsetX = event.changedTouches[0].pageX - box.left;
  1343. offsetY = event.changedTouches[0].pageY + box.top;
  1344. if (IS_IOS) {
  1345. offsetX -= translated.x;
  1346. offsetY -= translated.y;
  1347. }
  1348. }
  1349. position.y = 1 - Math.max(0, Math.min(1, offsetY / boxH));
  1350. position.x = Math.max(0, Math.min(1, offsetX / boxW));
  1351. return position;
  1352. }
  1353. /**
  1354. * Determines, via duck typing, whether or not a value is a text node.
  1355. *
  1356. * @param {Mixed} value
  1357. * Check if this value is a text node.
  1358. *
  1359. * @return {boolean}
  1360. * Will be `true` if the value is a text node, `false` otherwise.
  1361. */
  1362. function isTextNode$1(value) {
  1363. return isObject$1(value) && value.nodeType === 3;
  1364. }
  1365. /**
  1366. * Empties the contents of an element.
  1367. *
  1368. * @param {Element} el
  1369. * The element to empty children from
  1370. *
  1371. * @return {Element}
  1372. * The element with no children
  1373. */
  1374. function emptyEl(el) {
  1375. while (el.firstChild) {
  1376. el.removeChild(el.firstChild);
  1377. }
  1378. return el;
  1379. }
  1380. /**
  1381. * This is a mixed value that describes content to be injected into the DOM
  1382. * via some method. It can be of the following types:
  1383. *
  1384. * Type | Description
  1385. * -----------|-------------
  1386. * `string` | The value will be normalized into a text node.
  1387. * `Element` | The value will be accepted as-is.
  1388. * `TextNode` | The value will be accepted as-is.
  1389. * `Array` | A one-dimensional array of strings, elements, text nodes, or functions. These functions should return a string, element, or text node (any other return value, like an array, will be ignored).
  1390. * `Function` | A function, which is expected to return a string, element, text node, or array - any of the other possible values described above. This means that a content descriptor could be a function that returns an array of functions, but those second-level functions must return strings, elements, or text nodes.
  1391. *
  1392. * @typedef {string|Element|TextNode|Array|Function} module:dom~ContentDescriptor
  1393. */
  1394. /**
  1395. * Normalizes content for eventual insertion into the DOM.
  1396. *
  1397. * This allows a wide range of content definition methods, but helps protect
  1398. * from falling into the trap of simply writing to `innerHTML`, which could
  1399. * be an XSS concern.
  1400. *
  1401. * The content for an element can be passed in multiple types and
  1402. * combinations, whose behavior is as follows:
  1403. *
  1404. * @param {module:dom~ContentDescriptor} content
  1405. * A content descriptor value.
  1406. *
  1407. * @return {Array}
  1408. * All of the content that was passed in, normalized to an array of
  1409. * elements or text nodes.
  1410. */
  1411. function normalizeContent(content) {
  1412. // First, invoke content if it is a function. If it produces an array,
  1413. // that needs to happen before normalization.
  1414. if (typeof content === 'function') {
  1415. content = content();
  1416. } // Next up, normalize to an array, so one or many items can be normalized,
  1417. // filtered, and returned.
  1418. return (Array.isArray(content) ? content : [content]).map(function (value) {
  1419. // First, invoke value if it is a function to produce a new value,
  1420. // which will be subsequently normalized to a Node of some kind.
  1421. if (typeof value === 'function') {
  1422. value = value();
  1423. }
  1424. if (isEl(value) || isTextNode$1(value)) {
  1425. return value;
  1426. }
  1427. if (typeof value === 'string' && /\S/.test(value)) {
  1428. return document.createTextNode(value);
  1429. }
  1430. }).filter(function (value) {
  1431. return value;
  1432. });
  1433. }
  1434. /**
  1435. * Normalizes and appends content to an element.
  1436. *
  1437. * @param {Element} el
  1438. * Element to append normalized content to.
  1439. *
  1440. * @param {module:dom~ContentDescriptor} content
  1441. * A content descriptor value.
  1442. *
  1443. * @return {Element}
  1444. * The element with appended normalized content.
  1445. */
  1446. function appendContent(el, content) {
  1447. normalizeContent(content).forEach(function (node) {
  1448. return el.appendChild(node);
  1449. });
  1450. return el;
  1451. }
  1452. /**
  1453. * Normalizes and inserts content into an element; this is identical to
  1454. * `appendContent()`, except it empties the element first.
  1455. *
  1456. * @param {Element} el
  1457. * Element to insert normalized content into.
  1458. *
  1459. * @param {module:dom~ContentDescriptor} content
  1460. * A content descriptor value.
  1461. *
  1462. * @return {Element}
  1463. * The element with inserted normalized content.
  1464. */
  1465. function insertContent(el, content) {
  1466. return appendContent(emptyEl(el), content);
  1467. }
  1468. /**
  1469. * Check if an event was a single left click.
  1470. *
  1471. * @param {EventTarget~Event} event
  1472. * Event object.
  1473. *
  1474. * @return {boolean}
  1475. * Will be `true` if a single left click, `false` otherwise.
  1476. */
  1477. function isSingleLeftClick(event) {
  1478. // Note: if you create something draggable, be sure to
  1479. // call it on both `mousedown` and `mousemove` event,
  1480. // otherwise `mousedown` should be enough for a button
  1481. if (event.button === undefined && event.buttons === undefined) {
  1482. // Why do we need `buttons` ?
  1483. // Because, middle mouse sometimes have this:
  1484. // e.button === 0 and e.buttons === 4
  1485. // Furthermore, we want to prevent combination click, something like
  1486. // HOLD middlemouse then left click, that would be
  1487. // e.button === 0, e.buttons === 5
  1488. // just `button` is not gonna work
  1489. // Alright, then what this block does ?
  1490. // this is for chrome `simulate mobile devices`
  1491. // I want to support this as well
  1492. return true;
  1493. }
  1494. if (event.button === 0 && event.buttons === undefined) {
  1495. // Touch screen, sometimes on some specific device, `buttons`
  1496. // doesn't have anything (safari on ios, blackberry...)
  1497. return true;
  1498. } // `mouseup` event on a single left click has
  1499. // `button` and `buttons` equal to 0
  1500. if (event.type === 'mouseup' && event.button === 0 && event.buttons === 0) {
  1501. return true;
  1502. }
  1503. if (event.button !== 0 || event.buttons !== 1) {
  1504. // This is the reason we have those if else block above
  1505. // if any special case we can catch and let it slide
  1506. // we do it above, when get to here, this definitely
  1507. // is-not-left-click
  1508. return false;
  1509. }
  1510. return true;
  1511. }
  1512. /**
  1513. * Finds a single DOM element matching `selector` within the optional
  1514. * `context` of another DOM element (defaulting to `document`).
  1515. *
  1516. * @param {string} selector
  1517. * A valid CSS selector, which will be passed to `querySelector`.
  1518. *
  1519. * @param {Element|String} [context=document]
  1520. * A DOM element within which to query. Can also be a selector
  1521. * string in which case the first matching element will be used
  1522. * as context. If missing (or no element matches selector), falls
  1523. * back to `document`.
  1524. *
  1525. * @return {Element|null}
  1526. * The element that was found or null.
  1527. */
  1528. var $ = createQuerier('querySelector');
  1529. /**
  1530. * Finds a all DOM elements matching `selector` within the optional
  1531. * `context` of another DOM element (defaulting to `document`).
  1532. *
  1533. * @param {string} selector
  1534. * A valid CSS selector, which will be passed to `querySelectorAll`.
  1535. *
  1536. * @param {Element|String} [context=document]
  1537. * A DOM element within which to query. Can also be a selector
  1538. * string in which case the first matching element will be used
  1539. * as context. If missing (or no element matches selector), falls
  1540. * back to `document`.
  1541. *
  1542. * @return {NodeList}
  1543. * A element list of elements that were found. Will be empty if none
  1544. * were found.
  1545. *
  1546. */
  1547. var $$ = createQuerier('querySelectorAll');
  1548. var Dom = /*#__PURE__*/Object.freeze({
  1549. __proto__: null,
  1550. isReal: isReal,
  1551. isEl: isEl,
  1552. isInFrame: isInFrame,
  1553. createEl: createEl,
  1554. textContent: textContent,
  1555. prependTo: prependTo,
  1556. hasClass: hasClass,
  1557. addClass: addClass,
  1558. removeClass: removeClass,
  1559. toggleClass: toggleClass,
  1560. setAttributes: setAttributes,
  1561. getAttributes: getAttributes,
  1562. getAttribute: getAttribute,
  1563. setAttribute: setAttribute,
  1564. removeAttribute: removeAttribute,
  1565. blockTextSelection: blockTextSelection,
  1566. unblockTextSelection: unblockTextSelection,
  1567. getBoundingClientRect: getBoundingClientRect,
  1568. findPosition: findPosition,
  1569. getPointerPosition: getPointerPosition,
  1570. isTextNode: isTextNode$1,
  1571. emptyEl: emptyEl,
  1572. normalizeContent: normalizeContent,
  1573. appendContent: appendContent,
  1574. insertContent: insertContent,
  1575. isSingleLeftClick: isSingleLeftClick,
  1576. $: $,
  1577. $$: $$
  1578. });
  1579. /**
  1580. * @file setup.js - Functions for setting up a player without
  1581. * user interaction based on the data-setup `attribute` of the video tag.
  1582. *
  1583. * @module setup
  1584. */
  1585. var _windowLoaded = false;
  1586. var videojs$1;
  1587. /**
  1588. * Set up any tags that have a data-setup `attribute` when the player is started.
  1589. */
  1590. var autoSetup = function autoSetup() {
  1591. if (videojs$1.options.autoSetup === false) {
  1592. return;
  1593. }
  1594. var vids = Array.prototype.slice.call(document.getElementsByTagName('video'));
  1595. var audios = Array.prototype.slice.call(document.getElementsByTagName('audio'));
  1596. var divs = Array.prototype.slice.call(document.getElementsByTagName('video-js'));
  1597. var mediaEls = vids.concat(audios, divs); // Check if any media elements exist
  1598. if (mediaEls && mediaEls.length > 0) {
  1599. for (var i = 0, e = mediaEls.length; i < e; i++) {
  1600. var mediaEl = mediaEls[i]; // Check if element exists, has getAttribute func.
  1601. if (mediaEl && mediaEl.getAttribute) {
  1602. // Make sure this player hasn't already been set up.
  1603. if (mediaEl.player === undefined) {
  1604. var options = mediaEl.getAttribute('data-setup'); // Check if data-setup attr exists.
  1605. // We only auto-setup if they've added the data-setup attr.
  1606. if (options !== null) {
  1607. // Create new video.js instance.
  1608. videojs$1(mediaEl);
  1609. }
  1610. } // If getAttribute isn't defined, we need to wait for the DOM.
  1611. } else {
  1612. autoSetupTimeout(1);
  1613. break;
  1614. }
  1615. } // No videos were found, so keep looping unless page is finished loading.
  1616. } else if (!_windowLoaded) {
  1617. autoSetupTimeout(1);
  1618. }
  1619. };
  1620. /**
  1621. * Wait until the page is loaded before running autoSetup. This will be called in
  1622. * autoSetup if `hasLoaded` returns false.
  1623. *
  1624. * @param {number} wait
  1625. * How long to wait in ms
  1626. *
  1627. * @param {module:videojs} [vjs]
  1628. * The videojs library function
  1629. */
  1630. function autoSetupTimeout(wait, vjs) {
  1631. // Protect against breakage in non-browser environments
  1632. if (!isReal()) {
  1633. return;
  1634. }
  1635. if (vjs) {
  1636. videojs$1 = vjs;
  1637. }
  1638. window.setTimeout(autoSetup, wait);
  1639. }
  1640. /**
  1641. * Used to set the internal tracking of window loaded state to true.
  1642. *
  1643. * @private
  1644. */
  1645. function setWindowLoaded() {
  1646. _windowLoaded = true;
  1647. window.removeEventListener('load', setWindowLoaded);
  1648. }
  1649. if (isReal()) {
  1650. if (document.readyState === 'complete') {
  1651. setWindowLoaded();
  1652. } else {
  1653. /**
  1654. * Listen for the load event on window, and set _windowLoaded to true.
  1655. *
  1656. * We use a standard event listener here to avoid incrementing the GUID
  1657. * before any players are created.
  1658. *
  1659. * @listens load
  1660. */
  1661. window.addEventListener('load', setWindowLoaded);
  1662. }
  1663. }
  1664. /**
  1665. * @file stylesheet.js
  1666. * @module stylesheet
  1667. */
  1668. /**
  1669. * Create a DOM syle element given a className for it.
  1670. *
  1671. * @param {string} className
  1672. * The className to add to the created style element.
  1673. *
  1674. * @return {Element}
  1675. * The element that was created.
  1676. */
  1677. var createStyleElement = function createStyleElement(className) {
  1678. var style = document.createElement('style');
  1679. style.className = className;
  1680. return style;
  1681. };
  1682. /**
  1683. * Add text to a DOM element.
  1684. *
  1685. * @param {Element} el
  1686. * The Element to add text content to.
  1687. *
  1688. * @param {string} content
  1689. * The text to add to the element.
  1690. */
  1691. var setTextContent = function setTextContent(el, content) {
  1692. if (el.styleSheet) {
  1693. el.styleSheet.cssText = content;
  1694. } else {
  1695. el.textContent = content;
  1696. }
  1697. };
  1698. /**
  1699. * @file guid.js
  1700. * @module guid
  1701. */
  1702. // Default value for GUIDs. This allows us to reset the GUID counter in tests.
  1703. //
  1704. // The initial GUID is 3 because some users have come to rely on the first
  1705. // default player ID ending up as `vjs_video_3`.
  1706. //
  1707. // See: https://github.com/videojs/video.js/pull/6216
  1708. var _initialGuid = 3;
  1709. /**
  1710. * Unique ID for an element or function
  1711. *
  1712. * @type {Number}
  1713. */
  1714. var _guid = _initialGuid;
  1715. /**
  1716. * Get a unique auto-incrementing ID by number that has not been returned before.
  1717. *
  1718. * @return {number}
  1719. * A new unique ID.
  1720. */
  1721. function newGUID() {
  1722. return _guid++;
  1723. }
  1724. /**
  1725. * @file dom-data.js
  1726. * @module dom-data
  1727. */
  1728. var FakeWeakMap;
  1729. if (!window.WeakMap) {
  1730. FakeWeakMap = /*#__PURE__*/function () {
  1731. function FakeWeakMap() {
  1732. this.vdata = 'vdata' + Math.floor(window.performance && window.performance.now() || Date.now());
  1733. this.data = {};
  1734. }
  1735. var _proto = FakeWeakMap.prototype;
  1736. _proto.set = function set(key, value) {
  1737. var access = key[this.vdata] || newGUID();
  1738. if (!key[this.vdata]) {
  1739. key[this.vdata] = access;
  1740. }
  1741. this.data[access] = value;
  1742. return this;
  1743. };
  1744. _proto.get = function get(key) {
  1745. var access = key[this.vdata]; // we have data, return it
  1746. if (access) {
  1747. return this.data[access];
  1748. } // we don't have data, return nothing.
  1749. // return undefined explicitly as that's the contract for this method
  1750. log$1('We have no data for this element', key);
  1751. return undefined;
  1752. };
  1753. _proto.has = function has(key) {
  1754. var access = key[this.vdata];
  1755. return access in this.data;
  1756. };
  1757. _proto["delete"] = function _delete(key) {
  1758. var access = key[this.vdata];
  1759. if (access) {
  1760. delete this.data[access];
  1761. delete key[this.vdata];
  1762. }
  1763. };
  1764. return FakeWeakMap;
  1765. }();
  1766. }
  1767. /**
  1768. * Element Data Store.
  1769. *
  1770. * Allows for binding data to an element without putting it directly on the
  1771. * element. Ex. Event listeners are stored here.
  1772. * (also from jsninja.com, slightly modified and updated for closure compiler)
  1773. *
  1774. * @type {Object}
  1775. * @private
  1776. */
  1777. var DomData = window.WeakMap ? new WeakMap() : new FakeWeakMap();
  1778. /**
  1779. * @file events.js. An Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/)
  1780. * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible)
  1781. * This should work very similarly to jQuery's events, however it's based off the book version which isn't as
  1782. * robust as jquery's, so there's probably some differences.
  1783. *
  1784. * @file events.js
  1785. * @module events
  1786. */
  1787. /**
  1788. * Clean up the listener cache and dispatchers
  1789. *
  1790. * @param {Element|Object} elem
  1791. * Element to clean up
  1792. *
  1793. * @param {string} type
  1794. * Type of event to clean up
  1795. */
  1796. function _cleanUpEvents(elem, type) {
  1797. if (!DomData.has(elem)) {
  1798. return;
  1799. }
  1800. var data = DomData.get(elem); // Remove the events of a particular type if there are none left
  1801. if (data.handlers[type].length === 0) {
  1802. delete data.handlers[type]; // data.handlers[type] = null;
  1803. // Setting to null was causing an error with data.handlers
  1804. // Remove the meta-handler from the element
  1805. if (elem.removeEventListener) {
  1806. elem.removeEventListener(type, data.dispatcher, false);
  1807. } else if (elem.detachEvent) {
  1808. elem.detachEvent('on' + type, data.dispatcher);
  1809. }
  1810. } // Remove the events object if there are no types left
  1811. if (Object.getOwnPropertyNames(data.handlers).length <= 0) {
  1812. delete data.handlers;
  1813. delete data.dispatcher;
  1814. delete data.disabled;
  1815. } // Finally remove the element data if there is no data left
  1816. if (Object.getOwnPropertyNames(data).length === 0) {
  1817. DomData["delete"](elem);
  1818. }
  1819. }
  1820. /**
  1821. * Loops through an array of event types and calls the requested method for each type.
  1822. *
  1823. * @param {Function} fn
  1824. * The event method we want to use.
  1825. *
  1826. * @param {Element|Object} elem
  1827. * Element or object to bind listeners to
  1828. *
  1829. * @param {string} type
  1830. * Type of event to bind to.
  1831. *
  1832. * @param {EventTarget~EventListener} callback
  1833. * Event listener.
  1834. */
  1835. function _handleMultipleEvents(fn, elem, types, callback) {
  1836. types.forEach(function (type) {
  1837. // Call the event method for each one of the types
  1838. fn(elem, type, callback);
  1839. });
  1840. }
  1841. /**
  1842. * Fix a native event to have standard property values
  1843. *
  1844. * @param {Object} event
  1845. * Event object to fix.
  1846. *
  1847. * @return {Object}
  1848. * Fixed event object.
  1849. */
  1850. function fixEvent(event) {
  1851. if (event.fixed_) {
  1852. return event;
  1853. }
  1854. function returnTrue() {
  1855. return true;
  1856. }
  1857. function returnFalse() {
  1858. return false;
  1859. } // Test if fixing up is needed
  1860. // Used to check if !event.stopPropagation instead of isPropagationStopped
  1861. // But native events return true for stopPropagation, but don't have
  1862. // other expected methods like isPropagationStopped. Seems to be a problem
  1863. // with the Javascript Ninja code. So we're just overriding all events now.
  1864. if (!event || !event.isPropagationStopped || !event.isImmediatePropagationStopped) {
  1865. var old = event || window.event;
  1866. event = {}; // Clone the old object so that we can modify the values event = {};
  1867. // IE8 Doesn't like when you mess with native event properties
  1868. // Firefox returns false for event.hasOwnProperty('type') and other props
  1869. // which makes copying more difficult.
  1870. // TODO: Probably best to create a whitelist of event props
  1871. for (var key in old) {
  1872. // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y
  1873. // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation
  1874. // and webkitMovementX/Y
  1875. // Lighthouse complains if Event.path is copied
  1876. if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation' && key !== 'webkitMovementX' && key !== 'webkitMovementY' && key !== 'path') {
  1877. // Chrome 32+ warns if you try to copy deprecated returnValue, but
  1878. // we still want to if preventDefault isn't supported (IE8).
  1879. if (!(key === 'returnValue' && old.preventDefault)) {
  1880. event[key] = old[key];
  1881. }
  1882. }
  1883. } // The event occurred on this element
  1884. if (!event.target) {
  1885. event.target = event.srcElement || document;
  1886. } // Handle which other element the event is related to
  1887. if (!event.relatedTarget) {
  1888. event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement;
  1889. } // Stop the default browser action
  1890. event.preventDefault = function () {
  1891. if (old.preventDefault) {
  1892. old.preventDefault();
  1893. }
  1894. event.returnValue = false;
  1895. old.returnValue = false;
  1896. event.defaultPrevented = true;
  1897. };
  1898. event.defaultPrevented = false; // Stop the event from bubbling
  1899. event.stopPropagation = function () {
  1900. if (old.stopPropagation) {
  1901. old.stopPropagation();
  1902. }
  1903. event.cancelBubble = true;
  1904. old.cancelBubble = true;
  1905. event.isPropagationStopped = returnTrue;
  1906. };
  1907. event.isPropagationStopped = returnFalse; // Stop the event from bubbling and executing other handlers
  1908. event.stopImmediatePropagation = function () {
  1909. if (old.stopImmediatePropagation) {
  1910. old.stopImmediatePropagation();
  1911. }
  1912. event.isImmediatePropagationStopped = returnTrue;
  1913. event.stopPropagation();
  1914. };
  1915. event.isImmediatePropagationStopped = returnFalse; // Handle mouse position
  1916. if (event.clientX !== null && event.clientX !== undefined) {
  1917. var doc = document.documentElement;
  1918. var body = document.body;
  1919. event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  1920. event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  1921. } // Handle key presses
  1922. event.which = event.charCode || event.keyCode; // Fix button for mouse clicks:
  1923. // 0 == left; 1 == middle; 2 == right
  1924. if (event.button !== null && event.button !== undefined) {
  1925. // The following is disabled because it does not pass videojs-standard
  1926. // and... yikes.
  1927. /* eslint-disable */
  1928. event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0;
  1929. /* eslint-enable */
  1930. }
  1931. }
  1932. event.fixed_ = true; // Returns fixed-up instance
  1933. return event;
  1934. }
  1935. /**
  1936. * Whether passive event listeners are supported
  1937. */
  1938. var _supportsPassive;
  1939. var supportsPassive = function supportsPassive() {
  1940. if (typeof _supportsPassive !== 'boolean') {
  1941. _supportsPassive = false;
  1942. try {
  1943. var opts = Object.defineProperty({}, 'passive', {
  1944. get: function get() {
  1945. _supportsPassive = true;
  1946. }
  1947. });
  1948. window.addEventListener('test', null, opts);
  1949. window.removeEventListener('test', null, opts);
  1950. } catch (e) {// disregard
  1951. }
  1952. }
  1953. return _supportsPassive;
  1954. };
  1955. /**
  1956. * Touch events Chrome expects to be passive
  1957. */
  1958. var passiveEvents = ['touchstart', 'touchmove'];
  1959. /**
  1960. * Add an event listener to element
  1961. * It stores the handler function in a separate cache object
  1962. * and adds a generic handler to the element's event,
  1963. * along with a unique id (guid) to the element.
  1964. *
  1965. * @param {Element|Object} elem
  1966. * Element or object to bind listeners to
  1967. *
  1968. * @param {string|string[]} type
  1969. * Type of event to bind to.
  1970. *
  1971. * @param {EventTarget~EventListener} fn
  1972. * Event listener.
  1973. */
  1974. function on(elem, type, fn) {
  1975. if (Array.isArray(type)) {
  1976. return _handleMultipleEvents(on, elem, type, fn);
  1977. }
  1978. if (!DomData.has(elem)) {
  1979. DomData.set(elem, {});
  1980. }
  1981. var data = DomData.get(elem); // We need a place to store all our handler data
  1982. if (!data.handlers) {
  1983. data.handlers = {};
  1984. }
  1985. if (!data.handlers[type]) {
  1986. data.handlers[type] = [];
  1987. }
  1988. if (!fn.guid) {
  1989. fn.guid = newGUID();
  1990. }
  1991. data.handlers[type].push(fn);
  1992. if (!data.dispatcher) {
  1993. data.disabled = false;
  1994. data.dispatcher = function (event, hash) {
  1995. if (data.disabled) {
  1996. return;
  1997. }
  1998. event = fixEvent(event);
  1999. var handlers = data.handlers[event.type];
  2000. if (handlers) {
  2001. // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off.
  2002. var handlersCopy = handlers.slice(0);
  2003. for (var m = 0, n = handlersCopy.length; m < n; m++) {
  2004. if (event.isImmediatePropagationStopped()) {
  2005. break;
  2006. } else {
  2007. try {
  2008. handlersCopy[m].call(elem, event, hash);
  2009. } catch (e) {
  2010. log$1.error(e);
  2011. }
  2012. }
  2013. }
  2014. }
  2015. };
  2016. }
  2017. if (data.handlers[type].length === 1) {
  2018. if (elem.addEventListener) {
  2019. var options = false;
  2020. if (supportsPassive() && passiveEvents.indexOf(type) > -1) {
  2021. options = {
  2022. passive: true
  2023. };
  2024. }
  2025. elem.addEventListener(type, data.dispatcher, options);
  2026. } else if (elem.attachEvent) {
  2027. elem.attachEvent('on' + type, data.dispatcher);
  2028. }
  2029. }
  2030. }
  2031. /**
  2032. * Removes event listeners from an element
  2033. *
  2034. * @param {Element|Object} elem
  2035. * Object to remove listeners from.
  2036. *
  2037. * @param {string|string[]} [type]
  2038. * Type of listener to remove. Don't include to remove all events from element.
  2039. *
  2040. * @param {EventTarget~EventListener} [fn]
  2041. * Specific listener to remove. Don't include to remove listeners for an event
  2042. * type.
  2043. */
  2044. function off(elem, type, fn) {
  2045. // Don't want to add a cache object through getElData if not needed
  2046. if (!DomData.has(elem)) {
  2047. return;
  2048. }
  2049. var data = DomData.get(elem); // If no events exist, nothing to unbind
  2050. if (!data.handlers) {
  2051. return;
  2052. }
  2053. if (Array.isArray(type)) {
  2054. return _handleMultipleEvents(off, elem, type, fn);
  2055. } // Utility function
  2056. var removeType = function removeType(el, t) {
  2057. data.handlers[t] = [];
  2058. _cleanUpEvents(el, t);
  2059. }; // Are we removing all bound events?
  2060. if (type === undefined) {
  2061. for (var t in data.handlers) {
  2062. if (Object.prototype.hasOwnProperty.call(data.handlers || {}, t)) {
  2063. removeType(elem, t);
  2064. }
  2065. }
  2066. return;
  2067. }
  2068. var handlers = data.handlers[type]; // If no handlers exist, nothing to unbind
  2069. if (!handlers) {
  2070. return;
  2071. } // If no listener was provided, remove all listeners for type
  2072. if (!fn) {
  2073. removeType(elem, type);
  2074. return;
  2075. } // We're only removing a single handler
  2076. if (fn.guid) {
  2077. for (var n = 0; n < handlers.length; n++) {
  2078. if (handlers[n].guid === fn.guid) {
  2079. handlers.splice(n--, 1);
  2080. }
  2081. }
  2082. }
  2083. _cleanUpEvents(elem, type);
  2084. }
  2085. /**
  2086. * Trigger an event for an element
  2087. *
  2088. * @param {Element|Object} elem
  2089. * Element to trigger an event on
  2090. *
  2091. * @param {EventTarget~Event|string} event
  2092. * A string (the type) or an event object with a type attribute
  2093. *
  2094. * @param {Object} [hash]
  2095. * data hash to pass along with the event
  2096. *
  2097. * @return {boolean|undefined}
  2098. * Returns the opposite of `defaultPrevented` if default was
  2099. * prevented. Otherwise, returns `undefined`
  2100. */
  2101. function trigger(elem, event, hash) {
  2102. // Fetches element data and a reference to the parent (for bubbling).
  2103. // Don't want to add a data object to cache for every parent,
  2104. // so checking hasElData first.
  2105. var elemData = DomData.has(elem) ? DomData.get(elem) : {};
  2106. var parent = elem.parentNode || elem.ownerDocument; // type = event.type || event,
  2107. // handler;
  2108. // If an event name was passed as a string, creates an event out of it
  2109. if (typeof event === 'string') {
  2110. event = {
  2111. type: event,
  2112. target: elem
  2113. };
  2114. } else if (!event.target) {
  2115. event.target = elem;
  2116. } // Normalizes the event properties.
  2117. event = fixEvent(event); // If the passed element has a dispatcher, executes the established handlers.
  2118. if (elemData.dispatcher) {
  2119. elemData.dispatcher.call(elem, event, hash);
  2120. } // Unless explicitly stopped or the event does not bubble (e.g. media events)
  2121. // recursively calls this function to bubble the event up the DOM.
  2122. if (parent && !event.isPropagationStopped() && event.bubbles === true) {
  2123. trigger.call(null, parent, event, hash); // If at the top of the DOM, triggers the default action unless disabled.
  2124. } else if (!parent && !event.defaultPrevented && event.target && event.target[event.type]) {
  2125. if (!DomData.has(event.target)) {
  2126. DomData.set(event.target, {});
  2127. }
  2128. var targetData = DomData.get(event.target); // Checks if the target has a default action for this event.
  2129. if (event.target[event.type]) {
  2130. // Temporarily disables event dispatching on the target as we have already executed the handler.
  2131. targetData.disabled = true; // Executes the default action.
  2132. if (typeof event.target[event.type] === 'function') {
  2133. event.target[event.type]();
  2134. } // Re-enables event dispatching.
  2135. targetData.disabled = false;
  2136. }
  2137. } // Inform the triggerer if the default was prevented by returning false
  2138. return !event.defaultPrevented;
  2139. }
  2140. /**
  2141. * Trigger a listener only once for an event.
  2142. *
  2143. * @param {Element|Object} elem
  2144. * Element or object to bind to.
  2145. *
  2146. * @param {string|string[]} type
  2147. * Name/type of event
  2148. *
  2149. * @param {Event~EventListener} fn
  2150. * Event listener function
  2151. */
  2152. function one(elem, type, fn) {
  2153. if (Array.isArray(type)) {
  2154. return _handleMultipleEvents(one, elem, type, fn);
  2155. }
  2156. var func = function func() {
  2157. off(elem, type, func);
  2158. fn.apply(this, arguments);
  2159. }; // copy the guid to the new function so it can removed using the original function's ID
  2160. func.guid = fn.guid = fn.guid || newGUID();
  2161. on(elem, type, func);
  2162. }
  2163. /**
  2164. * Trigger a listener only once and then turn if off for all
  2165. * configured events
  2166. *
  2167. * @param {Element|Object} elem
  2168. * Element or object to bind to.
  2169. *
  2170. * @param {string|string[]} type
  2171. * Name/type of event
  2172. *
  2173. * @param {Event~EventListener} fn
  2174. * Event listener function
  2175. */
  2176. function any(elem, type, fn) {
  2177. var func = function func() {
  2178. off(elem, type, func);
  2179. fn.apply(this, arguments);
  2180. }; // copy the guid to the new function so it can removed using the original function's ID
  2181. func.guid = fn.guid = fn.guid || newGUID(); // multiple ons, but one off for everything
  2182. on(elem, type, func);
  2183. }
  2184. var Events = /*#__PURE__*/Object.freeze({
  2185. __proto__: null,
  2186. fixEvent: fixEvent,
  2187. on: on,
  2188. off: off,
  2189. trigger: trigger,
  2190. one: one,
  2191. any: any
  2192. });
  2193. /**
  2194. * @file fn.js
  2195. * @module fn
  2196. */
  2197. var UPDATE_REFRESH_INTERVAL = 30;
  2198. /**
  2199. * Bind (a.k.a proxy or context). A simple method for changing the context of
  2200. * a function.
  2201. *
  2202. * It also stores a unique id on the function so it can be easily removed from
  2203. * events.
  2204. *
  2205. * @function
  2206. * @param {Mixed} context
  2207. * The object to bind as scope.
  2208. *
  2209. * @param {Function} fn
  2210. * The function to be bound to a scope.
  2211. *
  2212. * @param {number} [uid]
  2213. * An optional unique ID for the function to be set
  2214. *
  2215. * @return {Function}
  2216. * The new function that will be bound into the context given
  2217. */
  2218. var bind = function bind(context, fn, uid) {
  2219. // Make sure the function has a unique ID
  2220. if (!fn.guid) {
  2221. fn.guid = newGUID();
  2222. } // Create the new function that changes the context
  2223. var bound = fn.bind(context); // Allow for the ability to individualize this function
  2224. // Needed in the case where multiple objects might share the same prototype
  2225. // IF both items add an event listener with the same function, then you try to remove just one
  2226. // it will remove both because they both have the same guid.
  2227. // when using this, you need to use the bind method when you remove the listener as well.
  2228. // currently used in text tracks
  2229. bound.guid = uid ? uid + '_' + fn.guid : fn.guid;
  2230. return bound;
  2231. };
  2232. /**
  2233. * Wraps the given function, `fn`, with a new function that only invokes `fn`
  2234. * at most once per every `wait` milliseconds.
  2235. *
  2236. * @function
  2237. * @param {Function} fn
  2238. * The function to be throttled.
  2239. *
  2240. * @param {number} wait
  2241. * The number of milliseconds by which to throttle.
  2242. *
  2243. * @return {Function}
  2244. */
  2245. var throttle = function throttle(fn, wait) {
  2246. var last = window.performance.now();
  2247. var throttled = function throttled() {
  2248. var now = window.performance.now();
  2249. if (now - last >= wait) {
  2250. fn.apply(void 0, arguments);
  2251. last = now;
  2252. }
  2253. };
  2254. return throttled;
  2255. };
  2256. /**
  2257. * Creates a debounced function that delays invoking `func` until after `wait`
  2258. * milliseconds have elapsed since the last time the debounced function was
  2259. * invoked.
  2260. *
  2261. * Inspired by lodash and underscore implementations.
  2262. *
  2263. * @function
  2264. * @param {Function} func
  2265. * The function to wrap with debounce behavior.
  2266. *
  2267. * @param {number} wait
  2268. * The number of milliseconds to wait after the last invocation.
  2269. *
  2270. * @param {boolean} [immediate]
  2271. * Whether or not to invoke the function immediately upon creation.
  2272. *
  2273. * @param {Object} [context=window]
  2274. * The "context" in which the debounced function should debounce. For
  2275. * example, if this function should be tied to a Video.js player,
  2276. * the player can be passed here. Alternatively, defaults to the
  2277. * global `window` object.
  2278. *
  2279. * @return {Function}
  2280. * A debounced function.
  2281. */
  2282. var debounce = function debounce(func, wait, immediate, context) {
  2283. if (context === void 0) {
  2284. context = window;
  2285. }
  2286. var timeout;
  2287. var cancel = function cancel() {
  2288. context.clearTimeout(timeout);
  2289. timeout = null;
  2290. };
  2291. /* eslint-disable consistent-this */
  2292. var debounced = function debounced() {
  2293. var self = this;
  2294. var args = arguments;
  2295. var _later = function later() {
  2296. timeout = null;
  2297. _later = null;
  2298. if (!immediate) {
  2299. func.apply(self, args);
  2300. }
  2301. };
  2302. if (!timeout && immediate) {
  2303. func.apply(self, args);
  2304. }
  2305. context.clearTimeout(timeout);
  2306. timeout = context.setTimeout(_later, wait);
  2307. };
  2308. /* eslint-enable consistent-this */
  2309. debounced.cancel = cancel;
  2310. return debounced;
  2311. };
  2312. /**
  2313. * @file src/js/event-target.js
  2314. */
  2315. /**
  2316. * `EventTarget` is a class that can have the same API as the DOM `EventTarget`. It
  2317. * adds shorthand functions that wrap around lengthy functions. For example:
  2318. * the `on` function is a wrapper around `addEventListener`.
  2319. *
  2320. * @see [EventTarget Spec]{@link https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget}
  2321. * @class EventTarget
  2322. */
  2323. var EventTarget$2 = function EventTarget() {};
  2324. /**
  2325. * A Custom DOM event.
  2326. *
  2327. * @typedef {Object} EventTarget~Event
  2328. * @see [Properties]{@link https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent}
  2329. */
  2330. /**
  2331. * All event listeners should follow the following format.
  2332. *
  2333. * @callback EventTarget~EventListener
  2334. * @this {EventTarget}
  2335. *
  2336. * @param {EventTarget~Event} event
  2337. * the event that triggered this function
  2338. *
  2339. * @param {Object} [hash]
  2340. * hash of data sent during the event
  2341. */
  2342. /**
  2343. * An object containing event names as keys and booleans as values.
  2344. *
  2345. * > NOTE: If an event name is set to a true value here {@link EventTarget#trigger}
  2346. * will have extra functionality. See that function for more information.
  2347. *
  2348. * @property EventTarget.prototype.allowedEvents_
  2349. * @private
  2350. */
  2351. EventTarget$2.prototype.allowedEvents_ = {};
  2352. /**
  2353. * Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a
  2354. * function that will get called when an event with a certain name gets triggered.
  2355. *
  2356. * @param {string|string[]} type
  2357. * An event name or an array of event names.
  2358. *
  2359. * @param {EventTarget~EventListener} fn
  2360. * The function to call with `EventTarget`s
  2361. */
  2362. EventTarget$2.prototype.on = function (type, fn) {
  2363. // Remove the addEventListener alias before calling Events.on
  2364. // so we don't get into an infinite type loop
  2365. var ael = this.addEventListener;
  2366. this.addEventListener = function () {};
  2367. on(this, type, fn);
  2368. this.addEventListener = ael;
  2369. };
  2370. /**
  2371. * An alias of {@link EventTarget#on}. Allows `EventTarget` to mimic
  2372. * the standard DOM API.
  2373. *
  2374. * @function
  2375. * @see {@link EventTarget#on}
  2376. */
  2377. EventTarget$2.prototype.addEventListener = EventTarget$2.prototype.on;
  2378. /**
  2379. * Removes an `event listener` for a specific event from an instance of `EventTarget`.
  2380. * This makes it so that the `event listener` will no longer get called when the
  2381. * named event happens.
  2382. *
  2383. * @param {string|string[]} type
  2384. * An event name or an array of event names.
  2385. *
  2386. * @param {EventTarget~EventListener} fn
  2387. * The function to remove.
  2388. */
  2389. EventTarget$2.prototype.off = function (type, fn) {
  2390. off(this, type, fn);
  2391. };
  2392. /**
  2393. * An alias of {@link EventTarget#off}. Allows `EventTarget` to mimic
  2394. * the standard DOM API.
  2395. *
  2396. * @function
  2397. * @see {@link EventTarget#off}
  2398. */
  2399. EventTarget$2.prototype.removeEventListener = EventTarget$2.prototype.off;
  2400. /**
  2401. * This function will add an `event listener` that gets triggered only once. After the
  2402. * first trigger it will get removed. This is like adding an `event listener`
  2403. * with {@link EventTarget#on} that calls {@link EventTarget#off} on itself.
  2404. *
  2405. * @param {string|string[]} type
  2406. * An event name or an array of event names.
  2407. *
  2408. * @param {EventTarget~EventListener} fn
  2409. * The function to be called once for each event name.
  2410. */
  2411. EventTarget$2.prototype.one = function (type, fn) {
  2412. // Remove the addEventListener aliasing Events.on
  2413. // so we don't get into an infinite type loop
  2414. var ael = this.addEventListener;
  2415. this.addEventListener = function () {};
  2416. one(this, type, fn);
  2417. this.addEventListener = ael;
  2418. };
  2419. EventTarget$2.prototype.any = function (type, fn) {
  2420. // Remove the addEventListener aliasing Events.on
  2421. // so we don't get into an infinite type loop
  2422. var ael = this.addEventListener;
  2423. this.addEventListener = function () {};
  2424. any(this, type, fn);
  2425. this.addEventListener = ael;
  2426. };
  2427. /**
  2428. * This function causes an event to happen. This will then cause any `event listeners`
  2429. * that are waiting for that event, to get called. If there are no `event listeners`
  2430. * for an event then nothing will happen.
  2431. *
  2432. * If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`.
  2433. * Trigger will also call the `on` + `uppercaseEventName` function.
  2434. *
  2435. * Example:
  2436. * 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call
  2437. * `onClick` if it exists.
  2438. *
  2439. * @param {string|EventTarget~Event|Object} event
  2440. * The name of the event, an `Event`, or an object with a key of type set to
  2441. * an event name.
  2442. */
  2443. EventTarget$2.prototype.trigger = function (event) {
  2444. var type = event.type || event; // deprecation
  2445. // In a future version we should default target to `this`
  2446. // similar to how we default the target to `elem` in
  2447. // `Events.trigger`. Right now the default `target` will be
  2448. // `document` due to the `Event.fixEvent` call.
  2449. if (typeof event === 'string') {
  2450. event = {
  2451. type: type
  2452. };
  2453. }
  2454. event = fixEvent(event);
  2455. if (this.allowedEvents_[type] && this['on' + type]) {
  2456. this['on' + type](event);
  2457. }
  2458. trigger(this, event);
  2459. };
  2460. /**
  2461. * An alias of {@link EventTarget#trigger}. Allows `EventTarget` to mimic
  2462. * the standard DOM API.
  2463. *
  2464. * @function
  2465. * @see {@link EventTarget#trigger}
  2466. */
  2467. EventTarget$2.prototype.dispatchEvent = EventTarget$2.prototype.trigger;
  2468. var EVENT_MAP;
  2469. EventTarget$2.prototype.queueTrigger = function (event) {
  2470. var _this = this;
  2471. // only set up EVENT_MAP if it'll be used
  2472. if (!EVENT_MAP) {
  2473. EVENT_MAP = new Map();
  2474. }
  2475. var type = event.type || event;
  2476. var map = EVENT_MAP.get(this);
  2477. if (!map) {
  2478. map = new Map();
  2479. EVENT_MAP.set(this, map);
  2480. }
  2481. var oldTimeout = map.get(type);
  2482. map["delete"](type);
  2483. window.clearTimeout(oldTimeout);
  2484. var timeout = window.setTimeout(function () {
  2485. map["delete"](type); // if we cleared out all timeouts for the current target, delete its map
  2486. if (map.size === 0) {
  2487. map = null;
  2488. EVENT_MAP["delete"](_this);
  2489. }
  2490. _this.trigger(event);
  2491. }, 0);
  2492. map.set(type, timeout);
  2493. };
  2494. /**
  2495. * @file mixins/evented.js
  2496. * @module evented
  2497. */
  2498. var objName = function objName(obj) {
  2499. if (typeof obj.name === 'function') {
  2500. return obj.name();
  2501. }
  2502. if (typeof obj.name === 'string') {
  2503. return obj.name;
  2504. }
  2505. if (obj.name_) {
  2506. return obj.name_;
  2507. }
  2508. if (obj.constructor && obj.constructor.name) {
  2509. return obj.constructor.name;
  2510. }
  2511. return typeof obj;
  2512. };
  2513. /**
  2514. * Returns whether or not an object has had the evented mixin applied.
  2515. *
  2516. * @param {Object} object
  2517. * An object to test.
  2518. *
  2519. * @return {boolean}
  2520. * Whether or not the object appears to be evented.
  2521. */
  2522. var isEvented = function isEvented(object) {
  2523. return object instanceof EventTarget$2 || !!object.eventBusEl_ && ['on', 'one', 'off', 'trigger'].every(function (k) {
  2524. return typeof object[k] === 'function';
  2525. });
  2526. };
  2527. /**
  2528. * Adds a callback to run after the evented mixin applied.
  2529. *
  2530. * @param {Object} object
  2531. * An object to Add
  2532. * @param {Function} callback
  2533. * The callback to run.
  2534. */
  2535. var addEventedCallback = function addEventedCallback(target, callback) {
  2536. if (isEvented(target)) {
  2537. callback();
  2538. } else {
  2539. if (!target.eventedCallbacks) {
  2540. target.eventedCallbacks = [];
  2541. }
  2542. target.eventedCallbacks.push(callback);
  2543. }
  2544. };
  2545. /**
  2546. * Whether a value is a valid event type - non-empty string or array.
  2547. *
  2548. * @private
  2549. * @param {string|Array} type
  2550. * The type value to test.
  2551. *
  2552. * @return {boolean}
  2553. * Whether or not the type is a valid event type.
  2554. */
  2555. var isValidEventType = function isValidEventType(type) {
  2556. return (// The regex here verifies that the `type` contains at least one non-
  2557. // whitespace character.
  2558. typeof type === 'string' && /\S/.test(type) || Array.isArray(type) && !!type.length
  2559. );
  2560. };
  2561. /**
  2562. * Validates a value to determine if it is a valid event target. Throws if not.
  2563. *
  2564. * @private
  2565. * @throws {Error}
  2566. * If the target does not appear to be a valid event target.
  2567. *
  2568. * @param {Object} target
  2569. * The object to test.
  2570. *
  2571. * @param {Object} obj
  2572. * The evented object we are validating for
  2573. *
  2574. * @param {string} fnName
  2575. * The name of the evented mixin function that called this.
  2576. */
  2577. var validateTarget = function validateTarget(target, obj, fnName) {
  2578. if (!target || !target.nodeName && !isEvented(target)) {
  2579. throw new Error("Invalid target for " + objName(obj) + "#" + fnName + "; must be a DOM node or evented object.");
  2580. }
  2581. };
  2582. /**
  2583. * Validates a value to determine if it is a valid event target. Throws if not.
  2584. *
  2585. * @private
  2586. * @throws {Error}
  2587. * If the type does not appear to be a valid event type.
  2588. *
  2589. * @param {string|Array} type
  2590. * The type to test.
  2591. *
  2592. * @param {Object} obj
  2593. * The evented object we are validating for
  2594. *
  2595. * @param {string} fnName
  2596. * The name of the evented mixin function that called this.
  2597. */
  2598. var validateEventType = function validateEventType(type, obj, fnName) {
  2599. if (!isValidEventType(type)) {
  2600. throw new Error("Invalid event type for " + objName(obj) + "#" + fnName + "; must be a non-empty string or array.");
  2601. }
  2602. };
  2603. /**
  2604. * Validates a value to determine if it is a valid listener. Throws if not.
  2605. *
  2606. * @private
  2607. * @throws {Error}
  2608. * If the listener is not a function.
  2609. *
  2610. * @param {Function} listener
  2611. * The listener to test.
  2612. *
  2613. * @param {Object} obj
  2614. * The evented object we are validating for
  2615. *
  2616. * @param {string} fnName
  2617. * The name of the evented mixin function that called this.
  2618. */
  2619. var validateListener = function validateListener(listener, obj, fnName) {
  2620. if (typeof listener !== 'function') {
  2621. throw new Error("Invalid listener for " + objName(obj) + "#" + fnName + "; must be a function.");
  2622. }
  2623. };
  2624. /**
  2625. * Takes an array of arguments given to `on()` or `one()`, validates them, and
  2626. * normalizes them into an object.
  2627. *
  2628. * @private
  2629. * @param {Object} self
  2630. * The evented object on which `on()` or `one()` was called. This
  2631. * object will be bound as the `this` value for the listener.
  2632. *
  2633. * @param {Array} args
  2634. * An array of arguments passed to `on()` or `one()`.
  2635. *
  2636. * @param {string} fnName
  2637. * The name of the evented mixin function that called this.
  2638. *
  2639. * @return {Object}
  2640. * An object containing useful values for `on()` or `one()` calls.
  2641. */
  2642. var normalizeListenArgs = function normalizeListenArgs(self, args, fnName) {
  2643. // If the number of arguments is less than 3, the target is always the
  2644. // evented object itself.
  2645. var isTargetingSelf = args.length < 3 || args[0] === self || args[0] === self.eventBusEl_;
  2646. var target;
  2647. var type;
  2648. var listener;
  2649. if (isTargetingSelf) {
  2650. target = self.eventBusEl_; // Deal with cases where we got 3 arguments, but we are still listening to
  2651. // the evented object itself.
  2652. if (args.length >= 3) {
  2653. args.shift();
  2654. }
  2655. type = args[0];
  2656. listener = args[1];
  2657. } else {
  2658. target = args[0];
  2659. type = args[1];
  2660. listener = args[2];
  2661. }
  2662. validateTarget(target, self, fnName);
  2663. validateEventType(type, self, fnName);
  2664. validateListener(listener, self, fnName);
  2665. listener = bind(self, listener);
  2666. return {
  2667. isTargetingSelf: isTargetingSelf,
  2668. target: target,
  2669. type: type,
  2670. listener: listener
  2671. };
  2672. };
  2673. /**
  2674. * Adds the listener to the event type(s) on the target, normalizing for
  2675. * the type of target.
  2676. *
  2677. * @private
  2678. * @param {Element|Object} target
  2679. * A DOM node or evented object.
  2680. *
  2681. * @param {string} method
  2682. * The event binding method to use ("on" or "one").
  2683. *
  2684. * @param {string|Array} type
  2685. * One or more event type(s).
  2686. *
  2687. * @param {Function} listener
  2688. * A listener function.
  2689. */
  2690. var listen = function listen(target, method, type, listener) {
  2691. validateTarget(target, target, method);
  2692. if (target.nodeName) {
  2693. Events[method](target, type, listener);
  2694. } else {
  2695. target[method](type, listener);
  2696. }
  2697. };
  2698. /**
  2699. * Contains methods that provide event capabilities to an object which is passed
  2700. * to {@link module:evented|evented}.
  2701. *
  2702. * @mixin EventedMixin
  2703. */
  2704. var EventedMixin = {
  2705. /**
  2706. * Add a listener to an event (or events) on this object or another evented
  2707. * object.
  2708. *
  2709. * @param {string|Array|Element|Object} targetOrType
  2710. * If this is a string or array, it represents the event type(s)
  2711. * that will trigger the listener.
  2712. *
  2713. * Another evented object can be passed here instead, which will
  2714. * cause the listener to listen for events on _that_ object.
  2715. *
  2716. * In either case, the listener's `this` value will be bound to
  2717. * this object.
  2718. *
  2719. * @param {string|Array|Function} typeOrListener
  2720. * If the first argument was a string or array, this should be the
  2721. * listener function. Otherwise, this is a string or array of event
  2722. * type(s).
  2723. *
  2724. * @param {Function} [listener]
  2725. * If the first argument was another evented object, this will be
  2726. * the listener function.
  2727. */
  2728. on: function on() {
  2729. var _this = this;
  2730. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  2731. args[_key] = arguments[_key];
  2732. }
  2733. var _normalizeListenArgs = normalizeListenArgs(this, args, 'on'),
  2734. isTargetingSelf = _normalizeListenArgs.isTargetingSelf,
  2735. target = _normalizeListenArgs.target,
  2736. type = _normalizeListenArgs.type,
  2737. listener = _normalizeListenArgs.listener;
  2738. listen(target, 'on', type, listener); // If this object is listening to another evented object.
  2739. if (!isTargetingSelf) {
  2740. // If this object is disposed, remove the listener.
  2741. var removeListenerOnDispose = function removeListenerOnDispose() {
  2742. return _this.off(target, type, listener);
  2743. }; // Use the same function ID as the listener so we can remove it later it
  2744. // using the ID of the original listener.
  2745. removeListenerOnDispose.guid = listener.guid; // Add a listener to the target's dispose event as well. This ensures
  2746. // that if the target is disposed BEFORE this object, we remove the
  2747. // removal listener that was just added. Otherwise, we create a memory leak.
  2748. var removeRemoverOnTargetDispose = function removeRemoverOnTargetDispose() {
  2749. return _this.off('dispose', removeListenerOnDispose);
  2750. }; // Use the same function ID as the listener so we can remove it later
  2751. // it using the ID of the original listener.
  2752. removeRemoverOnTargetDispose.guid = listener.guid;
  2753. listen(this, 'on', 'dispose', removeListenerOnDispose);
  2754. listen(target, 'on', 'dispose', removeRemoverOnTargetDispose);
  2755. }
  2756. },
  2757. /**
  2758. * Add a listener to an event (or events) on this object or another evented
  2759. * object. The listener will be called once per event and then removed.
  2760. *
  2761. * @param {string|Array|Element|Object} targetOrType
  2762. * If this is a string or array, it represents the event type(s)
  2763. * that will trigger the listener.
  2764. *
  2765. * Another evented object can be passed here instead, which will
  2766. * cause the listener to listen for events on _that_ object.
  2767. *
  2768. * In either case, the listener's `this` value will be bound to
  2769. * this object.
  2770. *
  2771. * @param {string|Array|Function} typeOrListener
  2772. * If the first argument was a string or array, this should be the
  2773. * listener function. Otherwise, this is a string or array of event
  2774. * type(s).
  2775. *
  2776. * @param {Function} [listener]
  2777. * If the first argument was another evented object, this will be
  2778. * the listener function.
  2779. */
  2780. one: function one() {
  2781. var _this2 = this;
  2782. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  2783. args[_key2] = arguments[_key2];
  2784. }
  2785. var _normalizeListenArgs2 = normalizeListenArgs(this, args, 'one'),
  2786. isTargetingSelf = _normalizeListenArgs2.isTargetingSelf,
  2787. target = _normalizeListenArgs2.target,
  2788. type = _normalizeListenArgs2.type,
  2789. listener = _normalizeListenArgs2.listener; // Targeting this evented object.
  2790. if (isTargetingSelf) {
  2791. listen(target, 'one', type, listener); // Targeting another evented object.
  2792. } else {
  2793. // TODO: This wrapper is incorrect! It should only
  2794. // remove the wrapper for the event type that called it.
  2795. // Instead all listners are removed on the first trigger!
  2796. // see https://github.com/videojs/video.js/issues/5962
  2797. var wrapper = function wrapper() {
  2798. _this2.off(target, type, wrapper);
  2799. for (var _len3 = arguments.length, largs = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
  2800. largs[_key3] = arguments[_key3];
  2801. }
  2802. listener.apply(null, largs);
  2803. }; // Use the same function ID as the listener so we can remove it later
  2804. // it using the ID of the original listener.
  2805. wrapper.guid = listener.guid;
  2806. listen(target, 'one', type, wrapper);
  2807. }
  2808. },
  2809. /**
  2810. * Add a listener to an event (or events) on this object or another evented
  2811. * object. The listener will only be called once for the first event that is triggered
  2812. * then removed.
  2813. *
  2814. * @param {string|Array|Element|Object} targetOrType
  2815. * If this is a string or array, it represents the event type(s)
  2816. * that will trigger the listener.
  2817. *
  2818. * Another evented object can be passed here instead, which will
  2819. * cause the listener to listen for events on _that_ object.
  2820. *
  2821. * In either case, the listener's `this` value will be bound to
  2822. * this object.
  2823. *
  2824. * @param {string|Array|Function} typeOrListener
  2825. * If the first argument was a string or array, this should be the
  2826. * listener function. Otherwise, this is a string or array of event
  2827. * type(s).
  2828. *
  2829. * @param {Function} [listener]
  2830. * If the first argument was another evented object, this will be
  2831. * the listener function.
  2832. */
  2833. any: function any() {
  2834. var _this3 = this;
  2835. for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
  2836. args[_key4] = arguments[_key4];
  2837. }
  2838. var _normalizeListenArgs3 = normalizeListenArgs(this, args, 'any'),
  2839. isTargetingSelf = _normalizeListenArgs3.isTargetingSelf,
  2840. target = _normalizeListenArgs3.target,
  2841. type = _normalizeListenArgs3.type,
  2842. listener = _normalizeListenArgs3.listener; // Targeting this evented object.
  2843. if (isTargetingSelf) {
  2844. listen(target, 'any', type, listener); // Targeting another evented object.
  2845. } else {
  2846. var wrapper = function wrapper() {
  2847. _this3.off(target, type, wrapper);
  2848. for (var _len5 = arguments.length, largs = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
  2849. largs[_key5] = arguments[_key5];
  2850. }
  2851. listener.apply(null, largs);
  2852. }; // Use the same function ID as the listener so we can remove it later
  2853. // it using the ID of the original listener.
  2854. wrapper.guid = listener.guid;
  2855. listen(target, 'any', type, wrapper);
  2856. }
  2857. },
  2858. /**
  2859. * Removes listener(s) from event(s) on an evented object.
  2860. *
  2861. * @param {string|Array|Element|Object} [targetOrType]
  2862. * If this is a string or array, it represents the event type(s).
  2863. *
  2864. * Another evented object can be passed here instead, in which case
  2865. * ALL 3 arguments are _required_.
  2866. *
  2867. * @param {string|Array|Function} [typeOrListener]
  2868. * If the first argument was a string or array, this may be the
  2869. * listener function. Otherwise, this is a string or array of event
  2870. * type(s).
  2871. *
  2872. * @param {Function} [listener]
  2873. * If the first argument was another evented object, this will be
  2874. * the listener function; otherwise, _all_ listeners bound to the
  2875. * event type(s) will be removed.
  2876. */
  2877. off: function off$1(targetOrType, typeOrListener, listener) {
  2878. // Targeting this evented object.
  2879. if (!targetOrType || isValidEventType(targetOrType)) {
  2880. off(this.eventBusEl_, targetOrType, typeOrListener); // Targeting another evented object.
  2881. } else {
  2882. var target = targetOrType;
  2883. var type = typeOrListener; // Fail fast and in a meaningful way!
  2884. validateTarget(target, this, 'off');
  2885. validateEventType(type, this, 'off');
  2886. validateListener(listener, this, 'off'); // Ensure there's at least a guid, even if the function hasn't been used
  2887. listener = bind(this, listener); // Remove the dispose listener on this evented object, which was given
  2888. // the same guid as the event listener in on().
  2889. this.off('dispose', listener);
  2890. if (target.nodeName) {
  2891. off(target, type, listener);
  2892. off(target, 'dispose', listener);
  2893. } else if (isEvented(target)) {
  2894. target.off(type, listener);
  2895. target.off('dispose', listener);
  2896. }
  2897. }
  2898. },
  2899. /**
  2900. * Fire an event on this evented object, causing its listeners to be called.
  2901. *
  2902. * @param {string|Object} event
  2903. * An event type or an object with a type property.
  2904. *
  2905. * @param {Object} [hash]
  2906. * An additional object to pass along to listeners.
  2907. *
  2908. * @return {boolean}
  2909. * Whether or not the default behavior was prevented.
  2910. */
  2911. trigger: function trigger$1(event, hash) {
  2912. validateTarget(this.eventBusEl_, this, 'trigger');
  2913. var type = event && typeof event !== 'string' ? event.type : event;
  2914. if (!isValidEventType(type)) {
  2915. var error = "Invalid event type for " + objName(this) + "#trigger; " + 'must be a non-empty string or object with a type key that has a non-empty value.';
  2916. if (event) {
  2917. (this.log || log$1).error(error);
  2918. } else {
  2919. throw new Error(error);
  2920. }
  2921. }
  2922. return trigger(this.eventBusEl_, event, hash);
  2923. }
  2924. };
  2925. /**
  2926. * Applies {@link module:evented~EventedMixin|EventedMixin} to a target object.
  2927. *
  2928. * @param {Object} target
  2929. * The object to which to add event methods.
  2930. *
  2931. * @param {Object} [options={}]
  2932. * Options for customizing the mixin behavior.
  2933. *
  2934. * @param {string} [options.eventBusKey]
  2935. * By default, adds a `eventBusEl_` DOM element to the target object,
  2936. * which is used as an event bus. If the target object already has a
  2937. * DOM element that should be used, pass its key here.
  2938. *
  2939. * @return {Object}
  2940. * The target object.
  2941. */
  2942. function evented(target, options) {
  2943. if (options === void 0) {
  2944. options = {};
  2945. }
  2946. var _options = options,
  2947. eventBusKey = _options.eventBusKey; // Set or create the eventBusEl_.
  2948. if (eventBusKey) {
  2949. if (!target[eventBusKey].nodeName) {
  2950. throw new Error("The eventBusKey \"" + eventBusKey + "\" does not refer to an element.");
  2951. }
  2952. target.eventBusEl_ = target[eventBusKey];
  2953. } else {
  2954. target.eventBusEl_ = createEl('span', {
  2955. className: 'vjs-event-bus'
  2956. });
  2957. }
  2958. assign$1(target, EventedMixin);
  2959. if (target.eventedCallbacks) {
  2960. target.eventedCallbacks.forEach(function (callback) {
  2961. callback();
  2962. });
  2963. } // When any evented object is disposed, it removes all its listeners.
  2964. target.on('dispose', function () {
  2965. target.off();
  2966. [target, target.el_, target.eventBusEl_].forEach(function (val) {
  2967. if (val && DomData.has(val)) {
  2968. DomData["delete"](val);
  2969. }
  2970. });
  2971. window.setTimeout(function () {
  2972. target.eventBusEl_ = null;
  2973. }, 0);
  2974. });
  2975. return target;
  2976. }
  2977. /**
  2978. * @file mixins/stateful.js
  2979. * @module stateful
  2980. */
  2981. /**
  2982. * Contains methods that provide statefulness to an object which is passed
  2983. * to {@link module:stateful}.
  2984. *
  2985. * @mixin StatefulMixin
  2986. */
  2987. var StatefulMixin = {
  2988. /**
  2989. * A hash containing arbitrary keys and values representing the state of
  2990. * the object.
  2991. *
  2992. * @type {Object}
  2993. */
  2994. state: {},
  2995. /**
  2996. * Set the state of an object by mutating its
  2997. * {@link module:stateful~StatefulMixin.state|state} object in place.
  2998. *
  2999. * @fires module:stateful~StatefulMixin#statechanged
  3000. * @param {Object|Function} stateUpdates
  3001. * A new set of properties to shallow-merge into the plugin state.
  3002. * Can be a plain object or a function returning a plain object.
  3003. *
  3004. * @return {Object|undefined}
  3005. * An object containing changes that occurred. If no changes
  3006. * occurred, returns `undefined`.
  3007. */
  3008. setState: function setState(stateUpdates) {
  3009. var _this = this;
  3010. // Support providing the `stateUpdates` state as a function.
  3011. if (typeof stateUpdates === 'function') {
  3012. stateUpdates = stateUpdates();
  3013. }
  3014. var changes;
  3015. each(stateUpdates, function (value, key) {
  3016. // Record the change if the value is different from what's in the
  3017. // current state.
  3018. if (_this.state[key] !== value) {
  3019. changes = changes || {};
  3020. changes[key] = {
  3021. from: _this.state[key],
  3022. to: value
  3023. };
  3024. }
  3025. _this.state[key] = value;
  3026. }); // Only trigger "statechange" if there were changes AND we have a trigger
  3027. // function. This allows us to not require that the target object be an
  3028. // evented object.
  3029. if (changes && isEvented(this)) {
  3030. /**
  3031. * An event triggered on an object that is both
  3032. * {@link module:stateful|stateful} and {@link module:evented|evented}
  3033. * indicating that its state has changed.
  3034. *
  3035. * @event module:stateful~StatefulMixin#statechanged
  3036. * @type {Object}
  3037. * @property {Object} changes
  3038. * A hash containing the properties that were changed and
  3039. * the values they were changed `from` and `to`.
  3040. */
  3041. this.trigger({
  3042. changes: changes,
  3043. type: 'statechanged'
  3044. });
  3045. }
  3046. return changes;
  3047. }
  3048. };
  3049. /**
  3050. * Applies {@link module:stateful~StatefulMixin|StatefulMixin} to a target
  3051. * object.
  3052. *
  3053. * If the target object is {@link module:evented|evented} and has a
  3054. * `handleStateChanged` method, that method will be automatically bound to the
  3055. * `statechanged` event on itself.
  3056. *
  3057. * @param {Object} target
  3058. * The object to be made stateful.
  3059. *
  3060. * @param {Object} [defaultState]
  3061. * A default set of properties to populate the newly-stateful object's
  3062. * `state` property.
  3063. *
  3064. * @return {Object}
  3065. * Returns the `target`.
  3066. */
  3067. function stateful(target, defaultState) {
  3068. assign$1(target, StatefulMixin); // This happens after the mixing-in because we need to replace the `state`
  3069. // added in that step.
  3070. target.state = assign$1({}, target.state, defaultState); // Auto-bind the `handleStateChanged` method of the target object if it exists.
  3071. if (typeof target.handleStateChanged === 'function' && isEvented(target)) {
  3072. target.on('statechanged', target.handleStateChanged);
  3073. }
  3074. return target;
  3075. }
  3076. /**
  3077. * @file string-cases.js
  3078. * @module to-lower-case
  3079. */
  3080. /**
  3081. * Lowercase the first letter of a string.
  3082. *
  3083. * @param {string} string
  3084. * String to be lowercased
  3085. *
  3086. * @return {string}
  3087. * The string with a lowercased first letter
  3088. */
  3089. var toLowerCase = function toLowerCase(string) {
  3090. if (typeof string !== 'string') {
  3091. return string;
  3092. }
  3093. return string.replace(/./, function (w) {
  3094. return w.toLowerCase();
  3095. });
  3096. };
  3097. /**
  3098. * Uppercase the first letter of a string.
  3099. *
  3100. * @param {string} string
  3101. * String to be uppercased
  3102. *
  3103. * @return {string}
  3104. * The string with an uppercased first letter
  3105. */
  3106. var toTitleCase$1 = function toTitleCase(string) {
  3107. if (typeof string !== 'string') {
  3108. return string;
  3109. }
  3110. return string.replace(/./, function (w) {
  3111. return w.toUpperCase();
  3112. });
  3113. };
  3114. /**
  3115. * Compares the TitleCase versions of the two strings for equality.
  3116. *
  3117. * @param {string} str1
  3118. * The first string to compare
  3119. *
  3120. * @param {string} str2
  3121. * The second string to compare
  3122. *
  3123. * @return {boolean}
  3124. * Whether the TitleCase versions of the strings are equal
  3125. */
  3126. var titleCaseEquals = function titleCaseEquals(str1, str2) {
  3127. return toTitleCase$1(str1) === toTitleCase$1(str2);
  3128. };
  3129. /**
  3130. * @file merge-options.js
  3131. * @module merge-options
  3132. */
  3133. /**
  3134. * Merge two objects recursively.
  3135. *
  3136. * Performs a deep merge like
  3137. * {@link https://lodash.com/docs/4.17.10#merge|lodash.merge}, but only merges
  3138. * plain objects (not arrays, elements, or anything else).
  3139. *
  3140. * Non-plain object values will be copied directly from the right-most
  3141. * argument.
  3142. *
  3143. * @static
  3144. * @param {Object[]} sources
  3145. * One or more objects to merge into a new object.
  3146. *
  3147. * @return {Object}
  3148. * A new object that is the merged result of all sources.
  3149. */
  3150. function mergeOptions$3() {
  3151. var result = {};
  3152. for (var _len = arguments.length, sources = new Array(_len), _key = 0; _key < _len; _key++) {
  3153. sources[_key] = arguments[_key];
  3154. }
  3155. sources.forEach(function (source) {
  3156. if (!source) {
  3157. return;
  3158. }
  3159. each(source, function (value, key) {
  3160. if (!isPlain(value)) {
  3161. result[key] = value;
  3162. return;
  3163. }
  3164. if (!isPlain(result[key])) {
  3165. result[key] = {};
  3166. }
  3167. result[key] = mergeOptions$3(result[key], value);
  3168. });
  3169. });
  3170. return result;
  3171. }
  3172. var MapSham = /*#__PURE__*/function () {
  3173. function MapSham() {
  3174. this.map_ = {};
  3175. }
  3176. var _proto = MapSham.prototype;
  3177. _proto.has = function has(key) {
  3178. return key in this.map_;
  3179. };
  3180. _proto["delete"] = function _delete(key) {
  3181. var has = this.has(key);
  3182. delete this.map_[key];
  3183. return has;
  3184. };
  3185. _proto.set = function set(key, value) {
  3186. this.map_[key] = value;
  3187. return this;
  3188. };
  3189. _proto.forEach = function forEach(callback, thisArg) {
  3190. for (var key in this.map_) {
  3191. callback.call(thisArg, this.map_[key], key, this);
  3192. }
  3193. };
  3194. return MapSham;
  3195. }();
  3196. var Map$1 = window.Map ? window.Map : MapSham;
  3197. var SetSham = /*#__PURE__*/function () {
  3198. function SetSham() {
  3199. this.set_ = {};
  3200. }
  3201. var _proto = SetSham.prototype;
  3202. _proto.has = function has(key) {
  3203. return key in this.set_;
  3204. };
  3205. _proto["delete"] = function _delete(key) {
  3206. var has = this.has(key);
  3207. delete this.set_[key];
  3208. return has;
  3209. };
  3210. _proto.add = function add(key) {
  3211. this.set_[key] = 1;
  3212. return this;
  3213. };
  3214. _proto.forEach = function forEach(callback, thisArg) {
  3215. for (var key in this.set_) {
  3216. callback.call(thisArg, key, key, this);
  3217. }
  3218. };
  3219. return SetSham;
  3220. }();
  3221. var Set$1 = window.Set ? window.Set : SetSham;
  3222. var keycode = createCommonjsModule(function (module, exports) {
  3223. // Source: http://jsfiddle.net/vWx8V/
  3224. // http://stackoverflow.com/questions/5603195/full-list-of-javascript-keycodes
  3225. /**
  3226. * Conenience method returns corresponding value for given keyName or keyCode.
  3227. *
  3228. * @param {Mixed} keyCode {Number} or keyName {String}
  3229. * @return {Mixed}
  3230. * @api public
  3231. */
  3232. function keyCode(searchInput) {
  3233. // Keyboard Events
  3234. if (searchInput && 'object' === typeof searchInput) {
  3235. var hasKeyCode = searchInput.which || searchInput.keyCode || searchInput.charCode;
  3236. if (hasKeyCode) searchInput = hasKeyCode;
  3237. } // Numbers
  3238. if ('number' === typeof searchInput) return names[searchInput]; // Everything else (cast to string)
  3239. var search = String(searchInput); // check codes
  3240. var foundNamedKey = codes[search.toLowerCase()];
  3241. if (foundNamedKey) return foundNamedKey; // check aliases
  3242. var foundNamedKey = aliases[search.toLowerCase()];
  3243. if (foundNamedKey) return foundNamedKey; // weird character?
  3244. if (search.length === 1) return search.charCodeAt(0);
  3245. return undefined;
  3246. }
  3247. /**
  3248. * Compares a keyboard event with a given keyCode or keyName.
  3249. *
  3250. * @param {Event} event Keyboard event that should be tested
  3251. * @param {Mixed} keyCode {Number} or keyName {String}
  3252. * @return {Boolean}
  3253. * @api public
  3254. */
  3255. keyCode.isEventKey = function isEventKey(event, nameOrCode) {
  3256. if (event && 'object' === typeof event) {
  3257. var keyCode = event.which || event.keyCode || event.charCode;
  3258. if (keyCode === null || keyCode === undefined) {
  3259. return false;
  3260. }
  3261. if (typeof nameOrCode === 'string') {
  3262. // check codes
  3263. var foundNamedKey = codes[nameOrCode.toLowerCase()];
  3264. if (foundNamedKey) {
  3265. return foundNamedKey === keyCode;
  3266. } // check aliases
  3267. var foundNamedKey = aliases[nameOrCode.toLowerCase()];
  3268. if (foundNamedKey) {
  3269. return foundNamedKey === keyCode;
  3270. }
  3271. } else if (typeof nameOrCode === 'number') {
  3272. return nameOrCode === keyCode;
  3273. }
  3274. return false;
  3275. }
  3276. };
  3277. exports = module.exports = keyCode;
  3278. /**
  3279. * Get by name
  3280. *
  3281. * exports.code['enter'] // => 13
  3282. */
  3283. var codes = exports.code = exports.codes = {
  3284. 'backspace': 8,
  3285. 'tab': 9,
  3286. 'enter': 13,
  3287. 'shift': 16,
  3288. 'ctrl': 17,
  3289. 'alt': 18,
  3290. 'pause/break': 19,
  3291. 'caps lock': 20,
  3292. 'esc': 27,
  3293. 'space': 32,
  3294. 'page up': 33,
  3295. 'page down': 34,
  3296. 'end': 35,
  3297. 'home': 36,
  3298. 'left': 37,
  3299. 'up': 38,
  3300. 'right': 39,
  3301. 'down': 40,
  3302. 'insert': 45,
  3303. 'delete': 46,
  3304. 'command': 91,
  3305. 'left command': 91,
  3306. 'right command': 93,
  3307. 'numpad *': 106,
  3308. 'numpad +': 107,
  3309. 'numpad -': 109,
  3310. 'numpad .': 110,
  3311. 'numpad /': 111,
  3312. 'num lock': 144,
  3313. 'scroll lock': 145,
  3314. 'my computer': 182,
  3315. 'my calculator': 183,
  3316. ';': 186,
  3317. '=': 187,
  3318. ',': 188,
  3319. '-': 189,
  3320. '.': 190,
  3321. '/': 191,
  3322. '`': 192,
  3323. '[': 219,
  3324. '\\': 220,
  3325. ']': 221,
  3326. "'": 222
  3327. }; // Helper aliases
  3328. var aliases = exports.aliases = {
  3329. 'windows': 91,
  3330. '⇧': 16,
  3331. '⌥': 18,
  3332. '⌃': 17,
  3333. '⌘': 91,
  3334. 'ctl': 17,
  3335. 'control': 17,
  3336. 'option': 18,
  3337. 'pause': 19,
  3338. 'break': 19,
  3339. 'caps': 20,
  3340. 'return': 13,
  3341. 'escape': 27,
  3342. 'spc': 32,
  3343. 'spacebar': 32,
  3344. 'pgup': 33,
  3345. 'pgdn': 34,
  3346. 'ins': 45,
  3347. 'del': 46,
  3348. 'cmd': 91
  3349. };
  3350. /*!
  3351. * Programatically add the following
  3352. */
  3353. // lower case chars
  3354. for (i = 97; i < 123; i++) {
  3355. codes[String.fromCharCode(i)] = i - 32;
  3356. } // numbers
  3357. for (var i = 48; i < 58; i++) {
  3358. codes[i - 48] = i;
  3359. } // function keys
  3360. for (i = 1; i < 13; i++) {
  3361. codes['f' + i] = i + 111;
  3362. } // numpad keys
  3363. for (i = 0; i < 10; i++) {
  3364. codes['numpad ' + i] = i + 96;
  3365. }
  3366. /**
  3367. * Get by code
  3368. *
  3369. * exports.name[13] // => 'Enter'
  3370. */
  3371. var names = exports.names = exports.title = {}; // title for backward compat
  3372. // Create reverse mapping
  3373. for (i in codes) {
  3374. names[codes[i]] = i;
  3375. } // Add aliases
  3376. for (var alias in aliases) {
  3377. codes[alias] = aliases[alias];
  3378. }
  3379. });
  3380. keycode.code;
  3381. keycode.codes;
  3382. keycode.aliases;
  3383. keycode.names;
  3384. keycode.title;
  3385. /**
  3386. * Player Component - Base class for all UI objects
  3387. *
  3388. * @file component.js
  3389. */
  3390. /**
  3391. * Base class for all UI Components.
  3392. * Components are UI objects which represent both a javascript object and an element
  3393. * in the DOM. They can be children of other components, and can have
  3394. * children themselves.
  3395. *
  3396. * Components can also use methods from {@link EventTarget}
  3397. */
  3398. var Component$1 = /*#__PURE__*/function () {
  3399. /**
  3400. * A callback that is called when a component is ready. Does not have any
  3401. * paramters and any callback value will be ignored.
  3402. *
  3403. * @callback Component~ReadyCallback
  3404. * @this Component
  3405. */
  3406. /**
  3407. * Creates an instance of this class.
  3408. *
  3409. * @param {Player} player
  3410. * The `Player` that this class should be attached to.
  3411. *
  3412. * @param {Object} [options]
  3413. * The key/value store of component options.
  3414. *
  3415. * @param {Object[]} [options.children]
  3416. * An array of children objects to intialize this component with. Children objects have
  3417. * a name property that will be used if more than one component of the same type needs to be
  3418. * added.
  3419. *
  3420. * @param {string} [options.className]
  3421. * A class or space separated list of classes to add the component
  3422. *
  3423. * @param {Component~ReadyCallback} [ready]
  3424. * Function that gets called when the `Component` is ready.
  3425. */
  3426. function Component(player, options, ready) {
  3427. var _this = this;
  3428. // The component might be the player itself and we can't pass `this` to super
  3429. if (!player && this.play) {
  3430. this.player_ = player = this; // eslint-disable-line
  3431. } else {
  3432. this.player_ = player;
  3433. }
  3434. this.isDisposed_ = false; // Hold the reference to the parent component via `addChild` method
  3435. this.parentComponent_ = null; // Make a copy of prototype.options_ to protect against overriding defaults
  3436. this.options_ = mergeOptions$3({}, this.options_); // Updated options with supplied options
  3437. options = this.options_ = mergeOptions$3(this.options_, options); // Get ID from options or options element if one is supplied
  3438. this.id_ = options.id || options.el && options.el.id; // If there was no ID from the options, generate one
  3439. if (!this.id_) {
  3440. // Don't require the player ID function in the case of mock players
  3441. var id = player && player.id && player.id() || 'no_player';
  3442. this.id_ = id + "_component_" + newGUID();
  3443. }
  3444. this.name_ = options.name || null; // Create element if one wasn't provided in options
  3445. if (options.el) {
  3446. this.el_ = options.el;
  3447. } else if (options.createEl !== false) {
  3448. this.el_ = this.createEl();
  3449. }
  3450. if (options.className && this.el_) {
  3451. options.className.split(' ').forEach(function (c) {
  3452. return _this.addClass(c);
  3453. });
  3454. } // if evented is anything except false, we want to mixin in evented
  3455. if (options.evented !== false) {
  3456. // Make this an evented object and use `el_`, if available, as its event bus
  3457. evented(this, {
  3458. eventBusKey: this.el_ ? 'el_' : null
  3459. });
  3460. this.handleLanguagechange = this.handleLanguagechange.bind(this);
  3461. this.on(this.player_, 'languagechange', this.handleLanguagechange);
  3462. }
  3463. stateful(this, this.constructor.defaultState);
  3464. this.children_ = [];
  3465. this.childIndex_ = {};
  3466. this.childNameIndex_ = {};
  3467. this.setTimeoutIds_ = new Set$1();
  3468. this.setIntervalIds_ = new Set$1();
  3469. this.rafIds_ = new Set$1();
  3470. this.namedRafs_ = new Map$1();
  3471. this.clearingTimersOnDispose_ = false; // Add any child components in options
  3472. if (options.initChildren !== false) {
  3473. this.initChildren();
  3474. } // Don't want to trigger ready here or it will go before init is actually
  3475. // finished for all children that run this constructor
  3476. this.ready(ready);
  3477. if (options.reportTouchActivity !== false) {
  3478. this.enableTouchActivity();
  3479. }
  3480. }
  3481. /**
  3482. * Dispose of the `Component` and all child components.
  3483. *
  3484. * @fires Component#dispose
  3485. *
  3486. * @param {Object} options
  3487. * @param {Element} options.originalEl element with which to replace player element
  3488. */
  3489. var _proto = Component.prototype;
  3490. _proto.dispose = function dispose(options) {
  3491. if (options === void 0) {
  3492. options = {};
  3493. }
  3494. // Bail out if the component has already been disposed.
  3495. if (this.isDisposed_) {
  3496. return;
  3497. }
  3498. if (this.readyQueue_) {
  3499. this.readyQueue_.length = 0;
  3500. }
  3501. /**
  3502. * Triggered when a `Component` is disposed.
  3503. *
  3504. * @event Component#dispose
  3505. * @type {EventTarget~Event}
  3506. *
  3507. * @property {boolean} [bubbles=false]
  3508. * set to false so that the dispose event does not
  3509. * bubble up
  3510. */
  3511. this.trigger({
  3512. type: 'dispose',
  3513. bubbles: false
  3514. });
  3515. this.isDisposed_ = true; // Dispose all children.
  3516. if (this.children_) {
  3517. for (var i = this.children_.length - 1; i >= 0; i--) {
  3518. if (this.children_[i].dispose) {
  3519. this.children_[i].dispose();
  3520. }
  3521. }
  3522. } // Delete child references
  3523. this.children_ = null;
  3524. this.childIndex_ = null;
  3525. this.childNameIndex_ = null;
  3526. this.parentComponent_ = null;
  3527. if (this.el_) {
  3528. // Remove element from DOM
  3529. if (this.el_.parentNode) {
  3530. if (options.restoreEl) {
  3531. this.el_.parentNode.replaceChild(options.restoreEl, this.el_);
  3532. } else {
  3533. this.el_.parentNode.removeChild(this.el_);
  3534. }
  3535. }
  3536. this.el_ = null;
  3537. } // remove reference to the player after disposing of the element
  3538. this.player_ = null;
  3539. }
  3540. /**
  3541. * Determine whether or not this component has been disposed.
  3542. *
  3543. * @return {boolean}
  3544. * If the component has been disposed, will be `true`. Otherwise, `false`.
  3545. */
  3546. ;
  3547. _proto.isDisposed = function isDisposed() {
  3548. return Boolean(this.isDisposed_);
  3549. }
  3550. /**
  3551. * Return the {@link Player} that the `Component` has attached to.
  3552. *
  3553. * @return {Player}
  3554. * The player that this `Component` has attached to.
  3555. */
  3556. ;
  3557. _proto.player = function player() {
  3558. return this.player_;
  3559. }
  3560. /**
  3561. * Deep merge of options objects with new options.
  3562. * > Note: When both `obj` and `options` contain properties whose values are objects.
  3563. * The two properties get merged using {@link module:mergeOptions}
  3564. *
  3565. * @param {Object} obj
  3566. * The object that contains new options.
  3567. *
  3568. * @return {Object}
  3569. * A new object of `this.options_` and `obj` merged together.
  3570. */
  3571. ;
  3572. _proto.options = function options(obj) {
  3573. if (!obj) {
  3574. return this.options_;
  3575. }
  3576. this.options_ = mergeOptions$3(this.options_, obj);
  3577. return this.options_;
  3578. }
  3579. /**
  3580. * Get the `Component`s DOM element
  3581. *
  3582. * @return {Element}
  3583. * The DOM element for this `Component`.
  3584. */
  3585. ;
  3586. _proto.el = function el() {
  3587. return this.el_;
  3588. }
  3589. /**
  3590. * Create the `Component`s DOM element.
  3591. *
  3592. * @param {string} [tagName]
  3593. * Element's DOM node type. e.g. 'div'
  3594. *
  3595. * @param {Object} [properties]
  3596. * An object of properties that should be set.
  3597. *
  3598. * @param {Object} [attributes]
  3599. * An object of attributes that should be set.
  3600. *
  3601. * @return {Element}
  3602. * The element that gets created.
  3603. */
  3604. ;
  3605. _proto.createEl = function createEl$1(tagName, properties, attributes) {
  3606. return createEl(tagName, properties, attributes);
  3607. }
  3608. /**
  3609. * Localize a string given the string in english.
  3610. *
  3611. * If tokens are provided, it'll try and run a simple token replacement on the provided string.
  3612. * The tokens it looks for look like `{1}` with the index being 1-indexed into the tokens array.
  3613. *
  3614. * If a `defaultValue` is provided, it'll use that over `string`,
  3615. * if a value isn't found in provided language files.
  3616. * This is useful if you want to have a descriptive key for token replacement
  3617. * but have a succinct localized string and not require `en.json` to be included.
  3618. *
  3619. * Currently, it is used for the progress bar timing.
  3620. * ```js
  3621. * {
  3622. * "progress bar timing: currentTime={1} duration={2}": "{1} of {2}"
  3623. * }
  3624. * ```
  3625. * It is then used like so:
  3626. * ```js
  3627. * this.localize('progress bar timing: currentTime={1} duration{2}',
  3628. * [this.player_.currentTime(), this.player_.duration()],
  3629. * '{1} of {2}');
  3630. * ```
  3631. *
  3632. * Which outputs something like: `01:23 of 24:56`.
  3633. *
  3634. *
  3635. * @param {string} string
  3636. * The string to localize and the key to lookup in the language files.
  3637. * @param {string[]} [tokens]
  3638. * If the current item has token replacements, provide the tokens here.
  3639. * @param {string} [defaultValue]
  3640. * Defaults to `string`. Can be a default value to use for token replacement
  3641. * if the lookup key is needed to be separate.
  3642. *
  3643. * @return {string}
  3644. * The localized string or if no localization exists the english string.
  3645. */
  3646. ;
  3647. _proto.localize = function localize(string, tokens, defaultValue) {
  3648. if (defaultValue === void 0) {
  3649. defaultValue = string;
  3650. }
  3651. var code = this.player_.language && this.player_.language();
  3652. var languages = this.player_.languages && this.player_.languages();
  3653. var language = languages && languages[code];
  3654. var primaryCode = code && code.split('-')[0];
  3655. var primaryLang = languages && languages[primaryCode];
  3656. var localizedString = defaultValue;
  3657. if (language && language[string]) {
  3658. localizedString = language[string];
  3659. } else if (primaryLang && primaryLang[string]) {
  3660. localizedString = primaryLang[string];
  3661. }
  3662. if (tokens) {
  3663. localizedString = localizedString.replace(/\{(\d+)\}/g, function (match, index) {
  3664. var value = tokens[index - 1];
  3665. var ret = value;
  3666. if (typeof value === 'undefined') {
  3667. ret = match;
  3668. }
  3669. return ret;
  3670. });
  3671. }
  3672. return localizedString;
  3673. }
  3674. /**
  3675. * Handles language change for the player in components. Should be overriden by sub-components.
  3676. *
  3677. * @abstract
  3678. */
  3679. ;
  3680. _proto.handleLanguagechange = function handleLanguagechange() {}
  3681. /**
  3682. * Return the `Component`s DOM element. This is where children get inserted.
  3683. * This will usually be the the same as the element returned in {@link Component#el}.
  3684. *
  3685. * @return {Element}
  3686. * The content element for this `Component`.
  3687. */
  3688. ;
  3689. _proto.contentEl = function contentEl() {
  3690. return this.contentEl_ || this.el_;
  3691. }
  3692. /**
  3693. * Get this `Component`s ID
  3694. *
  3695. * @return {string}
  3696. * The id of this `Component`
  3697. */
  3698. ;
  3699. _proto.id = function id() {
  3700. return this.id_;
  3701. }
  3702. /**
  3703. * Get the `Component`s name. The name gets used to reference the `Component`
  3704. * and is set during registration.
  3705. *
  3706. * @return {string}
  3707. * The name of this `Component`.
  3708. */
  3709. ;
  3710. _proto.name = function name() {
  3711. return this.name_;
  3712. }
  3713. /**
  3714. * Get an array of all child components
  3715. *
  3716. * @return {Array}
  3717. * The children
  3718. */
  3719. ;
  3720. _proto.children = function children() {
  3721. return this.children_;
  3722. }
  3723. /**
  3724. * Returns the child `Component` with the given `id`.
  3725. *
  3726. * @param {string} id
  3727. * The id of the child `Component` to get.
  3728. *
  3729. * @return {Component|undefined}
  3730. * The child `Component` with the given `id` or undefined.
  3731. */
  3732. ;
  3733. _proto.getChildById = function getChildById(id) {
  3734. return this.childIndex_[id];
  3735. }
  3736. /**
  3737. * Returns the child `Component` with the given `name`.
  3738. *
  3739. * @param {string} name
  3740. * The name of the child `Component` to get.
  3741. *
  3742. * @return {Component|undefined}
  3743. * The child `Component` with the given `name` or undefined.
  3744. */
  3745. ;
  3746. _proto.getChild = function getChild(name) {
  3747. if (!name) {
  3748. return;
  3749. }
  3750. return this.childNameIndex_[name];
  3751. }
  3752. /**
  3753. * Returns the descendant `Component` following the givent
  3754. * descendant `names`. For instance ['foo', 'bar', 'baz'] would
  3755. * try to get 'foo' on the current component, 'bar' on the 'foo'
  3756. * component and 'baz' on the 'bar' component and return undefined
  3757. * if any of those don't exist.
  3758. *
  3759. * @param {...string[]|...string} names
  3760. * The name of the child `Component` to get.
  3761. *
  3762. * @return {Component|undefined}
  3763. * The descendant `Component` following the given descendant
  3764. * `names` or undefined.
  3765. */
  3766. ;
  3767. _proto.getDescendant = function getDescendant() {
  3768. for (var _len = arguments.length, names = new Array(_len), _key = 0; _key < _len; _key++) {
  3769. names[_key] = arguments[_key];
  3770. }
  3771. // flatten array argument into the main array
  3772. names = names.reduce(function (acc, n) {
  3773. return acc.concat(n);
  3774. }, []);
  3775. var currentChild = this;
  3776. for (var i = 0; i < names.length; i++) {
  3777. currentChild = currentChild.getChild(names[i]);
  3778. if (!currentChild || !currentChild.getChild) {
  3779. return;
  3780. }
  3781. }
  3782. return currentChild;
  3783. }
  3784. /**
  3785. * Add a child `Component` inside the current `Component`.
  3786. *
  3787. *
  3788. * @param {string|Component} child
  3789. * The name or instance of a child to add.
  3790. *
  3791. * @param {Object} [options={}]
  3792. * The key/value store of options that will get passed to children of
  3793. * the child.
  3794. *
  3795. * @param {number} [index=this.children_.length]
  3796. * The index to attempt to add a child into.
  3797. *
  3798. * @return {Component}
  3799. * The `Component` that gets added as a child. When using a string the
  3800. * `Component` will get created by this process.
  3801. */
  3802. ;
  3803. _proto.addChild = function addChild(child, options, index) {
  3804. if (options === void 0) {
  3805. options = {};
  3806. }
  3807. if (index === void 0) {
  3808. index = this.children_.length;
  3809. }
  3810. var component;
  3811. var componentName; // If child is a string, create component with options
  3812. if (typeof child === 'string') {
  3813. componentName = toTitleCase$1(child);
  3814. var componentClassName = options.componentClass || componentName; // Set name through options
  3815. options.name = componentName; // Create a new object & element for this controls set
  3816. // If there's no .player_, this is a player
  3817. var ComponentClass = Component.getComponent(componentClassName);
  3818. if (!ComponentClass) {
  3819. throw new Error("Component " + componentClassName + " does not exist");
  3820. } // data stored directly on the videojs object may be
  3821. // misidentified as a component to retain
  3822. // backwards-compatibility with 4.x. check to make sure the
  3823. // component class can be instantiated.
  3824. if (typeof ComponentClass !== 'function') {
  3825. return null;
  3826. }
  3827. component = new ComponentClass(this.player_ || this, options); // child is a component instance
  3828. } else {
  3829. component = child;
  3830. }
  3831. if (component.parentComponent_) {
  3832. component.parentComponent_.removeChild(component);
  3833. }
  3834. this.children_.splice(index, 0, component);
  3835. component.parentComponent_ = this;
  3836. if (typeof component.id === 'function') {
  3837. this.childIndex_[component.id()] = component;
  3838. } // If a name wasn't used to create the component, check if we can use the
  3839. // name function of the component
  3840. componentName = componentName || component.name && toTitleCase$1(component.name());
  3841. if (componentName) {
  3842. this.childNameIndex_[componentName] = component;
  3843. this.childNameIndex_[toLowerCase(componentName)] = component;
  3844. } // Add the UI object's element to the container div (box)
  3845. // Having an element is not required
  3846. if (typeof component.el === 'function' && component.el()) {
  3847. // If inserting before a component, insert before that component's element
  3848. var refNode = null;
  3849. if (this.children_[index + 1]) {
  3850. // Most children are components, but the video tech is an HTML element
  3851. if (this.children_[index + 1].el_) {
  3852. refNode = this.children_[index + 1].el_;
  3853. } else if (isEl(this.children_[index + 1])) {
  3854. refNode = this.children_[index + 1];
  3855. }
  3856. }
  3857. this.contentEl().insertBefore(component.el(), refNode);
  3858. } // Return so it can stored on parent object if desired.
  3859. return component;
  3860. }
  3861. /**
  3862. * Remove a child `Component` from this `Component`s list of children. Also removes
  3863. * the child `Component`s element from this `Component`s element.
  3864. *
  3865. * @param {Component} component
  3866. * The child `Component` to remove.
  3867. */
  3868. ;
  3869. _proto.removeChild = function removeChild(component) {
  3870. if (typeof component === 'string') {
  3871. component = this.getChild(component);
  3872. }
  3873. if (!component || !this.children_) {
  3874. return;
  3875. }
  3876. var childFound = false;
  3877. for (var i = this.children_.length - 1; i >= 0; i--) {
  3878. if (this.children_[i] === component) {
  3879. childFound = true;
  3880. this.children_.splice(i, 1);
  3881. break;
  3882. }
  3883. }
  3884. if (!childFound) {
  3885. return;
  3886. }
  3887. component.parentComponent_ = null;
  3888. this.childIndex_[component.id()] = null;
  3889. this.childNameIndex_[toTitleCase$1(component.name())] = null;
  3890. this.childNameIndex_[toLowerCase(component.name())] = null;
  3891. var compEl = component.el();
  3892. if (compEl && compEl.parentNode === this.contentEl()) {
  3893. this.contentEl().removeChild(component.el());
  3894. }
  3895. }
  3896. /**
  3897. * Add and initialize default child `Component`s based upon options.
  3898. */
  3899. ;
  3900. _proto.initChildren = function initChildren() {
  3901. var _this2 = this;
  3902. var children = this.options_.children;
  3903. if (children) {
  3904. // `this` is `parent`
  3905. var parentOptions = this.options_;
  3906. var handleAdd = function handleAdd(child) {
  3907. var name = child.name;
  3908. var opts = child.opts; // Allow options for children to be set at the parent options
  3909. // e.g. videojs(id, { controlBar: false });
  3910. // instead of videojs(id, { children: { controlBar: false });
  3911. if (parentOptions[name] !== undefined) {
  3912. opts = parentOptions[name];
  3913. } // Allow for disabling default components
  3914. // e.g. options['children']['posterImage'] = false
  3915. if (opts === false) {
  3916. return;
  3917. } // Allow options to be passed as a simple boolean if no configuration
  3918. // is necessary.
  3919. if (opts === true) {
  3920. opts = {};
  3921. } // We also want to pass the original player options
  3922. // to each component as well so they don't need to
  3923. // reach back into the player for options later.
  3924. opts.playerOptions = _this2.options_.playerOptions; // Create and add the child component.
  3925. // Add a direct reference to the child by name on the parent instance.
  3926. // If two of the same component are used, different names should be supplied
  3927. // for each
  3928. var newChild = _this2.addChild(name, opts);
  3929. if (newChild) {
  3930. _this2[name] = newChild;
  3931. }
  3932. }; // Allow for an array of children details to passed in the options
  3933. var workingChildren;
  3934. var Tech = Component.getComponent('Tech');
  3935. if (Array.isArray(children)) {
  3936. workingChildren = children;
  3937. } else {
  3938. workingChildren = Object.keys(children);
  3939. }
  3940. workingChildren // children that are in this.options_ but also in workingChildren would
  3941. // give us extra children we do not want. So, we want to filter them out.
  3942. .concat(Object.keys(this.options_).filter(function (child) {
  3943. return !workingChildren.some(function (wchild) {
  3944. if (typeof wchild === 'string') {
  3945. return child === wchild;
  3946. }
  3947. return child === wchild.name;
  3948. });
  3949. })).map(function (child) {
  3950. var name;
  3951. var opts;
  3952. if (typeof child === 'string') {
  3953. name = child;
  3954. opts = children[name] || _this2.options_[name] || {};
  3955. } else {
  3956. name = child.name;
  3957. opts = child;
  3958. }
  3959. return {
  3960. name: name,
  3961. opts: opts
  3962. };
  3963. }).filter(function (child) {
  3964. // we have to make sure that child.name isn't in the techOrder since
  3965. // techs are registerd as Components but can't aren't compatible
  3966. // See https://github.com/videojs/video.js/issues/2772
  3967. var c = Component.getComponent(child.opts.componentClass || toTitleCase$1(child.name));
  3968. return c && !Tech.isTech(c);
  3969. }).forEach(handleAdd);
  3970. }
  3971. }
  3972. /**
  3973. * Builds the default DOM class name. Should be overriden by sub-components.
  3974. *
  3975. * @return {string}
  3976. * The DOM class name for this object.
  3977. *
  3978. * @abstract
  3979. */
  3980. ;
  3981. _proto.buildCSSClass = function buildCSSClass() {
  3982. // Child classes can include a function that does:
  3983. // return 'CLASS NAME' + this._super();
  3984. return '';
  3985. }
  3986. /**
  3987. * Bind a listener to the component's ready state.
  3988. * Different from event listeners in that if the ready event has already happened
  3989. * it will trigger the function immediately.
  3990. *
  3991. * @return {Component}
  3992. * Returns itself; method can be chained.
  3993. */
  3994. ;
  3995. _proto.ready = function ready(fn, sync) {
  3996. if (sync === void 0) {
  3997. sync = false;
  3998. }
  3999. if (!fn) {
  4000. return;
  4001. }
  4002. if (!this.isReady_) {
  4003. this.readyQueue_ = this.readyQueue_ || [];
  4004. this.readyQueue_.push(fn);
  4005. return;
  4006. }
  4007. if (sync) {
  4008. fn.call(this);
  4009. } else {
  4010. // Call the function asynchronously by default for consistency
  4011. this.setTimeout(fn, 1);
  4012. }
  4013. }
  4014. /**
  4015. * Trigger all the ready listeners for this `Component`.
  4016. *
  4017. * @fires Component#ready
  4018. */
  4019. ;
  4020. _proto.triggerReady = function triggerReady() {
  4021. this.isReady_ = true; // Ensure ready is triggered asynchronously
  4022. this.setTimeout(function () {
  4023. var readyQueue = this.readyQueue_; // Reset Ready Queue
  4024. this.readyQueue_ = [];
  4025. if (readyQueue && readyQueue.length > 0) {
  4026. readyQueue.forEach(function (fn) {
  4027. fn.call(this);
  4028. }, this);
  4029. } // Allow for using event listeners also
  4030. /**
  4031. * Triggered when a `Component` is ready.
  4032. *
  4033. * @event Component#ready
  4034. * @type {EventTarget~Event}
  4035. */
  4036. this.trigger('ready');
  4037. }, 1);
  4038. }
  4039. /**
  4040. * Find a single DOM element matching a `selector`. This can be within the `Component`s
  4041. * `contentEl()` or another custom context.
  4042. *
  4043. * @param {string} selector
  4044. * A valid CSS selector, which will be passed to `querySelector`.
  4045. *
  4046. * @param {Element|string} [context=this.contentEl()]
  4047. * A DOM element within which to query. Can also be a selector string in
  4048. * which case the first matching element will get used as context. If
  4049. * missing `this.contentEl()` gets used. If `this.contentEl()` returns
  4050. * nothing it falls back to `document`.
  4051. *
  4052. * @return {Element|null}
  4053. * the dom element that was found, or null
  4054. *
  4055. * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)
  4056. */
  4057. ;
  4058. _proto.$ = function $$1(selector, context) {
  4059. return $(selector, context || this.contentEl());
  4060. }
  4061. /**
  4062. * Finds all DOM element matching a `selector`. This can be within the `Component`s
  4063. * `contentEl()` or another custom context.
  4064. *
  4065. * @param {string} selector
  4066. * A valid CSS selector, which will be passed to `querySelectorAll`.
  4067. *
  4068. * @param {Element|string} [context=this.contentEl()]
  4069. * A DOM element within which to query. Can also be a selector string in
  4070. * which case the first matching element will get used as context. If
  4071. * missing `this.contentEl()` gets used. If `this.contentEl()` returns
  4072. * nothing it falls back to `document`.
  4073. *
  4074. * @return {NodeList}
  4075. * a list of dom elements that were found
  4076. *
  4077. * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors)
  4078. */
  4079. ;
  4080. _proto.$$ = function $$$1(selector, context) {
  4081. return $$(selector, context || this.contentEl());
  4082. }
  4083. /**
  4084. * Check if a component's element has a CSS class name.
  4085. *
  4086. * @param {string} classToCheck
  4087. * CSS class name to check.
  4088. *
  4089. * @return {boolean}
  4090. * - True if the `Component` has the class.
  4091. * - False if the `Component` does not have the class`
  4092. */
  4093. ;
  4094. _proto.hasClass = function hasClass$1(classToCheck) {
  4095. return hasClass(this.el_, classToCheck);
  4096. }
  4097. /**
  4098. * Add a CSS class name to the `Component`s element.
  4099. *
  4100. * @param {string} classToAdd
  4101. * CSS class name to add
  4102. */
  4103. ;
  4104. _proto.addClass = function addClass$1(classToAdd) {
  4105. addClass(this.el_, classToAdd);
  4106. }
  4107. /**
  4108. * Remove a CSS class name from the `Component`s element.
  4109. *
  4110. * @param {string} classToRemove
  4111. * CSS class name to remove
  4112. */
  4113. ;
  4114. _proto.removeClass = function removeClass$1(classToRemove) {
  4115. removeClass(this.el_, classToRemove);
  4116. }
  4117. /**
  4118. * Add or remove a CSS class name from the component's element.
  4119. * - `classToToggle` gets added when {@link Component#hasClass} would return false.
  4120. * - `classToToggle` gets removed when {@link Component#hasClass} would return true.
  4121. *
  4122. * @param {string} classToToggle
  4123. * The class to add or remove based on (@link Component#hasClass}
  4124. *
  4125. * @param {boolean|Dom~predicate} [predicate]
  4126. * An {@link Dom~predicate} function or a boolean
  4127. */
  4128. ;
  4129. _proto.toggleClass = function toggleClass$1(classToToggle, predicate) {
  4130. toggleClass(this.el_, classToToggle, predicate);
  4131. }
  4132. /**
  4133. * Show the `Component`s element if it is hidden by removing the
  4134. * 'vjs-hidden' class name from it.
  4135. */
  4136. ;
  4137. _proto.show = function show() {
  4138. this.removeClass('vjs-hidden');
  4139. }
  4140. /**
  4141. * Hide the `Component`s element if it is currently showing by adding the
  4142. * 'vjs-hidden` class name to it.
  4143. */
  4144. ;
  4145. _proto.hide = function hide() {
  4146. this.addClass('vjs-hidden');
  4147. }
  4148. /**
  4149. * Lock a `Component`s element in its visible state by adding the 'vjs-lock-showing'
  4150. * class name to it. Used during fadeIn/fadeOut.
  4151. *
  4152. * @private
  4153. */
  4154. ;
  4155. _proto.lockShowing = function lockShowing() {
  4156. this.addClass('vjs-lock-showing');
  4157. }
  4158. /**
  4159. * Unlock a `Component`s element from its visible state by removing the 'vjs-lock-showing'
  4160. * class name from it. Used during fadeIn/fadeOut.
  4161. *
  4162. * @private
  4163. */
  4164. ;
  4165. _proto.unlockShowing = function unlockShowing() {
  4166. this.removeClass('vjs-lock-showing');
  4167. }
  4168. /**
  4169. * Get the value of an attribute on the `Component`s element.
  4170. *
  4171. * @param {string} attribute
  4172. * Name of the attribute to get the value from.
  4173. *
  4174. * @return {string|null}
  4175. * - The value of the attribute that was asked for.
  4176. * - Can be an empty string on some browsers if the attribute does not exist
  4177. * or has no value
  4178. * - Most browsers will return null if the attibute does not exist or has
  4179. * no value.
  4180. *
  4181. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute}
  4182. */
  4183. ;
  4184. _proto.getAttribute = function getAttribute$1(attribute) {
  4185. return getAttribute(this.el_, attribute);
  4186. }
  4187. /**
  4188. * Set the value of an attribute on the `Component`'s element
  4189. *
  4190. * @param {string} attribute
  4191. * Name of the attribute to set.
  4192. *
  4193. * @param {string} value
  4194. * Value to set the attribute to.
  4195. *
  4196. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute}
  4197. */
  4198. ;
  4199. _proto.setAttribute = function setAttribute$1(attribute, value) {
  4200. setAttribute(this.el_, attribute, value);
  4201. }
  4202. /**
  4203. * Remove an attribute from the `Component`s element.
  4204. *
  4205. * @param {string} attribute
  4206. * Name of the attribute to remove.
  4207. *
  4208. * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute}
  4209. */
  4210. ;
  4211. _proto.removeAttribute = function removeAttribute$1(attribute) {
  4212. removeAttribute(this.el_, attribute);
  4213. }
  4214. /**
  4215. * Get or set the width of the component based upon the CSS styles.
  4216. * See {@link Component#dimension} for more detailed information.
  4217. *
  4218. * @param {number|string} [num]
  4219. * The width that you want to set postfixed with '%', 'px' or nothing.
  4220. *
  4221. * @param {boolean} [skipListeners]
  4222. * Skip the componentresize event trigger
  4223. *
  4224. * @return {number|string}
  4225. * The width when getting, zero if there is no width. Can be a string
  4226. * postpixed with '%' or 'px'.
  4227. */
  4228. ;
  4229. _proto.width = function width(num, skipListeners) {
  4230. return this.dimension('width', num, skipListeners);
  4231. }
  4232. /**
  4233. * Get or set the height of the component based upon the CSS styles.
  4234. * See {@link Component#dimension} for more detailed information.
  4235. *
  4236. * @param {number|string} [num]
  4237. * The height that you want to set postfixed with '%', 'px' or nothing.
  4238. *
  4239. * @param {boolean} [skipListeners]
  4240. * Skip the componentresize event trigger
  4241. *
  4242. * @return {number|string}
  4243. * The width when getting, zero if there is no width. Can be a string
  4244. * postpixed with '%' or 'px'.
  4245. */
  4246. ;
  4247. _proto.height = function height(num, skipListeners) {
  4248. return this.dimension('height', num, skipListeners);
  4249. }
  4250. /**
  4251. * Set both the width and height of the `Component` element at the same time.
  4252. *
  4253. * @param {number|string} width
  4254. * Width to set the `Component`s element to.
  4255. *
  4256. * @param {number|string} height
  4257. * Height to set the `Component`s element to.
  4258. */
  4259. ;
  4260. _proto.dimensions = function dimensions(width, height) {
  4261. // Skip componentresize listeners on width for optimization
  4262. this.width(width, true);
  4263. this.height(height);
  4264. }
  4265. /**
  4266. * Get or set width or height of the `Component` element. This is the shared code
  4267. * for the {@link Component#width} and {@link Component#height}.
  4268. *
  4269. * Things to know:
  4270. * - If the width or height in an number this will return the number postfixed with 'px'.
  4271. * - If the width/height is a percent this will return the percent postfixed with '%'
  4272. * - Hidden elements have a width of 0 with `window.getComputedStyle`. This function
  4273. * defaults to the `Component`s `style.width` and falls back to `window.getComputedStyle`.
  4274. * See [this]{@link http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/}
  4275. * for more information
  4276. * - If you want the computed style of the component, use {@link Component#currentWidth}
  4277. * and {@link {Component#currentHeight}
  4278. *
  4279. * @fires Component#componentresize
  4280. *
  4281. * @param {string} widthOrHeight
  4282. 8 'width' or 'height'
  4283. *
  4284. * @param {number|string} [num]
  4285. 8 New dimension
  4286. *
  4287. * @param {boolean} [skipListeners]
  4288. * Skip componentresize event trigger
  4289. *
  4290. * @return {number}
  4291. * The dimension when getting or 0 if unset
  4292. */
  4293. ;
  4294. _proto.dimension = function dimension(widthOrHeight, num, skipListeners) {
  4295. if (num !== undefined) {
  4296. // Set to zero if null or literally NaN (NaN !== NaN)
  4297. if (num === null || num !== num) {
  4298. num = 0;
  4299. } // Check if using css width/height (% or px) and adjust
  4300. if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) {
  4301. this.el_.style[widthOrHeight] = num;
  4302. } else if (num === 'auto') {
  4303. this.el_.style[widthOrHeight] = '';
  4304. } else {
  4305. this.el_.style[widthOrHeight] = num + 'px';
  4306. } // skipListeners allows us to avoid triggering the resize event when setting both width and height
  4307. if (!skipListeners) {
  4308. /**
  4309. * Triggered when a component is resized.
  4310. *
  4311. * @event Component#componentresize
  4312. * @type {EventTarget~Event}
  4313. */
  4314. this.trigger('componentresize');
  4315. }
  4316. return;
  4317. } // Not setting a value, so getting it
  4318. // Make sure element exists
  4319. if (!this.el_) {
  4320. return 0;
  4321. } // Get dimension value from style
  4322. var val = this.el_.style[widthOrHeight];
  4323. var pxIndex = val.indexOf('px');
  4324. if (pxIndex !== -1) {
  4325. // Return the pixel value with no 'px'
  4326. return parseInt(val.slice(0, pxIndex), 10);
  4327. } // No px so using % or no style was set, so falling back to offsetWidth/height
  4328. // If component has display:none, offset will return 0
  4329. // TODO: handle display:none and no dimension style using px
  4330. return parseInt(this.el_['offset' + toTitleCase$1(widthOrHeight)], 10);
  4331. }
  4332. /**
  4333. * Get the computed width or the height of the component's element.
  4334. *
  4335. * Uses `window.getComputedStyle`.
  4336. *
  4337. * @param {string} widthOrHeight
  4338. * A string containing 'width' or 'height'. Whichever one you want to get.
  4339. *
  4340. * @return {number}
  4341. * The dimension that gets asked for or 0 if nothing was set
  4342. * for that dimension.
  4343. */
  4344. ;
  4345. _proto.currentDimension = function currentDimension(widthOrHeight) {
  4346. var computedWidthOrHeight = 0;
  4347. if (widthOrHeight !== 'width' && widthOrHeight !== 'height') {
  4348. throw new Error('currentDimension only accepts width or height value');
  4349. }
  4350. computedWidthOrHeight = computedStyle(this.el_, widthOrHeight); // remove 'px' from variable and parse as integer
  4351. computedWidthOrHeight = parseFloat(computedWidthOrHeight); // if the computed value is still 0, it's possible that the browser is lying
  4352. // and we want to check the offset values.
  4353. // This code also runs wherever getComputedStyle doesn't exist.
  4354. if (computedWidthOrHeight === 0 || isNaN(computedWidthOrHeight)) {
  4355. var rule = "offset" + toTitleCase$1(widthOrHeight);
  4356. computedWidthOrHeight = this.el_[rule];
  4357. }
  4358. return computedWidthOrHeight;
  4359. }
  4360. /**
  4361. * An object that contains width and height values of the `Component`s
  4362. * computed style. Uses `window.getComputedStyle`.
  4363. *
  4364. * @typedef {Object} Component~DimensionObject
  4365. *
  4366. * @property {number} width
  4367. * The width of the `Component`s computed style.
  4368. *
  4369. * @property {number} height
  4370. * The height of the `Component`s computed style.
  4371. */
  4372. /**
  4373. * Get an object that contains computed width and height values of the
  4374. * component's element.
  4375. *
  4376. * Uses `window.getComputedStyle`.
  4377. *
  4378. * @return {Component~DimensionObject}
  4379. * The computed dimensions of the component's element.
  4380. */
  4381. ;
  4382. _proto.currentDimensions = function currentDimensions() {
  4383. return {
  4384. width: this.currentDimension('width'),
  4385. height: this.currentDimension('height')
  4386. };
  4387. }
  4388. /**
  4389. * Get the computed width of the component's element.
  4390. *
  4391. * Uses `window.getComputedStyle`.
  4392. *
  4393. * @return {number}
  4394. * The computed width of the component's element.
  4395. */
  4396. ;
  4397. _proto.currentWidth = function currentWidth() {
  4398. return this.currentDimension('width');
  4399. }
  4400. /**
  4401. * Get the computed height of the component's element.
  4402. *
  4403. * Uses `window.getComputedStyle`.
  4404. *
  4405. * @return {number}
  4406. * The computed height of the component's element.
  4407. */
  4408. ;
  4409. _proto.currentHeight = function currentHeight() {
  4410. return this.currentDimension('height');
  4411. }
  4412. /**
  4413. * Set the focus to this component
  4414. */
  4415. ;
  4416. _proto.focus = function focus() {
  4417. this.el_.focus();
  4418. }
  4419. /**
  4420. * Remove the focus from this component
  4421. */
  4422. ;
  4423. _proto.blur = function blur() {
  4424. this.el_.blur();
  4425. }
  4426. /**
  4427. * When this Component receives a `keydown` event which it does not process,
  4428. * it passes the event to the Player for handling.
  4429. *
  4430. * @param {EventTarget~Event} event
  4431. * The `keydown` event that caused this function to be called.
  4432. */
  4433. ;
  4434. _proto.handleKeyDown = function handleKeyDown(event) {
  4435. if (this.player_) {
  4436. // We only stop propagation here because we want unhandled events to fall
  4437. // back to the browser. Exclude Tab for focus trapping.
  4438. if (!keycode.isEventKey(event, 'Tab')) {
  4439. event.stopPropagation();
  4440. }
  4441. this.player_.handleKeyDown(event);
  4442. }
  4443. }
  4444. /**
  4445. * Many components used to have a `handleKeyPress` method, which was poorly
  4446. * named because it listened to a `keydown` event. This method name now
  4447. * delegates to `handleKeyDown`. This means anyone calling `handleKeyPress`
  4448. * will not see their method calls stop working.
  4449. *
  4450. * @param {EventTarget~Event} event
  4451. * The event that caused this function to be called.
  4452. */
  4453. ;
  4454. _proto.handleKeyPress = function handleKeyPress(event) {
  4455. this.handleKeyDown(event);
  4456. }
  4457. /**
  4458. * Emit a 'tap' events when touch event support gets detected. This gets used to
  4459. * support toggling the controls through a tap on the video. They get enabled
  4460. * because every sub-component would have extra overhead otherwise.
  4461. *
  4462. * @private
  4463. * @fires Component#tap
  4464. * @listens Component#touchstart
  4465. * @listens Component#touchmove
  4466. * @listens Component#touchleave
  4467. * @listens Component#touchcancel
  4468. * @listens Component#touchend
  4469. */
  4470. ;
  4471. _proto.emitTapEvents = function emitTapEvents() {
  4472. // Track the start time so we can determine how long the touch lasted
  4473. var touchStart = 0;
  4474. var firstTouch = null; // Maximum movement allowed during a touch event to still be considered a tap
  4475. // Other popular libs use anywhere from 2 (hammer.js) to 15,
  4476. // so 10 seems like a nice, round number.
  4477. var tapMovementThreshold = 10; // The maximum length a touch can be while still being considered a tap
  4478. var touchTimeThreshold = 200;
  4479. var couldBeTap;
  4480. this.on('touchstart', function (event) {
  4481. // If more than one finger, don't consider treating this as a click
  4482. if (event.touches.length === 1) {
  4483. // Copy pageX/pageY from the object
  4484. firstTouch = {
  4485. pageX: event.touches[0].pageX,
  4486. pageY: event.touches[0].pageY
  4487. }; // Record start time so we can detect a tap vs. "touch and hold"
  4488. touchStart = window.performance.now(); // Reset couldBeTap tracking
  4489. couldBeTap = true;
  4490. }
  4491. });
  4492. this.on('touchmove', function (event) {
  4493. // If more than one finger, don't consider treating this as a click
  4494. if (event.touches.length > 1) {
  4495. couldBeTap = false;
  4496. } else if (firstTouch) {
  4497. // Some devices will throw touchmoves for all but the slightest of taps.
  4498. // So, if we moved only a small distance, this could still be a tap
  4499. var xdiff = event.touches[0].pageX - firstTouch.pageX;
  4500. var ydiff = event.touches[0].pageY - firstTouch.pageY;
  4501. var touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff);
  4502. if (touchDistance > tapMovementThreshold) {
  4503. couldBeTap = false;
  4504. }
  4505. }
  4506. });
  4507. var noTap = function noTap() {
  4508. couldBeTap = false;
  4509. }; // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s
  4510. this.on('touchleave', noTap);
  4511. this.on('touchcancel', noTap); // When the touch ends, measure how long it took and trigger the appropriate
  4512. // event
  4513. this.on('touchend', function (event) {
  4514. firstTouch = null; // Proceed only if the touchmove/leave/cancel event didn't happen
  4515. if (couldBeTap === true) {
  4516. // Measure how long the touch lasted
  4517. var touchTime = window.performance.now() - touchStart; // Make sure the touch was less than the threshold to be considered a tap
  4518. if (touchTime < touchTimeThreshold) {
  4519. // Don't let browser turn this into a click
  4520. event.preventDefault();
  4521. /**
  4522. * Triggered when a `Component` is tapped.
  4523. *
  4524. * @event Component#tap
  4525. * @type {EventTarget~Event}
  4526. */
  4527. this.trigger('tap'); // It may be good to copy the touchend event object and change the
  4528. // type to tap, if the other event properties aren't exact after
  4529. // Events.fixEvent runs (e.g. event.target)
  4530. }
  4531. }
  4532. });
  4533. }
  4534. /**
  4535. * This function reports user activity whenever touch events happen. This can get
  4536. * turned off by any sub-components that wants touch events to act another way.
  4537. *
  4538. * Report user touch activity when touch events occur. User activity gets used to
  4539. * determine when controls should show/hide. It is simple when it comes to mouse
  4540. * events, because any mouse event should show the controls. So we capture mouse
  4541. * events that bubble up to the player and report activity when that happens.
  4542. * With touch events it isn't as easy as `touchstart` and `touchend` toggle player
  4543. * controls. So touch events can't help us at the player level either.
  4544. *
  4545. * User activity gets checked asynchronously. So what could happen is a tap event
  4546. * on the video turns the controls off. Then the `touchend` event bubbles up to
  4547. * the player. Which, if it reported user activity, would turn the controls right
  4548. * back on. We also don't want to completely block touch events from bubbling up.
  4549. * Furthermore a `touchmove` event and anything other than a tap, should not turn
  4550. * controls back on.
  4551. *
  4552. * @listens Component#touchstart
  4553. * @listens Component#touchmove
  4554. * @listens Component#touchend
  4555. * @listens Component#touchcancel
  4556. */
  4557. ;
  4558. _proto.enableTouchActivity = function enableTouchActivity() {
  4559. // Don't continue if the root player doesn't support reporting user activity
  4560. if (!this.player() || !this.player().reportUserActivity) {
  4561. return;
  4562. } // listener for reporting that the user is active
  4563. var report = bind(this.player(), this.player().reportUserActivity);
  4564. var touchHolding;
  4565. this.on('touchstart', function () {
  4566. report(); // For as long as the they are touching the device or have their mouse down,
  4567. // we consider them active even if they're not moving their finger or mouse.
  4568. // So we want to continue to update that they are active
  4569. this.clearInterval(touchHolding); // report at the same interval as activityCheck
  4570. touchHolding = this.setInterval(report, 250);
  4571. });
  4572. var touchEnd = function touchEnd(event) {
  4573. report(); // stop the interval that maintains activity if the touch is holding
  4574. this.clearInterval(touchHolding);
  4575. };
  4576. this.on('touchmove', report);
  4577. this.on('touchend', touchEnd);
  4578. this.on('touchcancel', touchEnd);
  4579. }
  4580. /**
  4581. * A callback that has no parameters and is bound into `Component`s context.
  4582. *
  4583. * @callback Component~GenericCallback
  4584. * @this Component
  4585. */
  4586. /**
  4587. * Creates a function that runs after an `x` millisecond timeout. This function is a
  4588. * wrapper around `window.setTimeout`. There are a few reasons to use this one
  4589. * instead though:
  4590. * 1. It gets cleared via {@link Component#clearTimeout} when
  4591. * {@link Component#dispose} gets called.
  4592. * 2. The function callback will gets turned into a {@link Component~GenericCallback}
  4593. *
  4594. * > Note: You can't use `window.clearTimeout` on the id returned by this function. This
  4595. * will cause its dispose listener not to get cleaned up! Please use
  4596. * {@link Component#clearTimeout} or {@link Component#dispose} instead.
  4597. *
  4598. * @param {Component~GenericCallback} fn
  4599. * The function that will be run after `timeout`.
  4600. *
  4601. * @param {number} timeout
  4602. * Timeout in milliseconds to delay before executing the specified function.
  4603. *
  4604. * @return {number}
  4605. * Returns a timeout ID that gets used to identify the timeout. It can also
  4606. * get used in {@link Component#clearTimeout} to clear the timeout that
  4607. * was set.
  4608. *
  4609. * @listens Component#dispose
  4610. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout}
  4611. */
  4612. ;
  4613. _proto.setTimeout = function setTimeout(fn, timeout) {
  4614. var _this3 = this;
  4615. // declare as variables so they are properly available in timeout function
  4616. // eslint-disable-next-line
  4617. var timeoutId;
  4618. fn = bind(this, fn);
  4619. this.clearTimersOnDispose_();
  4620. timeoutId = window.setTimeout(function () {
  4621. if (_this3.setTimeoutIds_.has(timeoutId)) {
  4622. _this3.setTimeoutIds_["delete"](timeoutId);
  4623. }
  4624. fn();
  4625. }, timeout);
  4626. this.setTimeoutIds_.add(timeoutId);
  4627. return timeoutId;
  4628. }
  4629. /**
  4630. * Clears a timeout that gets created via `window.setTimeout` or
  4631. * {@link Component#setTimeout}. If you set a timeout via {@link Component#setTimeout}
  4632. * use this function instead of `window.clearTimout`. If you don't your dispose
  4633. * listener will not get cleaned up until {@link Component#dispose}!
  4634. *
  4635. * @param {number} timeoutId
  4636. * The id of the timeout to clear. The return value of
  4637. * {@link Component#setTimeout} or `window.setTimeout`.
  4638. *
  4639. * @return {number}
  4640. * Returns the timeout id that was cleared.
  4641. *
  4642. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearTimeout}
  4643. */
  4644. ;
  4645. _proto.clearTimeout = function clearTimeout(timeoutId) {
  4646. if (this.setTimeoutIds_.has(timeoutId)) {
  4647. this.setTimeoutIds_["delete"](timeoutId);
  4648. window.clearTimeout(timeoutId);
  4649. }
  4650. return timeoutId;
  4651. }
  4652. /**
  4653. * Creates a function that gets run every `x` milliseconds. This function is a wrapper
  4654. * around `window.setInterval`. There are a few reasons to use this one instead though.
  4655. * 1. It gets cleared via {@link Component#clearInterval} when
  4656. * {@link Component#dispose} gets called.
  4657. * 2. The function callback will be a {@link Component~GenericCallback}
  4658. *
  4659. * @param {Component~GenericCallback} fn
  4660. * The function to run every `x` seconds.
  4661. *
  4662. * @param {number} interval
  4663. * Execute the specified function every `x` milliseconds.
  4664. *
  4665. * @return {number}
  4666. * Returns an id that can be used to identify the interval. It can also be be used in
  4667. * {@link Component#clearInterval} to clear the interval.
  4668. *
  4669. * @listens Component#dispose
  4670. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval}
  4671. */
  4672. ;
  4673. _proto.setInterval = function setInterval(fn, interval) {
  4674. fn = bind(this, fn);
  4675. this.clearTimersOnDispose_();
  4676. var intervalId = window.setInterval(fn, interval);
  4677. this.setIntervalIds_.add(intervalId);
  4678. return intervalId;
  4679. }
  4680. /**
  4681. * Clears an interval that gets created via `window.setInterval` or
  4682. * {@link Component#setInterval}. If you set an inteval via {@link Component#setInterval}
  4683. * use this function instead of `window.clearInterval`. If you don't your dispose
  4684. * listener will not get cleaned up until {@link Component#dispose}!
  4685. *
  4686. * @param {number} intervalId
  4687. * The id of the interval to clear. The return value of
  4688. * {@link Component#setInterval} or `window.setInterval`.
  4689. *
  4690. * @return {number}
  4691. * Returns the interval id that was cleared.
  4692. *
  4693. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval}
  4694. */
  4695. ;
  4696. _proto.clearInterval = function clearInterval(intervalId) {
  4697. if (this.setIntervalIds_.has(intervalId)) {
  4698. this.setIntervalIds_["delete"](intervalId);
  4699. window.clearInterval(intervalId);
  4700. }
  4701. return intervalId;
  4702. }
  4703. /**
  4704. * Queues up a callback to be passed to requestAnimationFrame (rAF), but
  4705. * with a few extra bonuses:
  4706. *
  4707. * - Supports browsers that do not support rAF by falling back to
  4708. * {@link Component#setTimeout}.
  4709. *
  4710. * - The callback is turned into a {@link Component~GenericCallback} (i.e.
  4711. * bound to the component).
  4712. *
  4713. * - Automatic cancellation of the rAF callback is handled if the component
  4714. * is disposed before it is called.
  4715. *
  4716. * @param {Component~GenericCallback} fn
  4717. * A function that will be bound to this component and executed just
  4718. * before the browser's next repaint.
  4719. *
  4720. * @return {number}
  4721. * Returns an rAF ID that gets used to identify the timeout. It can
  4722. * also be used in {@link Component#cancelAnimationFrame} to cancel
  4723. * the animation frame callback.
  4724. *
  4725. * @listens Component#dispose
  4726. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame}
  4727. */
  4728. ;
  4729. _proto.requestAnimationFrame = function requestAnimationFrame(fn) {
  4730. var _this4 = this;
  4731. // Fall back to using a timer.
  4732. if (!this.supportsRaf_) {
  4733. return this.setTimeout(fn, 1000 / 60);
  4734. }
  4735. this.clearTimersOnDispose_(); // declare as variables so they are properly available in rAF function
  4736. // eslint-disable-next-line
  4737. var id;
  4738. fn = bind(this, fn);
  4739. id = window.requestAnimationFrame(function () {
  4740. if (_this4.rafIds_.has(id)) {
  4741. _this4.rafIds_["delete"](id);
  4742. }
  4743. fn();
  4744. });
  4745. this.rafIds_.add(id);
  4746. return id;
  4747. }
  4748. /**
  4749. * Request an animation frame, but only one named animation
  4750. * frame will be queued. Another will never be added until
  4751. * the previous one finishes.
  4752. *
  4753. * @param {string} name
  4754. * The name to give this requestAnimationFrame
  4755. *
  4756. * @param {Component~GenericCallback} fn
  4757. * A function that will be bound to this component and executed just
  4758. * before the browser's next repaint.
  4759. */
  4760. ;
  4761. _proto.requestNamedAnimationFrame = function requestNamedAnimationFrame(name, fn) {
  4762. var _this5 = this;
  4763. if (this.namedRafs_.has(name)) {
  4764. return;
  4765. }
  4766. this.clearTimersOnDispose_();
  4767. fn = bind(this, fn);
  4768. var id = this.requestAnimationFrame(function () {
  4769. fn();
  4770. if (_this5.namedRafs_.has(name)) {
  4771. _this5.namedRafs_["delete"](name);
  4772. }
  4773. });
  4774. this.namedRafs_.set(name, id);
  4775. return name;
  4776. }
  4777. /**
  4778. * Cancels a current named animation frame if it exists.
  4779. *
  4780. * @param {string} name
  4781. * The name of the requestAnimationFrame to cancel.
  4782. */
  4783. ;
  4784. _proto.cancelNamedAnimationFrame = function cancelNamedAnimationFrame(name) {
  4785. if (!this.namedRafs_.has(name)) {
  4786. return;
  4787. }
  4788. this.cancelAnimationFrame(this.namedRafs_.get(name));
  4789. this.namedRafs_["delete"](name);
  4790. }
  4791. /**
  4792. * Cancels a queued callback passed to {@link Component#requestAnimationFrame}
  4793. * (rAF).
  4794. *
  4795. * If you queue an rAF callback via {@link Component#requestAnimationFrame},
  4796. * use this function instead of `window.cancelAnimationFrame`. If you don't,
  4797. * your dispose listener will not get cleaned up until {@link Component#dispose}!
  4798. *
  4799. * @param {number} id
  4800. * The rAF ID to clear. The return value of {@link Component#requestAnimationFrame}.
  4801. *
  4802. * @return {number}
  4803. * Returns the rAF ID that was cleared.
  4804. *
  4805. * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/window/cancelAnimationFrame}
  4806. */
  4807. ;
  4808. _proto.cancelAnimationFrame = function cancelAnimationFrame(id) {
  4809. // Fall back to using a timer.
  4810. if (!this.supportsRaf_) {
  4811. return this.clearTimeout(id);
  4812. }
  4813. if (this.rafIds_.has(id)) {
  4814. this.rafIds_["delete"](id);
  4815. window.cancelAnimationFrame(id);
  4816. }
  4817. return id;
  4818. }
  4819. /**
  4820. * A function to setup `requestAnimationFrame`, `setTimeout`,
  4821. * and `setInterval`, clearing on dispose.
  4822. *
  4823. * > Previously each timer added and removed dispose listeners on it's own.
  4824. * For better performance it was decided to batch them all, and use `Set`s
  4825. * to track outstanding timer ids.
  4826. *
  4827. * @private
  4828. */
  4829. ;
  4830. _proto.clearTimersOnDispose_ = function clearTimersOnDispose_() {
  4831. var _this6 = this;
  4832. if (this.clearingTimersOnDispose_) {
  4833. return;
  4834. }
  4835. this.clearingTimersOnDispose_ = true;
  4836. this.one('dispose', function () {
  4837. [['namedRafs_', 'cancelNamedAnimationFrame'], ['rafIds_', 'cancelAnimationFrame'], ['setTimeoutIds_', 'clearTimeout'], ['setIntervalIds_', 'clearInterval']].forEach(function (_ref) {
  4838. var idName = _ref[0],
  4839. cancelName = _ref[1];
  4840. // for a `Set` key will actually be the value again
  4841. // so forEach((val, val) =>` but for maps we want to use
  4842. // the key.
  4843. _this6[idName].forEach(function (val, key) {
  4844. return _this6[cancelName](key);
  4845. });
  4846. });
  4847. _this6.clearingTimersOnDispose_ = false;
  4848. });
  4849. }
  4850. /**
  4851. * Register a `Component` with `videojs` given the name and the component.
  4852. *
  4853. * > NOTE: {@link Tech}s should not be registered as a `Component`. {@link Tech}s
  4854. * should be registered using {@link Tech.registerTech} or
  4855. * {@link videojs:videojs.registerTech}.
  4856. *
  4857. * > NOTE: This function can also be seen on videojs as
  4858. * {@link videojs:videojs.registerComponent}.
  4859. *
  4860. * @param {string} name
  4861. * The name of the `Component` to register.
  4862. *
  4863. * @param {Component} ComponentToRegister
  4864. * The `Component` class to register.
  4865. *
  4866. * @return {Component}
  4867. * The `Component` that was registered.
  4868. */
  4869. ;
  4870. Component.registerComponent = function registerComponent(name, ComponentToRegister) {
  4871. if (typeof name !== 'string' || !name) {
  4872. throw new Error("Illegal component name, \"" + name + "\"; must be a non-empty string.");
  4873. }
  4874. var Tech = Component.getComponent('Tech'); // We need to make sure this check is only done if Tech has been registered.
  4875. var isTech = Tech && Tech.isTech(ComponentToRegister);
  4876. var isComp = Component === ComponentToRegister || Component.prototype.isPrototypeOf(ComponentToRegister.prototype);
  4877. if (isTech || !isComp) {
  4878. var reason;
  4879. if (isTech) {
  4880. reason = 'techs must be registered using Tech.registerTech()';
  4881. } else {
  4882. reason = 'must be a Component subclass';
  4883. }
  4884. throw new Error("Illegal component, \"" + name + "\"; " + reason + ".");
  4885. }
  4886. name = toTitleCase$1(name);
  4887. if (!Component.components_) {
  4888. Component.components_ = {};
  4889. }
  4890. var Player = Component.getComponent('Player');
  4891. if (name === 'Player' && Player && Player.players) {
  4892. var players = Player.players;
  4893. var playerNames = Object.keys(players); // If we have players that were disposed, then their name will still be
  4894. // in Players.players. So, we must loop through and verify that the value
  4895. // for each item is not null. This allows registration of the Player component
  4896. // after all players have been disposed or before any were created.
  4897. if (players && playerNames.length > 0 && playerNames.map(function (pname) {
  4898. return players[pname];
  4899. }).every(Boolean)) {
  4900. throw new Error('Can not register Player component after player has been created.');
  4901. }
  4902. }
  4903. Component.components_[name] = ComponentToRegister;
  4904. Component.components_[toLowerCase(name)] = ComponentToRegister;
  4905. return ComponentToRegister;
  4906. }
  4907. /**
  4908. * Get a `Component` based on the name it was registered with.
  4909. *
  4910. * @param {string} name
  4911. * The Name of the component to get.
  4912. *
  4913. * @return {Component}
  4914. * The `Component` that got registered under the given name.
  4915. */
  4916. ;
  4917. Component.getComponent = function getComponent(name) {
  4918. if (!name || !Component.components_) {
  4919. return;
  4920. }
  4921. return Component.components_[name];
  4922. };
  4923. return Component;
  4924. }();
  4925. /**
  4926. * Whether or not this component supports `requestAnimationFrame`.
  4927. *
  4928. * This is exposed primarily for testing purposes.
  4929. *
  4930. * @private
  4931. * @type {Boolean}
  4932. */
  4933. Component$1.prototype.supportsRaf_ = typeof window.requestAnimationFrame === 'function' && typeof window.cancelAnimationFrame === 'function';
  4934. Component$1.registerComponent('Component', Component$1);
  4935. function _assertThisInitialized(self) {
  4936. if (self === void 0) {
  4937. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  4938. }
  4939. return self;
  4940. }
  4941. var assertThisInitialized = _assertThisInitialized;
  4942. function _inheritsLoose(subClass, superClass) {
  4943. subClass.prototype = Object.create(superClass.prototype);
  4944. subClass.prototype.constructor = subClass;
  4945. subClass.__proto__ = superClass;
  4946. }
  4947. var inheritsLoose = _inheritsLoose;
  4948. /**
  4949. * @file time-ranges.js
  4950. * @module time-ranges
  4951. */
  4952. /**
  4953. * Returns the time for the specified index at the start or end
  4954. * of a TimeRange object.
  4955. *
  4956. * @typedef {Function} TimeRangeIndex
  4957. *
  4958. * @param {number} [index=0]
  4959. * The range number to return the time for.
  4960. *
  4961. * @return {number}
  4962. * The time offset at the specified index.
  4963. *
  4964. * @deprecated The index argument must be provided.
  4965. * In the future, leaving it out will throw an error.
  4966. */
  4967. /**
  4968. * An object that contains ranges of time.
  4969. *
  4970. * @typedef {Object} TimeRange
  4971. *
  4972. * @property {number} length
  4973. * The number of time ranges represented by this object.
  4974. *
  4975. * @property {module:time-ranges~TimeRangeIndex} start
  4976. * Returns the time offset at which a specified time range begins.
  4977. *
  4978. * @property {module:time-ranges~TimeRangeIndex} end
  4979. * Returns the time offset at which a specified time range ends.
  4980. *
  4981. * @see https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges
  4982. */
  4983. /**
  4984. * Check if any of the time ranges are over the maximum index.
  4985. *
  4986. * @private
  4987. * @param {string} fnName
  4988. * The function name to use for logging
  4989. *
  4990. * @param {number} index
  4991. * The index to check
  4992. *
  4993. * @param {number} maxIndex
  4994. * The maximum possible index
  4995. *
  4996. * @throws {Error} if the timeRanges provided are over the maxIndex
  4997. */
  4998. function rangeCheck(fnName, index, maxIndex) {
  4999. if (typeof index !== 'number' || index < 0 || index > maxIndex) {
  5000. throw new Error("Failed to execute '" + fnName + "' on 'TimeRanges': The index provided (" + index + ") is non-numeric or out of bounds (0-" + maxIndex + ").");
  5001. }
  5002. }
  5003. /**
  5004. * Get the time for the specified index at the start or end
  5005. * of a TimeRange object.
  5006. *
  5007. * @private
  5008. * @param {string} fnName
  5009. * The function name to use for logging
  5010. *
  5011. * @param {string} valueIndex
  5012. * The property that should be used to get the time. should be
  5013. * 'start' or 'end'
  5014. *
  5015. * @param {Array} ranges
  5016. * An array of time ranges
  5017. *
  5018. * @param {Array} [rangeIndex=0]
  5019. * The index to start the search at
  5020. *
  5021. * @return {number}
  5022. * The time that offset at the specified index.
  5023. *
  5024. * @deprecated rangeIndex must be set to a value, in the future this will throw an error.
  5025. * @throws {Error} if rangeIndex is more than the length of ranges
  5026. */
  5027. function getRange(fnName, valueIndex, ranges, rangeIndex) {
  5028. rangeCheck(fnName, rangeIndex, ranges.length - 1);
  5029. return ranges[rangeIndex][valueIndex];
  5030. }
  5031. /**
  5032. * Create a time range object given ranges of time.
  5033. *
  5034. * @private
  5035. * @param {Array} [ranges]
  5036. * An array of time ranges.
  5037. */
  5038. function createTimeRangesObj(ranges) {
  5039. var timeRangesObj;
  5040. if (ranges === undefined || ranges.length === 0) {
  5041. timeRangesObj = {
  5042. length: 0,
  5043. start: function start() {
  5044. throw new Error('This TimeRanges object is empty');
  5045. },
  5046. end: function end() {
  5047. throw new Error('This TimeRanges object is empty');
  5048. }
  5049. };
  5050. } else {
  5051. timeRangesObj = {
  5052. length: ranges.length,
  5053. start: getRange.bind(null, 'start', 0, ranges),
  5054. end: getRange.bind(null, 'end', 1, ranges)
  5055. };
  5056. }
  5057. if (window.Symbol && window.Symbol.iterator) {
  5058. timeRangesObj[window.Symbol.iterator] = function () {
  5059. return (ranges || []).values();
  5060. };
  5061. }
  5062. return timeRangesObj;
  5063. }
  5064. /**
  5065. * Create a `TimeRange` object which mimics an
  5066. * {@link https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges|HTML5 TimeRanges instance}.
  5067. *
  5068. * @param {number|Array[]} start
  5069. * The start of a single range (a number) or an array of ranges (an
  5070. * array of arrays of two numbers each).
  5071. *
  5072. * @param {number} end
  5073. * The end of a single range. Cannot be used with the array form of
  5074. * the `start` argument.
  5075. */
  5076. function createTimeRanges(start, end) {
  5077. if (Array.isArray(start)) {
  5078. return createTimeRangesObj(start);
  5079. } else if (start === undefined || end === undefined) {
  5080. return createTimeRangesObj();
  5081. }
  5082. return createTimeRangesObj([[start, end]]);
  5083. }
  5084. /**
  5085. * @file buffer.js
  5086. * @module buffer
  5087. */
  5088. /**
  5089. * Compute the percentage of the media that has been buffered.
  5090. *
  5091. * @param {TimeRange} buffered
  5092. * The current `TimeRange` object representing buffered time ranges
  5093. *
  5094. * @param {number} duration
  5095. * Total duration of the media
  5096. *
  5097. * @return {number}
  5098. * Percent buffered of the total duration in decimal form.
  5099. */
  5100. function bufferedPercent(buffered, duration) {
  5101. var bufferedDuration = 0;
  5102. var start;
  5103. var end;
  5104. if (!duration) {
  5105. return 0;
  5106. }
  5107. if (!buffered || !buffered.length) {
  5108. buffered = createTimeRanges(0, 0);
  5109. }
  5110. for (var i = 0; i < buffered.length; i++) {
  5111. start = buffered.start(i);
  5112. end = buffered.end(i); // buffered end can be bigger than duration by a very small fraction
  5113. if (end > duration) {
  5114. end = duration;
  5115. }
  5116. bufferedDuration += end - start;
  5117. }
  5118. return bufferedDuration / duration;
  5119. }
  5120. /**
  5121. * @file media-error.js
  5122. */
  5123. /**
  5124. * A Custom `MediaError` class which mimics the standard HTML5 `MediaError` class.
  5125. *
  5126. * @param {number|string|Object|MediaError} value
  5127. * This can be of multiple types:
  5128. * - number: should be a standard error code
  5129. * - string: an error message (the code will be 0)
  5130. * - Object: arbitrary properties
  5131. * - `MediaError` (native): used to populate a video.js `MediaError` object
  5132. * - `MediaError` (video.js): will return itself if it's already a
  5133. * video.js `MediaError` object.
  5134. *
  5135. * @see [MediaError Spec]{@link https://dev.w3.org/html5/spec-author-view/video.html#mediaerror}
  5136. * @see [Encrypted MediaError Spec]{@link https://www.w3.org/TR/2013/WD-encrypted-media-20130510/#error-codes}
  5137. *
  5138. * @class MediaError
  5139. */
  5140. function MediaError(value) {
  5141. // Allow redundant calls to this constructor to avoid having `instanceof`
  5142. // checks peppered around the code.
  5143. if (value instanceof MediaError) {
  5144. return value;
  5145. }
  5146. if (typeof value === 'number') {
  5147. this.code = value;
  5148. } else if (typeof value === 'string') {
  5149. // default code is zero, so this is a custom error
  5150. this.message = value;
  5151. } else if (isObject$1(value)) {
  5152. // We assign the `code` property manually because native `MediaError` objects
  5153. // do not expose it as an own/enumerable property of the object.
  5154. if (typeof value.code === 'number') {
  5155. this.code = value.code;
  5156. }
  5157. assign$1(this, value);
  5158. }
  5159. if (!this.message) {
  5160. this.message = MediaError.defaultMessages[this.code] || '';
  5161. }
  5162. }
  5163. /**
  5164. * The error code that refers two one of the defined `MediaError` types
  5165. *
  5166. * @type {Number}
  5167. */
  5168. MediaError.prototype.code = 0;
  5169. /**
  5170. * An optional message that to show with the error. Message is not part of the HTML5
  5171. * video spec but allows for more informative custom errors.
  5172. *
  5173. * @type {String}
  5174. */
  5175. MediaError.prototype.message = '';
  5176. /**
  5177. * An optional status code that can be set by plugins to allow even more detail about
  5178. * the error. For example a plugin might provide a specific HTTP status code and an
  5179. * error message for that code. Then when the plugin gets that error this class will
  5180. * know how to display an error message for it. This allows a custom message to show
  5181. * up on the `Player` error overlay.
  5182. *
  5183. * @type {Array}
  5184. */
  5185. MediaError.prototype.status = null;
  5186. /**
  5187. * Errors indexed by the W3C standard. The order **CANNOT CHANGE**! See the
  5188. * specification listed under {@link MediaError} for more information.
  5189. *
  5190. * @enum {array}
  5191. * @readonly
  5192. * @property {string} 0 - MEDIA_ERR_CUSTOM
  5193. * @property {string} 1 - MEDIA_ERR_ABORTED
  5194. * @property {string} 2 - MEDIA_ERR_NETWORK
  5195. * @property {string} 3 - MEDIA_ERR_DECODE
  5196. * @property {string} 4 - MEDIA_ERR_SRC_NOT_SUPPORTED
  5197. * @property {string} 5 - MEDIA_ERR_ENCRYPTED
  5198. */
  5199. MediaError.errorTypes = ['MEDIA_ERR_CUSTOM', 'MEDIA_ERR_ABORTED', 'MEDIA_ERR_NETWORK', 'MEDIA_ERR_DECODE', 'MEDIA_ERR_SRC_NOT_SUPPORTED', 'MEDIA_ERR_ENCRYPTED'];
  5200. /**
  5201. * The default `MediaError` messages based on the {@link MediaError.errorTypes}.
  5202. *
  5203. * @type {Array}
  5204. * @constant
  5205. */
  5206. MediaError.defaultMessages = {
  5207. 1: 'You aborted the media playback',
  5208. 2: 'A network error caused the media download to fail part-way.',
  5209. 3: 'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.',
  5210. 4: 'The media could not be loaded, either because the server or network failed or because the format is not supported.',
  5211. 5: 'The media is encrypted and we do not have the keys to decrypt it.'
  5212. }; // Add types as properties on MediaError
  5213. // e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
  5214. for (var errNum = 0; errNum < MediaError.errorTypes.length; errNum++) {
  5215. MediaError[MediaError.errorTypes[errNum]] = errNum; // values should be accessible on both the class and instance
  5216. MediaError.prototype[MediaError.errorTypes[errNum]] = errNum;
  5217. } // jsdocs for instance/static members added above
  5218. var tuple = SafeParseTuple;
  5219. function SafeParseTuple(obj, reviver) {
  5220. var json;
  5221. var error = null;
  5222. try {
  5223. json = JSON.parse(obj, reviver);
  5224. } catch (err) {
  5225. error = err;
  5226. }
  5227. return [error, json];
  5228. }
  5229. /**
  5230. * Returns whether an object is `Promise`-like (i.e. has a `then` method).
  5231. *
  5232. * @param {Object} value
  5233. * An object that may or may not be `Promise`-like.
  5234. *
  5235. * @return {boolean}
  5236. * Whether or not the object is `Promise`-like.
  5237. */
  5238. function isPromise(value) {
  5239. return value !== undefined && value !== null && typeof value.then === 'function';
  5240. }
  5241. /**
  5242. * Silence a Promise-like object.
  5243. *
  5244. * This is useful for avoiding non-harmful, but potentially confusing "uncaught
  5245. * play promise" rejection error messages.
  5246. *
  5247. * @param {Object} value
  5248. * An object that may or may not be `Promise`-like.
  5249. */
  5250. function silencePromise(value) {
  5251. if (isPromise(value)) {
  5252. value.then(null, function (e) {});
  5253. }
  5254. }
  5255. /**
  5256. * @file text-track-list-converter.js Utilities for capturing text track state and
  5257. * re-creating tracks based on a capture.
  5258. *
  5259. * @module text-track-list-converter
  5260. */
  5261. /**
  5262. * Examine a single {@link TextTrack} and return a JSON-compatible javascript object that
  5263. * represents the {@link TextTrack}'s state.
  5264. *
  5265. * @param {TextTrack} track
  5266. * The text track to query.
  5267. *
  5268. * @return {Object}
  5269. * A serializable javascript representation of the TextTrack.
  5270. * @private
  5271. */
  5272. var trackToJson_ = function trackToJson_(track) {
  5273. var ret = ['kind', 'label', 'language', 'id', 'inBandMetadataTrackDispatchType', 'mode', 'src'].reduce(function (acc, prop, i) {
  5274. if (track[prop]) {
  5275. acc[prop] = track[prop];
  5276. }
  5277. return acc;
  5278. }, {
  5279. cues: track.cues && Array.prototype.map.call(track.cues, function (cue) {
  5280. return {
  5281. startTime: cue.startTime,
  5282. endTime: cue.endTime,
  5283. text: cue.text,
  5284. id: cue.id
  5285. };
  5286. })
  5287. });
  5288. return ret;
  5289. };
  5290. /**
  5291. * Examine a {@link Tech} and return a JSON-compatible javascript array that represents the
  5292. * state of all {@link TextTrack}s currently configured. The return array is compatible with
  5293. * {@link text-track-list-converter:jsonToTextTracks}.
  5294. *
  5295. * @param {Tech} tech
  5296. * The tech object to query
  5297. *
  5298. * @return {Array}
  5299. * A serializable javascript representation of the {@link Tech}s
  5300. * {@link TextTrackList}.
  5301. */
  5302. var textTracksToJson = function textTracksToJson(tech) {
  5303. var trackEls = tech.$$('track');
  5304. var trackObjs = Array.prototype.map.call(trackEls, function (t) {
  5305. return t.track;
  5306. });
  5307. var tracks = Array.prototype.map.call(trackEls, function (trackEl) {
  5308. var json = trackToJson_(trackEl.track);
  5309. if (trackEl.src) {
  5310. json.src = trackEl.src;
  5311. }
  5312. return json;
  5313. });
  5314. return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function (track) {
  5315. return trackObjs.indexOf(track) === -1;
  5316. }).map(trackToJson_));
  5317. };
  5318. /**
  5319. * Create a set of remote {@link TextTrack}s on a {@link Tech} based on an array of javascript
  5320. * object {@link TextTrack} representations.
  5321. *
  5322. * @param {Array} json
  5323. * An array of `TextTrack` representation objects, like those that would be
  5324. * produced by `textTracksToJson`.
  5325. *
  5326. * @param {Tech} tech
  5327. * The `Tech` to create the `TextTrack`s on.
  5328. */
  5329. var jsonToTextTracks = function jsonToTextTracks(json, tech) {
  5330. json.forEach(function (track) {
  5331. var addedTrack = tech.addRemoteTextTrack(track).track;
  5332. if (!track.src && track.cues) {
  5333. track.cues.forEach(function (cue) {
  5334. return addedTrack.addCue(cue);
  5335. });
  5336. }
  5337. });
  5338. return tech.textTracks();
  5339. };
  5340. var textTrackConverter = {
  5341. textTracksToJson: textTracksToJson,
  5342. jsonToTextTracks: jsonToTextTracks,
  5343. trackToJson_: trackToJson_
  5344. };
  5345. var MODAL_CLASS_NAME = 'vjs-modal-dialog';
  5346. /**
  5347. * The `ModalDialog` displays over the video and its controls, which blocks
  5348. * interaction with the player until it is closed.
  5349. *
  5350. * Modal dialogs include a "Close" button and will close when that button
  5351. * is activated - or when ESC is pressed anywhere.
  5352. *
  5353. * @extends Component
  5354. */
  5355. var ModalDialog = /*#__PURE__*/function (_Component) {
  5356. inheritsLoose(ModalDialog, _Component);
  5357. /**
  5358. * Create an instance of this class.
  5359. *
  5360. * @param {Player} player
  5361. * The `Player` that this class should be attached to.
  5362. *
  5363. * @param {Object} [options]
  5364. * The key/value store of player options.
  5365. *
  5366. * @param {Mixed} [options.content=undefined]
  5367. * Provide customized content for this modal.
  5368. *
  5369. * @param {string} [options.description]
  5370. * A text description for the modal, primarily for accessibility.
  5371. *
  5372. * @param {boolean} [options.fillAlways=false]
  5373. * Normally, modals are automatically filled only the first time
  5374. * they open. This tells the modal to refresh its content
  5375. * every time it opens.
  5376. *
  5377. * @param {string} [options.label]
  5378. * A text label for the modal, primarily for accessibility.
  5379. *
  5380. * @param {boolean} [options.pauseOnOpen=true]
  5381. * If `true`, playback will will be paused if playing when
  5382. * the modal opens, and resumed when it closes.
  5383. *
  5384. * @param {boolean} [options.temporary=true]
  5385. * If `true`, the modal can only be opened once; it will be
  5386. * disposed as soon as it's closed.
  5387. *
  5388. * @param {boolean} [options.uncloseable=false]
  5389. * If `true`, the user will not be able to close the modal
  5390. * through the UI in the normal ways. Programmatic closing is
  5391. * still possible.
  5392. */
  5393. function ModalDialog(player, options) {
  5394. var _this;
  5395. _this = _Component.call(this, player, options) || this;
  5396. _this.handleKeyDown_ = function (e) {
  5397. return _this.handleKeyDown(e);
  5398. };
  5399. _this.close_ = function (e) {
  5400. return _this.close(e);
  5401. };
  5402. _this.opened_ = _this.hasBeenOpened_ = _this.hasBeenFilled_ = false;
  5403. _this.closeable(!_this.options_.uncloseable);
  5404. _this.content(_this.options_.content); // Make sure the contentEl is defined AFTER any children are initialized
  5405. // because we only want the contents of the modal in the contentEl
  5406. // (not the UI elements like the close button).
  5407. _this.contentEl_ = createEl('div', {
  5408. className: MODAL_CLASS_NAME + "-content"
  5409. }, {
  5410. role: 'document'
  5411. });
  5412. _this.descEl_ = createEl('p', {
  5413. className: MODAL_CLASS_NAME + "-description vjs-control-text",
  5414. id: _this.el().getAttribute('aria-describedby')
  5415. });
  5416. textContent(_this.descEl_, _this.description());
  5417. _this.el_.appendChild(_this.descEl_);
  5418. _this.el_.appendChild(_this.contentEl_);
  5419. return _this;
  5420. }
  5421. /**
  5422. * Create the `ModalDialog`'s DOM element
  5423. *
  5424. * @return {Element}
  5425. * The DOM element that gets created.
  5426. */
  5427. var _proto = ModalDialog.prototype;
  5428. _proto.createEl = function createEl() {
  5429. return _Component.prototype.createEl.call(this, 'div', {
  5430. className: this.buildCSSClass(),
  5431. tabIndex: -1
  5432. }, {
  5433. 'aria-describedby': this.id() + "_description",
  5434. 'aria-hidden': 'true',
  5435. 'aria-label': this.label(),
  5436. 'role': 'dialog'
  5437. });
  5438. };
  5439. _proto.dispose = function dispose() {
  5440. this.contentEl_ = null;
  5441. this.descEl_ = null;
  5442. this.previouslyActiveEl_ = null;
  5443. _Component.prototype.dispose.call(this);
  5444. }
  5445. /**
  5446. * Builds the default DOM `className`.
  5447. *
  5448. * @return {string}
  5449. * The DOM `className` for this object.
  5450. */
  5451. ;
  5452. _proto.buildCSSClass = function buildCSSClass() {
  5453. return MODAL_CLASS_NAME + " vjs-hidden " + _Component.prototype.buildCSSClass.call(this);
  5454. }
  5455. /**
  5456. * Returns the label string for this modal. Primarily used for accessibility.
  5457. *
  5458. * @return {string}
  5459. * the localized or raw label of this modal.
  5460. */
  5461. ;
  5462. _proto.label = function label() {
  5463. return this.localize(this.options_.label || 'Modal Window');
  5464. }
  5465. /**
  5466. * Returns the description string for this modal. Primarily used for
  5467. * accessibility.
  5468. *
  5469. * @return {string}
  5470. * The localized or raw description of this modal.
  5471. */
  5472. ;
  5473. _proto.description = function description() {
  5474. var desc = this.options_.description || this.localize('This is a modal window.'); // Append a universal closeability message if the modal is closeable.
  5475. if (this.closeable()) {
  5476. desc += ' ' + this.localize('This modal can be closed by pressing the Escape key or activating the close button.');
  5477. }
  5478. return desc;
  5479. }
  5480. /**
  5481. * Opens the modal.
  5482. *
  5483. * @fires ModalDialog#beforemodalopen
  5484. * @fires ModalDialog#modalopen
  5485. */
  5486. ;
  5487. _proto.open = function open() {
  5488. if (!this.opened_) {
  5489. var player = this.player();
  5490. /**
  5491. * Fired just before a `ModalDialog` is opened.
  5492. *
  5493. * @event ModalDialog#beforemodalopen
  5494. * @type {EventTarget~Event}
  5495. */
  5496. this.trigger('beforemodalopen');
  5497. this.opened_ = true; // Fill content if the modal has never opened before and
  5498. // never been filled.
  5499. if (this.options_.fillAlways || !this.hasBeenOpened_ && !this.hasBeenFilled_) {
  5500. this.fill();
  5501. } // If the player was playing, pause it and take note of its previously
  5502. // playing state.
  5503. this.wasPlaying_ = !player.paused();
  5504. if (this.options_.pauseOnOpen && this.wasPlaying_) {
  5505. player.pause();
  5506. }
  5507. this.on('keydown', this.handleKeyDown_); // Hide controls and note if they were enabled.
  5508. this.hadControls_ = player.controls();
  5509. player.controls(false);
  5510. this.show();
  5511. this.conditionalFocus_();
  5512. this.el().setAttribute('aria-hidden', 'false');
  5513. /**
  5514. * Fired just after a `ModalDialog` is opened.
  5515. *
  5516. * @event ModalDialog#modalopen
  5517. * @type {EventTarget~Event}
  5518. */
  5519. this.trigger('modalopen');
  5520. this.hasBeenOpened_ = true;
  5521. }
  5522. }
  5523. /**
  5524. * If the `ModalDialog` is currently open or closed.
  5525. *
  5526. * @param {boolean} [value]
  5527. * If given, it will open (`true`) or close (`false`) the modal.
  5528. *
  5529. * @return {boolean}
  5530. * the current open state of the modaldialog
  5531. */
  5532. ;
  5533. _proto.opened = function opened(value) {
  5534. if (typeof value === 'boolean') {
  5535. this[value ? 'open' : 'close']();
  5536. }
  5537. return this.opened_;
  5538. }
  5539. /**
  5540. * Closes the modal, does nothing if the `ModalDialog` is
  5541. * not open.
  5542. *
  5543. * @fires ModalDialog#beforemodalclose
  5544. * @fires ModalDialog#modalclose
  5545. */
  5546. ;
  5547. _proto.close = function close() {
  5548. if (!this.opened_) {
  5549. return;
  5550. }
  5551. var player = this.player();
  5552. /**
  5553. * Fired just before a `ModalDialog` is closed.
  5554. *
  5555. * @event ModalDialog#beforemodalclose
  5556. * @type {EventTarget~Event}
  5557. */
  5558. this.trigger('beforemodalclose');
  5559. this.opened_ = false;
  5560. if (this.wasPlaying_ && this.options_.pauseOnOpen) {
  5561. player.play();
  5562. }
  5563. this.off('keydown', this.handleKeyDown_);
  5564. if (this.hadControls_) {
  5565. player.controls(true);
  5566. }
  5567. this.hide();
  5568. this.el().setAttribute('aria-hidden', 'true');
  5569. /**
  5570. * Fired just after a `ModalDialog` is closed.
  5571. *
  5572. * @event ModalDialog#modalclose
  5573. * @type {EventTarget~Event}
  5574. */
  5575. this.trigger('modalclose');
  5576. this.conditionalBlur_();
  5577. if (this.options_.temporary) {
  5578. this.dispose();
  5579. }
  5580. }
  5581. /**
  5582. * Check to see if the `ModalDialog` is closeable via the UI.
  5583. *
  5584. * @param {boolean} [value]
  5585. * If given as a boolean, it will set the `closeable` option.
  5586. *
  5587. * @return {boolean}
  5588. * Returns the final value of the closable option.
  5589. */
  5590. ;
  5591. _proto.closeable = function closeable(value) {
  5592. if (typeof value === 'boolean') {
  5593. var closeable = this.closeable_ = !!value;
  5594. var close = this.getChild('closeButton'); // If this is being made closeable and has no close button, add one.
  5595. if (closeable && !close) {
  5596. // The close button should be a child of the modal - not its
  5597. // content element, so temporarily change the content element.
  5598. var temp = this.contentEl_;
  5599. this.contentEl_ = this.el_;
  5600. close = this.addChild('closeButton', {
  5601. controlText: 'Close Modal Dialog'
  5602. });
  5603. this.contentEl_ = temp;
  5604. this.on(close, 'close', this.close_);
  5605. } // If this is being made uncloseable and has a close button, remove it.
  5606. if (!closeable && close) {
  5607. this.off(close, 'close', this.close_);
  5608. this.removeChild(close);
  5609. close.dispose();
  5610. }
  5611. }
  5612. return this.closeable_;
  5613. }
  5614. /**
  5615. * Fill the modal's content element with the modal's "content" option.
  5616. * The content element will be emptied before this change takes place.
  5617. */
  5618. ;
  5619. _proto.fill = function fill() {
  5620. this.fillWith(this.content());
  5621. }
  5622. /**
  5623. * Fill the modal's content element with arbitrary content.
  5624. * The content element will be emptied before this change takes place.
  5625. *
  5626. * @fires ModalDialog#beforemodalfill
  5627. * @fires ModalDialog#modalfill
  5628. *
  5629. * @param {Mixed} [content]
  5630. * The same rules apply to this as apply to the `content` option.
  5631. */
  5632. ;
  5633. _proto.fillWith = function fillWith(content) {
  5634. var contentEl = this.contentEl();
  5635. var parentEl = contentEl.parentNode;
  5636. var nextSiblingEl = contentEl.nextSibling;
  5637. /**
  5638. * Fired just before a `ModalDialog` is filled with content.
  5639. *
  5640. * @event ModalDialog#beforemodalfill
  5641. * @type {EventTarget~Event}
  5642. */
  5643. this.trigger('beforemodalfill');
  5644. this.hasBeenFilled_ = true; // Detach the content element from the DOM before performing
  5645. // manipulation to avoid modifying the live DOM multiple times.
  5646. parentEl.removeChild(contentEl);
  5647. this.empty();
  5648. insertContent(contentEl, content);
  5649. /**
  5650. * Fired just after a `ModalDialog` is filled with content.
  5651. *
  5652. * @event ModalDialog#modalfill
  5653. * @type {EventTarget~Event}
  5654. */
  5655. this.trigger('modalfill'); // Re-inject the re-filled content element.
  5656. if (nextSiblingEl) {
  5657. parentEl.insertBefore(contentEl, nextSiblingEl);
  5658. } else {
  5659. parentEl.appendChild(contentEl);
  5660. } // make sure that the close button is last in the dialog DOM
  5661. var closeButton = this.getChild('closeButton');
  5662. if (closeButton) {
  5663. parentEl.appendChild(closeButton.el_);
  5664. }
  5665. }
  5666. /**
  5667. * Empties the content element. This happens anytime the modal is filled.
  5668. *
  5669. * @fires ModalDialog#beforemodalempty
  5670. * @fires ModalDialog#modalempty
  5671. */
  5672. ;
  5673. _proto.empty = function empty() {
  5674. /**
  5675. * Fired just before a `ModalDialog` is emptied.
  5676. *
  5677. * @event ModalDialog#beforemodalempty
  5678. * @type {EventTarget~Event}
  5679. */
  5680. this.trigger('beforemodalempty');
  5681. emptyEl(this.contentEl());
  5682. /**
  5683. * Fired just after a `ModalDialog` is emptied.
  5684. *
  5685. * @event ModalDialog#modalempty
  5686. * @type {EventTarget~Event}
  5687. */
  5688. this.trigger('modalempty');
  5689. }
  5690. /**
  5691. * Gets or sets the modal content, which gets normalized before being
  5692. * rendered into the DOM.
  5693. *
  5694. * This does not update the DOM or fill the modal, but it is called during
  5695. * that process.
  5696. *
  5697. * @param {Mixed} [value]
  5698. * If defined, sets the internal content value to be used on the
  5699. * next call(s) to `fill`. This value is normalized before being
  5700. * inserted. To "clear" the internal content value, pass `null`.
  5701. *
  5702. * @return {Mixed}
  5703. * The current content of the modal dialog
  5704. */
  5705. ;
  5706. _proto.content = function content(value) {
  5707. if (typeof value !== 'undefined') {
  5708. this.content_ = value;
  5709. }
  5710. return this.content_;
  5711. }
  5712. /**
  5713. * conditionally focus the modal dialog if focus was previously on the player.
  5714. *
  5715. * @private
  5716. */
  5717. ;
  5718. _proto.conditionalFocus_ = function conditionalFocus_() {
  5719. var activeEl = document.activeElement;
  5720. var playerEl = this.player_.el_;
  5721. this.previouslyActiveEl_ = null;
  5722. if (playerEl.contains(activeEl) || playerEl === activeEl) {
  5723. this.previouslyActiveEl_ = activeEl;
  5724. this.focus();
  5725. }
  5726. }
  5727. /**
  5728. * conditionally blur the element and refocus the last focused element
  5729. *
  5730. * @private
  5731. */
  5732. ;
  5733. _proto.conditionalBlur_ = function conditionalBlur_() {
  5734. if (this.previouslyActiveEl_) {
  5735. this.previouslyActiveEl_.focus();
  5736. this.previouslyActiveEl_ = null;
  5737. }
  5738. }
  5739. /**
  5740. * Keydown handler. Attached when modal is focused.
  5741. *
  5742. * @listens keydown
  5743. */
  5744. ;
  5745. _proto.handleKeyDown = function handleKeyDown(event) {
  5746. // Do not allow keydowns to reach out of the modal dialog.
  5747. event.stopPropagation();
  5748. if (keycode.isEventKey(event, 'Escape') && this.closeable()) {
  5749. event.preventDefault();
  5750. this.close();
  5751. return;
  5752. } // exit early if it isn't a tab key
  5753. if (!keycode.isEventKey(event, 'Tab')) {
  5754. return;
  5755. }
  5756. var focusableEls = this.focusableEls_();
  5757. var activeEl = this.el_.querySelector(':focus');
  5758. var focusIndex;
  5759. for (var i = 0; i < focusableEls.length; i++) {
  5760. if (activeEl === focusableEls[i]) {
  5761. focusIndex = i;
  5762. break;
  5763. }
  5764. }
  5765. if (document.activeElement === this.el_) {
  5766. focusIndex = 0;
  5767. }
  5768. if (event.shiftKey && focusIndex === 0) {
  5769. focusableEls[focusableEls.length - 1].focus();
  5770. event.preventDefault();
  5771. } else if (!event.shiftKey && focusIndex === focusableEls.length - 1) {
  5772. focusableEls[0].focus();
  5773. event.preventDefault();
  5774. }
  5775. }
  5776. /**
  5777. * get all focusable elements
  5778. *
  5779. * @private
  5780. */
  5781. ;
  5782. _proto.focusableEls_ = function focusableEls_() {
  5783. var allChildren = this.el_.querySelectorAll('*');
  5784. return Array.prototype.filter.call(allChildren, function (child) {
  5785. return (child instanceof window.HTMLAnchorElement || child instanceof window.HTMLAreaElement) && child.hasAttribute('href') || (child instanceof window.HTMLInputElement || child instanceof window.HTMLSelectElement || child instanceof window.HTMLTextAreaElement || child instanceof window.HTMLButtonElement) && !child.hasAttribute('disabled') || child instanceof window.HTMLIFrameElement || child instanceof window.HTMLObjectElement || child instanceof window.HTMLEmbedElement || child.hasAttribute('tabindex') && child.getAttribute('tabindex') !== -1 || child.hasAttribute('contenteditable');
  5786. });
  5787. };
  5788. return ModalDialog;
  5789. }(Component$1);
  5790. /**
  5791. * Default options for `ModalDialog` default options.
  5792. *
  5793. * @type {Object}
  5794. * @private
  5795. */
  5796. ModalDialog.prototype.options_ = {
  5797. pauseOnOpen: true,
  5798. temporary: true
  5799. };
  5800. Component$1.registerComponent('ModalDialog', ModalDialog);
  5801. /**
  5802. * Common functionaliy between {@link TextTrackList}, {@link AudioTrackList}, and
  5803. * {@link VideoTrackList}
  5804. *
  5805. * @extends EventTarget
  5806. */
  5807. var TrackList = /*#__PURE__*/function (_EventTarget) {
  5808. inheritsLoose(TrackList, _EventTarget);
  5809. /**
  5810. * Create an instance of this class
  5811. *
  5812. * @param {Track[]} tracks
  5813. * A list of tracks to initialize the list with.
  5814. *
  5815. * @abstract
  5816. */
  5817. function TrackList(tracks) {
  5818. var _this;
  5819. if (tracks === void 0) {
  5820. tracks = [];
  5821. }
  5822. _this = _EventTarget.call(this) || this;
  5823. _this.tracks_ = [];
  5824. /**
  5825. * @memberof TrackList
  5826. * @member {number} length
  5827. * The current number of `Track`s in the this Trackist.
  5828. * @instance
  5829. */
  5830. Object.defineProperty(assertThisInitialized(_this), 'length', {
  5831. get: function get() {
  5832. return this.tracks_.length;
  5833. }
  5834. });
  5835. for (var i = 0; i < tracks.length; i++) {
  5836. _this.addTrack(tracks[i]);
  5837. }
  5838. return _this;
  5839. }
  5840. /**
  5841. * Add a {@link Track} to the `TrackList`
  5842. *
  5843. * @param {Track} track
  5844. * The audio, video, or text track to add to the list.
  5845. *
  5846. * @fires TrackList#addtrack
  5847. */
  5848. var _proto = TrackList.prototype;
  5849. _proto.addTrack = function addTrack(track) {
  5850. var _this2 = this;
  5851. var index = this.tracks_.length;
  5852. if (!('' + index in this)) {
  5853. Object.defineProperty(this, index, {
  5854. get: function get() {
  5855. return this.tracks_[index];
  5856. }
  5857. });
  5858. } // Do not add duplicate tracks
  5859. if (this.tracks_.indexOf(track) === -1) {
  5860. this.tracks_.push(track);
  5861. /**
  5862. * Triggered when a track is added to a track list.
  5863. *
  5864. * @event TrackList#addtrack
  5865. * @type {EventTarget~Event}
  5866. * @property {Track} track
  5867. * A reference to track that was added.
  5868. */
  5869. this.trigger({
  5870. track: track,
  5871. type: 'addtrack',
  5872. target: this
  5873. });
  5874. }
  5875. /**
  5876. * Triggered when a track label is changed.
  5877. *
  5878. * @event TrackList#addtrack
  5879. * @type {EventTarget~Event}
  5880. * @property {Track} track
  5881. * A reference to track that was added.
  5882. */
  5883. track.labelchange_ = function () {
  5884. _this2.trigger({
  5885. track: track,
  5886. type: 'labelchange',
  5887. target: _this2
  5888. });
  5889. };
  5890. if (isEvented(track)) {
  5891. track.addEventListener('labelchange', track.labelchange_);
  5892. }
  5893. }
  5894. /**
  5895. * Remove a {@link Track} from the `TrackList`
  5896. *
  5897. * @param {Track} rtrack
  5898. * The audio, video, or text track to remove from the list.
  5899. *
  5900. * @fires TrackList#removetrack
  5901. */
  5902. ;
  5903. _proto.removeTrack = function removeTrack(rtrack) {
  5904. var track;
  5905. for (var i = 0, l = this.length; i < l; i++) {
  5906. if (this[i] === rtrack) {
  5907. track = this[i];
  5908. if (track.off) {
  5909. track.off();
  5910. }
  5911. this.tracks_.splice(i, 1);
  5912. break;
  5913. }
  5914. }
  5915. if (!track) {
  5916. return;
  5917. }
  5918. /**
  5919. * Triggered when a track is removed from track list.
  5920. *
  5921. * @event TrackList#removetrack
  5922. * @type {EventTarget~Event}
  5923. * @property {Track} track
  5924. * A reference to track that was removed.
  5925. */
  5926. this.trigger({
  5927. track: track,
  5928. type: 'removetrack',
  5929. target: this
  5930. });
  5931. }
  5932. /**
  5933. * Get a Track from the TrackList by a tracks id
  5934. *
  5935. * @param {string} id - the id of the track to get
  5936. * @method getTrackById
  5937. * @return {Track}
  5938. * @private
  5939. */
  5940. ;
  5941. _proto.getTrackById = function getTrackById(id) {
  5942. var result = null;
  5943. for (var i = 0, l = this.length; i < l; i++) {
  5944. var track = this[i];
  5945. if (track.id === id) {
  5946. result = track;
  5947. break;
  5948. }
  5949. }
  5950. return result;
  5951. };
  5952. return TrackList;
  5953. }(EventTarget$2);
  5954. /**
  5955. * Triggered when a different track is selected/enabled.
  5956. *
  5957. * @event TrackList#change
  5958. * @type {EventTarget~Event}
  5959. */
  5960. /**
  5961. * Events that can be called with on + eventName. See {@link EventHandler}.
  5962. *
  5963. * @property {Object} TrackList#allowedEvents_
  5964. * @private
  5965. */
  5966. TrackList.prototype.allowedEvents_ = {
  5967. change: 'change',
  5968. addtrack: 'addtrack',
  5969. removetrack: 'removetrack',
  5970. labelchange: 'labelchange'
  5971. }; // emulate attribute EventHandler support to allow for feature detection
  5972. for (var event in TrackList.prototype.allowedEvents_) {
  5973. TrackList.prototype['on' + event] = null;
  5974. }
  5975. /**
  5976. * Anywhere we call this function we diverge from the spec
  5977. * as we only support one enabled audiotrack at a time
  5978. *
  5979. * @param {AudioTrackList} list
  5980. * list to work on
  5981. *
  5982. * @param {AudioTrack} track
  5983. * The track to skip
  5984. *
  5985. * @private
  5986. */
  5987. var disableOthers$1 = function disableOthers(list, track) {
  5988. for (var i = 0; i < list.length; i++) {
  5989. if (!Object.keys(list[i]).length || track.id === list[i].id) {
  5990. continue;
  5991. } // another audio track is enabled, disable it
  5992. list[i].enabled = false;
  5993. }
  5994. };
  5995. /**
  5996. * The current list of {@link AudioTrack} for a media file.
  5997. *
  5998. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist}
  5999. * @extends TrackList
  6000. */
  6001. var AudioTrackList = /*#__PURE__*/function (_TrackList) {
  6002. inheritsLoose(AudioTrackList, _TrackList);
  6003. /**
  6004. * Create an instance of this class.
  6005. *
  6006. * @param {AudioTrack[]} [tracks=[]]
  6007. * A list of `AudioTrack` to instantiate the list with.
  6008. */
  6009. function AudioTrackList(tracks) {
  6010. var _this;
  6011. if (tracks === void 0) {
  6012. tracks = [];
  6013. }
  6014. // make sure only 1 track is enabled
  6015. // sorted from last index to first index
  6016. for (var i = tracks.length - 1; i >= 0; i--) {
  6017. if (tracks[i].enabled) {
  6018. disableOthers$1(tracks, tracks[i]);
  6019. break;
  6020. }
  6021. }
  6022. _this = _TrackList.call(this, tracks) || this;
  6023. _this.changing_ = false;
  6024. return _this;
  6025. }
  6026. /**
  6027. * Add an {@link AudioTrack} to the `AudioTrackList`.
  6028. *
  6029. * @param {AudioTrack} track
  6030. * The AudioTrack to add to the list
  6031. *
  6032. * @fires TrackList#addtrack
  6033. */
  6034. var _proto = AudioTrackList.prototype;
  6035. _proto.addTrack = function addTrack(track) {
  6036. var _this2 = this;
  6037. if (track.enabled) {
  6038. disableOthers$1(this, track);
  6039. }
  6040. _TrackList.prototype.addTrack.call(this, track); // native tracks don't have this
  6041. if (!track.addEventListener) {
  6042. return;
  6043. }
  6044. track.enabledChange_ = function () {
  6045. // when we are disabling other tracks (since we don't support
  6046. // more than one track at a time) we will set changing_
  6047. // to true so that we don't trigger additional change events
  6048. if (_this2.changing_) {
  6049. return;
  6050. }
  6051. _this2.changing_ = true;
  6052. disableOthers$1(_this2, track);
  6053. _this2.changing_ = false;
  6054. _this2.trigger('change');
  6055. };
  6056. /**
  6057. * @listens AudioTrack#enabledchange
  6058. * @fires TrackList#change
  6059. */
  6060. track.addEventListener('enabledchange', track.enabledChange_);
  6061. };
  6062. _proto.removeTrack = function removeTrack(rtrack) {
  6063. _TrackList.prototype.removeTrack.call(this, rtrack);
  6064. if (rtrack.removeEventListener && rtrack.enabledChange_) {
  6065. rtrack.removeEventListener('enabledchange', rtrack.enabledChange_);
  6066. rtrack.enabledChange_ = null;
  6067. }
  6068. };
  6069. return AudioTrackList;
  6070. }(TrackList);
  6071. /**
  6072. * Un-select all other {@link VideoTrack}s that are selected.
  6073. *
  6074. * @param {VideoTrackList} list
  6075. * list to work on
  6076. *
  6077. * @param {VideoTrack} track
  6078. * The track to skip
  6079. *
  6080. * @private
  6081. */
  6082. var disableOthers = function disableOthers(list, track) {
  6083. for (var i = 0; i < list.length; i++) {
  6084. if (!Object.keys(list[i]).length || track.id === list[i].id) {
  6085. continue;
  6086. } // another video track is enabled, disable it
  6087. list[i].selected = false;
  6088. }
  6089. };
  6090. /**
  6091. * The current list of {@link VideoTrack} for a video.
  6092. *
  6093. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist}
  6094. * @extends TrackList
  6095. */
  6096. var VideoTrackList = /*#__PURE__*/function (_TrackList) {
  6097. inheritsLoose(VideoTrackList, _TrackList);
  6098. /**
  6099. * Create an instance of this class.
  6100. *
  6101. * @param {VideoTrack[]} [tracks=[]]
  6102. * A list of `VideoTrack` to instantiate the list with.
  6103. */
  6104. function VideoTrackList(tracks) {
  6105. var _this;
  6106. if (tracks === void 0) {
  6107. tracks = [];
  6108. }
  6109. // make sure only 1 track is enabled
  6110. // sorted from last index to first index
  6111. for (var i = tracks.length - 1; i >= 0; i--) {
  6112. if (tracks[i].selected) {
  6113. disableOthers(tracks, tracks[i]);
  6114. break;
  6115. }
  6116. }
  6117. _this = _TrackList.call(this, tracks) || this;
  6118. _this.changing_ = false;
  6119. /**
  6120. * @member {number} VideoTrackList#selectedIndex
  6121. * The current index of the selected {@link VideoTrack`}.
  6122. */
  6123. Object.defineProperty(assertThisInitialized(_this), 'selectedIndex', {
  6124. get: function get() {
  6125. for (var _i = 0; _i < this.length; _i++) {
  6126. if (this[_i].selected) {
  6127. return _i;
  6128. }
  6129. }
  6130. return -1;
  6131. },
  6132. set: function set() {}
  6133. });
  6134. return _this;
  6135. }
  6136. /**
  6137. * Add a {@link VideoTrack} to the `VideoTrackList`.
  6138. *
  6139. * @param {VideoTrack} track
  6140. * The VideoTrack to add to the list
  6141. *
  6142. * @fires TrackList#addtrack
  6143. */
  6144. var _proto = VideoTrackList.prototype;
  6145. _proto.addTrack = function addTrack(track) {
  6146. var _this2 = this;
  6147. if (track.selected) {
  6148. disableOthers(this, track);
  6149. }
  6150. _TrackList.prototype.addTrack.call(this, track); // native tracks don't have this
  6151. if (!track.addEventListener) {
  6152. return;
  6153. }
  6154. track.selectedChange_ = function () {
  6155. if (_this2.changing_) {
  6156. return;
  6157. }
  6158. _this2.changing_ = true;
  6159. disableOthers(_this2, track);
  6160. _this2.changing_ = false;
  6161. _this2.trigger('change');
  6162. };
  6163. /**
  6164. * @listens VideoTrack#selectedchange
  6165. * @fires TrackList#change
  6166. */
  6167. track.addEventListener('selectedchange', track.selectedChange_);
  6168. };
  6169. _proto.removeTrack = function removeTrack(rtrack) {
  6170. _TrackList.prototype.removeTrack.call(this, rtrack);
  6171. if (rtrack.removeEventListener && rtrack.selectedChange_) {
  6172. rtrack.removeEventListener('selectedchange', rtrack.selectedChange_);
  6173. rtrack.selectedChange_ = null;
  6174. }
  6175. };
  6176. return VideoTrackList;
  6177. }(TrackList);
  6178. /**
  6179. * The current list of {@link TextTrack} for a media file.
  6180. *
  6181. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist}
  6182. * @extends TrackList
  6183. */
  6184. var TextTrackList = /*#__PURE__*/function (_TrackList) {
  6185. inheritsLoose(TextTrackList, _TrackList);
  6186. function TextTrackList() {
  6187. return _TrackList.apply(this, arguments) || this;
  6188. }
  6189. var _proto = TextTrackList.prototype;
  6190. /**
  6191. * Add a {@link TextTrack} to the `TextTrackList`
  6192. *
  6193. * @param {TextTrack} track
  6194. * The text track to add to the list.
  6195. *
  6196. * @fires TrackList#addtrack
  6197. */
  6198. _proto.addTrack = function addTrack(track) {
  6199. var _this = this;
  6200. _TrackList.prototype.addTrack.call(this, track);
  6201. if (!this.queueChange_) {
  6202. this.queueChange_ = function () {
  6203. return _this.queueTrigger('change');
  6204. };
  6205. }
  6206. if (!this.triggerSelectedlanguagechange) {
  6207. this.triggerSelectedlanguagechange_ = function () {
  6208. return _this.trigger('selectedlanguagechange');
  6209. };
  6210. }
  6211. /**
  6212. * @listens TextTrack#modechange
  6213. * @fires TrackList#change
  6214. */
  6215. track.addEventListener('modechange', this.queueChange_);
  6216. var nonLanguageTextTrackKind = ['metadata', 'chapters'];
  6217. if (nonLanguageTextTrackKind.indexOf(track.kind) === -1) {
  6218. track.addEventListener('modechange', this.triggerSelectedlanguagechange_);
  6219. }
  6220. };
  6221. _proto.removeTrack = function removeTrack(rtrack) {
  6222. _TrackList.prototype.removeTrack.call(this, rtrack); // manually remove the event handlers we added
  6223. if (rtrack.removeEventListener) {
  6224. if (this.queueChange_) {
  6225. rtrack.removeEventListener('modechange', this.queueChange_);
  6226. }
  6227. if (this.selectedlanguagechange_) {
  6228. rtrack.removeEventListener('modechange', this.triggerSelectedlanguagechange_);
  6229. }
  6230. }
  6231. };
  6232. return TextTrackList;
  6233. }(TrackList);
  6234. /**
  6235. * @file html-track-element-list.js
  6236. */
  6237. /**
  6238. * The current list of {@link HtmlTrackElement}s.
  6239. */
  6240. var HtmlTrackElementList = /*#__PURE__*/function () {
  6241. /**
  6242. * Create an instance of this class.
  6243. *
  6244. * @param {HtmlTrackElement[]} [tracks=[]]
  6245. * A list of `HtmlTrackElement` to instantiate the list with.
  6246. */
  6247. function HtmlTrackElementList(trackElements) {
  6248. if (trackElements === void 0) {
  6249. trackElements = [];
  6250. }
  6251. this.trackElements_ = [];
  6252. /**
  6253. * @memberof HtmlTrackElementList
  6254. * @member {number} length
  6255. * The current number of `Track`s in the this Trackist.
  6256. * @instance
  6257. */
  6258. Object.defineProperty(this, 'length', {
  6259. get: function get() {
  6260. return this.trackElements_.length;
  6261. }
  6262. });
  6263. for (var i = 0, length = trackElements.length; i < length; i++) {
  6264. this.addTrackElement_(trackElements[i]);
  6265. }
  6266. }
  6267. /**
  6268. * Add an {@link HtmlTrackElement} to the `HtmlTrackElementList`
  6269. *
  6270. * @param {HtmlTrackElement} trackElement
  6271. * The track element to add to the list.
  6272. *
  6273. * @private
  6274. */
  6275. var _proto = HtmlTrackElementList.prototype;
  6276. _proto.addTrackElement_ = function addTrackElement_(trackElement) {
  6277. var index = this.trackElements_.length;
  6278. if (!('' + index in this)) {
  6279. Object.defineProperty(this, index, {
  6280. get: function get() {
  6281. return this.trackElements_[index];
  6282. }
  6283. });
  6284. } // Do not add duplicate elements
  6285. if (this.trackElements_.indexOf(trackElement) === -1) {
  6286. this.trackElements_.push(trackElement);
  6287. }
  6288. }
  6289. /**
  6290. * Get an {@link HtmlTrackElement} from the `HtmlTrackElementList` given an
  6291. * {@link TextTrack}.
  6292. *
  6293. * @param {TextTrack} track
  6294. * The track associated with a track element.
  6295. *
  6296. * @return {HtmlTrackElement|undefined}
  6297. * The track element that was found or undefined.
  6298. *
  6299. * @private
  6300. */
  6301. ;
  6302. _proto.getTrackElementByTrack_ = function getTrackElementByTrack_(track) {
  6303. var trackElement_;
  6304. for (var i = 0, length = this.trackElements_.length; i < length; i++) {
  6305. if (track === this.trackElements_[i].track) {
  6306. trackElement_ = this.trackElements_[i];
  6307. break;
  6308. }
  6309. }
  6310. return trackElement_;
  6311. }
  6312. /**
  6313. * Remove a {@link HtmlTrackElement} from the `HtmlTrackElementList`
  6314. *
  6315. * @param {HtmlTrackElement} trackElement
  6316. * The track element to remove from the list.
  6317. *
  6318. * @private
  6319. */
  6320. ;
  6321. _proto.removeTrackElement_ = function removeTrackElement_(trackElement) {
  6322. for (var i = 0, length = this.trackElements_.length; i < length; i++) {
  6323. if (trackElement === this.trackElements_[i]) {
  6324. if (this.trackElements_[i].track && typeof this.trackElements_[i].track.off === 'function') {
  6325. this.trackElements_[i].track.off();
  6326. }
  6327. if (typeof this.trackElements_[i].off === 'function') {
  6328. this.trackElements_[i].off();
  6329. }
  6330. this.trackElements_.splice(i, 1);
  6331. break;
  6332. }
  6333. }
  6334. };
  6335. return HtmlTrackElementList;
  6336. }();
  6337. /**
  6338. * @file text-track-cue-list.js
  6339. */
  6340. /**
  6341. * @typedef {Object} TextTrackCueList~TextTrackCue
  6342. *
  6343. * @property {string} id
  6344. * The unique id for this text track cue
  6345. *
  6346. * @property {number} startTime
  6347. * The start time for this text track cue
  6348. *
  6349. * @property {number} endTime
  6350. * The end time for this text track cue
  6351. *
  6352. * @property {boolean} pauseOnExit
  6353. * Pause when the end time is reached if true.
  6354. *
  6355. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcue}
  6356. */
  6357. /**
  6358. * A List of TextTrackCues.
  6359. *
  6360. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist}
  6361. */
  6362. var TextTrackCueList = /*#__PURE__*/function () {
  6363. /**
  6364. * Create an instance of this class..
  6365. *
  6366. * @param {Array} cues
  6367. * A list of cues to be initialized with
  6368. */
  6369. function TextTrackCueList(cues) {
  6370. TextTrackCueList.prototype.setCues_.call(this, cues);
  6371. /**
  6372. * @memberof TextTrackCueList
  6373. * @member {number} length
  6374. * The current number of `TextTrackCue`s in the TextTrackCueList.
  6375. * @instance
  6376. */
  6377. Object.defineProperty(this, 'length', {
  6378. get: function get() {
  6379. return this.length_;
  6380. }
  6381. });
  6382. }
  6383. /**
  6384. * A setter for cues in this list. Creates getters
  6385. * an an index for the cues.
  6386. *
  6387. * @param {Array} cues
  6388. * An array of cues to set
  6389. *
  6390. * @private
  6391. */
  6392. var _proto = TextTrackCueList.prototype;
  6393. _proto.setCues_ = function setCues_(cues) {
  6394. var oldLength = this.length || 0;
  6395. var i = 0;
  6396. var l = cues.length;
  6397. this.cues_ = cues;
  6398. this.length_ = cues.length;
  6399. var defineProp = function defineProp(index) {
  6400. if (!('' + index in this)) {
  6401. Object.defineProperty(this, '' + index, {
  6402. get: function get() {
  6403. return this.cues_[index];
  6404. }
  6405. });
  6406. }
  6407. };
  6408. if (oldLength < l) {
  6409. i = oldLength;
  6410. for (; i < l; i++) {
  6411. defineProp.call(this, i);
  6412. }
  6413. }
  6414. }
  6415. /**
  6416. * Get a `TextTrackCue` that is currently in the `TextTrackCueList` by id.
  6417. *
  6418. * @param {string} id
  6419. * The id of the cue that should be searched for.
  6420. *
  6421. * @return {TextTrackCueList~TextTrackCue|null}
  6422. * A single cue or null if none was found.
  6423. */
  6424. ;
  6425. _proto.getCueById = function getCueById(id) {
  6426. var result = null;
  6427. for (var i = 0, l = this.length; i < l; i++) {
  6428. var cue = this[i];
  6429. if (cue.id === id) {
  6430. result = cue;
  6431. break;
  6432. }
  6433. }
  6434. return result;
  6435. };
  6436. return TextTrackCueList;
  6437. }();
  6438. /**
  6439. * @file track-kinds.js
  6440. */
  6441. /**
  6442. * All possible `VideoTrackKind`s
  6443. *
  6444. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-videotrack-kind
  6445. * @typedef VideoTrack~Kind
  6446. * @enum
  6447. */
  6448. var VideoTrackKind = {
  6449. alternative: 'alternative',
  6450. captions: 'captions',
  6451. main: 'main',
  6452. sign: 'sign',
  6453. subtitles: 'subtitles',
  6454. commentary: 'commentary'
  6455. };
  6456. /**
  6457. * All possible `AudioTrackKind`s
  6458. *
  6459. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-audiotrack-kind
  6460. * @typedef AudioTrack~Kind
  6461. * @enum
  6462. */
  6463. var AudioTrackKind = {
  6464. 'alternative': 'alternative',
  6465. 'descriptions': 'descriptions',
  6466. 'main': 'main',
  6467. 'main-desc': 'main-desc',
  6468. 'translation': 'translation',
  6469. 'commentary': 'commentary'
  6470. };
  6471. /**
  6472. * All possible `TextTrackKind`s
  6473. *
  6474. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-texttrack-kind
  6475. * @typedef TextTrack~Kind
  6476. * @enum
  6477. */
  6478. var TextTrackKind = {
  6479. subtitles: 'subtitles',
  6480. captions: 'captions',
  6481. descriptions: 'descriptions',
  6482. chapters: 'chapters',
  6483. metadata: 'metadata'
  6484. };
  6485. /**
  6486. * All possible `TextTrackMode`s
  6487. *
  6488. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode
  6489. * @typedef TextTrack~Mode
  6490. * @enum
  6491. */
  6492. var TextTrackMode = {
  6493. disabled: 'disabled',
  6494. hidden: 'hidden',
  6495. showing: 'showing'
  6496. };
  6497. /**
  6498. * A Track class that contains all of the common functionality for {@link AudioTrack},
  6499. * {@link VideoTrack}, and {@link TextTrack}.
  6500. *
  6501. * > Note: This class should not be used directly
  6502. *
  6503. * @see {@link https://html.spec.whatwg.org/multipage/embedded-content.html}
  6504. * @extends EventTarget
  6505. * @abstract
  6506. */
  6507. var Track = /*#__PURE__*/function (_EventTarget) {
  6508. inheritsLoose(Track, _EventTarget);
  6509. /**
  6510. * Create an instance of this class.
  6511. *
  6512. * @param {Object} [options={}]
  6513. * Object of option names and values
  6514. *
  6515. * @param {string} [options.kind='']
  6516. * A valid kind for the track type you are creating.
  6517. *
  6518. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  6519. * A unique id for this AudioTrack.
  6520. *
  6521. * @param {string} [options.label='']
  6522. * The menu label for this track.
  6523. *
  6524. * @param {string} [options.language='']
  6525. * A valid two character language code.
  6526. *
  6527. * @abstract
  6528. */
  6529. function Track(options) {
  6530. var _this;
  6531. if (options === void 0) {
  6532. options = {};
  6533. }
  6534. _this = _EventTarget.call(this) || this;
  6535. var trackProps = {
  6536. id: options.id || 'vjs_track_' + newGUID(),
  6537. kind: options.kind || '',
  6538. language: options.language || ''
  6539. };
  6540. var label = options.label || '';
  6541. /**
  6542. * @memberof Track
  6543. * @member {string} id
  6544. * The id of this track. Cannot be changed after creation.
  6545. * @instance
  6546. *
  6547. * @readonly
  6548. */
  6549. /**
  6550. * @memberof Track
  6551. * @member {string} kind
  6552. * The kind of track that this is. Cannot be changed after creation.
  6553. * @instance
  6554. *
  6555. * @readonly
  6556. */
  6557. /**
  6558. * @memberof Track
  6559. * @member {string} language
  6560. * The two letter language code for this track. Cannot be changed after
  6561. * creation.
  6562. * @instance
  6563. *
  6564. * @readonly
  6565. */
  6566. var _loop = function _loop(key) {
  6567. Object.defineProperty(assertThisInitialized(_this), key, {
  6568. get: function get() {
  6569. return trackProps[key];
  6570. },
  6571. set: function set() {}
  6572. });
  6573. };
  6574. for (var key in trackProps) {
  6575. _loop(key);
  6576. }
  6577. /**
  6578. * @memberof Track
  6579. * @member {string} label
  6580. * The label of this track. Cannot be changed after creation.
  6581. * @instance
  6582. *
  6583. * @fires Track#labelchange
  6584. */
  6585. Object.defineProperty(assertThisInitialized(_this), 'label', {
  6586. get: function get() {
  6587. return label;
  6588. },
  6589. set: function set(newLabel) {
  6590. if (newLabel !== label) {
  6591. label = newLabel;
  6592. /**
  6593. * An event that fires when label changes on this track.
  6594. *
  6595. * > Note: This is not part of the spec!
  6596. *
  6597. * @event Track#labelchange
  6598. * @type {EventTarget~Event}
  6599. */
  6600. this.trigger('labelchange');
  6601. }
  6602. }
  6603. });
  6604. return _this;
  6605. }
  6606. return Track;
  6607. }(EventTarget$2);
  6608. /**
  6609. * @file url.js
  6610. * @module url
  6611. */
  6612. /**
  6613. * @typedef {Object} url:URLObject
  6614. *
  6615. * @property {string} protocol
  6616. * The protocol of the url that was parsed.
  6617. *
  6618. * @property {string} hostname
  6619. * The hostname of the url that was parsed.
  6620. *
  6621. * @property {string} port
  6622. * The port of the url that was parsed.
  6623. *
  6624. * @property {string} pathname
  6625. * The pathname of the url that was parsed.
  6626. *
  6627. * @property {string} search
  6628. * The search query of the url that was parsed.
  6629. *
  6630. * @property {string} hash
  6631. * The hash of the url that was parsed.
  6632. *
  6633. * @property {string} host
  6634. * The host of the url that was parsed.
  6635. */
  6636. /**
  6637. * Resolve and parse the elements of a URL.
  6638. *
  6639. * @function
  6640. * @param {String} url
  6641. * The url to parse
  6642. *
  6643. * @return {url:URLObject}
  6644. * An object of url details
  6645. */
  6646. var parseUrl = function parseUrl(url) {
  6647. // This entire method can be replace with URL once we are able to drop IE11
  6648. var props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host']; // add the url to an anchor and let the browser parse the URL
  6649. var a = document.createElement('a');
  6650. a.href = url; // Copy the specific URL properties to a new object
  6651. // This is also needed for IE because the anchor loses its
  6652. // properties when it's removed from the dom
  6653. var details = {};
  6654. for (var i = 0; i < props.length; i++) {
  6655. details[props[i]] = a[props[i]];
  6656. } // IE adds the port to the host property unlike everyone else. If
  6657. // a port identifier is added for standard ports, strip it.
  6658. if (details.protocol === 'http:') {
  6659. details.host = details.host.replace(/:80$/, '');
  6660. }
  6661. if (details.protocol === 'https:') {
  6662. details.host = details.host.replace(/:443$/, '');
  6663. }
  6664. if (!details.protocol) {
  6665. details.protocol = window.location.protocol;
  6666. }
  6667. /* istanbul ignore if */
  6668. if (!details.host) {
  6669. details.host = window.location.host;
  6670. }
  6671. return details;
  6672. };
  6673. /**
  6674. * Get absolute version of relative URL. Used to tell Flash the correct URL.
  6675. *
  6676. * @function
  6677. * @param {string} url
  6678. * URL to make absolute
  6679. *
  6680. * @return {string}
  6681. * Absolute URL
  6682. *
  6683. * @see http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue
  6684. */
  6685. var getAbsoluteURL = function getAbsoluteURL(url) {
  6686. // Check if absolute URL
  6687. if (!url.match(/^https?:\/\//)) {
  6688. // Convert to absolute URL. Flash hosted off-site needs an absolute URL.
  6689. // add the url to an anchor and let the browser parse the URL
  6690. var a = document.createElement('a');
  6691. a.href = url;
  6692. url = a.href;
  6693. }
  6694. return url;
  6695. };
  6696. /**
  6697. * Returns the extension of the passed file name. It will return an empty string
  6698. * if passed an invalid path.
  6699. *
  6700. * @function
  6701. * @param {string} path
  6702. * The fileName path like '/path/to/file.mp4'
  6703. *
  6704. * @return {string}
  6705. * The extension in lower case or an empty string if no
  6706. * extension could be found.
  6707. */
  6708. var getFileExtension = function getFileExtension(path) {
  6709. if (typeof path === 'string') {
  6710. var splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/;
  6711. var pathParts = splitPathRe.exec(path);
  6712. if (pathParts) {
  6713. return pathParts.pop().toLowerCase();
  6714. }
  6715. }
  6716. return '';
  6717. };
  6718. /**
  6719. * Returns whether the url passed is a cross domain request or not.
  6720. *
  6721. * @function
  6722. * @param {string} url
  6723. * The url to check.
  6724. *
  6725. * @param {Object} [winLoc]
  6726. * the domain to check the url against, defaults to window.location
  6727. *
  6728. * @param {string} [winLoc.protocol]
  6729. * The window location protocol defaults to window.location.protocol
  6730. *
  6731. * @param {string} [winLoc.host]
  6732. * The window location host defaults to window.location.host
  6733. *
  6734. * @return {boolean}
  6735. * Whether it is a cross domain request or not.
  6736. */
  6737. var isCrossOrigin = function isCrossOrigin(url, winLoc) {
  6738. if (winLoc === void 0) {
  6739. winLoc = window.location;
  6740. }
  6741. var urlInfo = parseUrl(url); // IE8 protocol relative urls will return ':' for protocol
  6742. var srcProtocol = urlInfo.protocol === ':' ? winLoc.protocol : urlInfo.protocol; // Check if url is for another domain/origin
  6743. // IE8 doesn't know location.origin, so we won't rely on it here
  6744. var crossOrigin = srcProtocol + urlInfo.host !== winLoc.protocol + winLoc.host;
  6745. return crossOrigin;
  6746. };
  6747. var Url = /*#__PURE__*/Object.freeze({
  6748. __proto__: null,
  6749. parseUrl: parseUrl,
  6750. getAbsoluteURL: getAbsoluteURL,
  6751. getFileExtension: getFileExtension,
  6752. isCrossOrigin: isCrossOrigin
  6753. });
  6754. var win;
  6755. if (typeof window !== "undefined") {
  6756. win = window;
  6757. } else if (typeof commonjsGlobal !== "undefined") {
  6758. win = commonjsGlobal;
  6759. } else if (typeof self !== "undefined") {
  6760. win = self;
  6761. } else {
  6762. win = {};
  6763. }
  6764. var window_1 = win;
  6765. var isFunction_1 = isFunction;
  6766. var toString = Object.prototype.toString;
  6767. function isFunction(fn) {
  6768. if (!fn) {
  6769. return false;
  6770. }
  6771. var string = toString.call(fn);
  6772. return string === '[object Function]' || typeof fn === 'function' && string !== '[object RegExp]' || typeof window !== 'undefined' && ( // IE8 and below
  6773. fn === window.setTimeout || fn === window.alert || fn === window.confirm || fn === window.prompt);
  6774. }
  6775. var httpResponseHandler = function httpResponseHandler(callback, decodeResponseBody) {
  6776. if (decodeResponseBody === void 0) {
  6777. decodeResponseBody = false;
  6778. }
  6779. return function (err, response, responseBody) {
  6780. // if the XHR failed, return that error
  6781. if (err) {
  6782. callback(err);
  6783. return;
  6784. } // if the HTTP status code is 4xx or 5xx, the request also failed
  6785. if (response.statusCode >= 400 && response.statusCode <= 599) {
  6786. var cause = responseBody;
  6787. if (decodeResponseBody) {
  6788. if (window_1.TextDecoder) {
  6789. var charset = getCharset(response.headers && response.headers['content-type']);
  6790. try {
  6791. cause = new TextDecoder(charset).decode(responseBody);
  6792. } catch (e) {}
  6793. } else {
  6794. cause = String.fromCharCode.apply(null, new Uint8Array(responseBody));
  6795. }
  6796. }
  6797. callback({
  6798. cause: cause
  6799. });
  6800. return;
  6801. } // otherwise, request succeeded
  6802. callback(null, responseBody);
  6803. };
  6804. };
  6805. function getCharset(contentTypeHeader) {
  6806. if (contentTypeHeader === void 0) {
  6807. contentTypeHeader = '';
  6808. }
  6809. return contentTypeHeader.toLowerCase().split(';').reduce(function (charset, contentType) {
  6810. var _contentType$split = contentType.split('='),
  6811. type = _contentType$split[0],
  6812. value = _contentType$split[1];
  6813. if (type.trim() === 'charset') {
  6814. return value.trim();
  6815. }
  6816. return charset;
  6817. }, 'utf-8');
  6818. }
  6819. var httpHandler = httpResponseHandler;
  6820. createXHR.httpHandler = httpHandler;
  6821. /**
  6822. * @license
  6823. * slighly modified parse-headers 2.0.2 <https://github.com/kesla/parse-headers/>
  6824. * Copyright (c) 2014 David Björklund
  6825. * Available under the MIT license
  6826. * <https://github.com/kesla/parse-headers/blob/master/LICENCE>
  6827. */
  6828. var parseHeaders = function parseHeaders(headers) {
  6829. var result = {};
  6830. if (!headers) {
  6831. return result;
  6832. }
  6833. headers.trim().split('\n').forEach(function (row) {
  6834. var index = row.indexOf(':');
  6835. var key = row.slice(0, index).trim().toLowerCase();
  6836. var value = row.slice(index + 1).trim();
  6837. if (typeof result[key] === 'undefined') {
  6838. result[key] = value;
  6839. } else if (Array.isArray(result[key])) {
  6840. result[key].push(value);
  6841. } else {
  6842. result[key] = [result[key], value];
  6843. }
  6844. });
  6845. return result;
  6846. };
  6847. var lib = createXHR; // Allow use of default import syntax in TypeScript
  6848. var default_1 = createXHR;
  6849. createXHR.XMLHttpRequest = window_1.XMLHttpRequest || noop$1;
  6850. createXHR.XDomainRequest = "withCredentials" in new createXHR.XMLHttpRequest() ? createXHR.XMLHttpRequest : window_1.XDomainRequest;
  6851. forEachArray(["get", "put", "post", "patch", "head", "delete"], function (method) {
  6852. createXHR[method === "delete" ? "del" : method] = function (uri, options, callback) {
  6853. options = initParams(uri, options, callback);
  6854. options.method = method.toUpperCase();
  6855. return _createXHR(options);
  6856. };
  6857. });
  6858. function forEachArray(array, iterator) {
  6859. for (var i = 0; i < array.length; i++) {
  6860. iterator(array[i]);
  6861. }
  6862. }
  6863. function isEmpty(obj) {
  6864. for (var i in obj) {
  6865. if (obj.hasOwnProperty(i)) return false;
  6866. }
  6867. return true;
  6868. }
  6869. function initParams(uri, options, callback) {
  6870. var params = uri;
  6871. if (isFunction_1(options)) {
  6872. callback = options;
  6873. if (typeof uri === "string") {
  6874. params = {
  6875. uri: uri
  6876. };
  6877. }
  6878. } else {
  6879. params = _extends_1({}, options, {
  6880. uri: uri
  6881. });
  6882. }
  6883. params.callback = callback;
  6884. return params;
  6885. }
  6886. function createXHR(uri, options, callback) {
  6887. options = initParams(uri, options, callback);
  6888. return _createXHR(options);
  6889. }
  6890. function _createXHR(options) {
  6891. if (typeof options.callback === "undefined") {
  6892. throw new Error("callback argument missing");
  6893. }
  6894. var called = false;
  6895. var callback = function cbOnce(err, response, body) {
  6896. if (!called) {
  6897. called = true;
  6898. options.callback(err, response, body);
  6899. }
  6900. };
  6901. function readystatechange() {
  6902. if (xhr.readyState === 4) {
  6903. setTimeout(loadFunc, 0);
  6904. }
  6905. }
  6906. function getBody() {
  6907. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  6908. var body = undefined;
  6909. if (xhr.response) {
  6910. body = xhr.response;
  6911. } else {
  6912. body = xhr.responseText || getXml(xhr);
  6913. }
  6914. if (isJson) {
  6915. try {
  6916. body = JSON.parse(body);
  6917. } catch (e) {}
  6918. }
  6919. return body;
  6920. }
  6921. function errorFunc(evt) {
  6922. clearTimeout(timeoutTimer);
  6923. if (!(evt instanceof Error)) {
  6924. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error"));
  6925. }
  6926. evt.statusCode = 0;
  6927. return callback(evt, failureResponse);
  6928. } // will load the data & process the response in a special response object
  6929. function loadFunc() {
  6930. if (aborted) return;
  6931. var status;
  6932. clearTimeout(timeoutTimer);
  6933. if (options.useXDR && xhr.status === undefined) {
  6934. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  6935. status = 200;
  6936. } else {
  6937. status = xhr.status === 1223 ? 204 : xhr.status;
  6938. }
  6939. var response = failureResponse;
  6940. var err = null;
  6941. if (status !== 0) {
  6942. response = {
  6943. body: getBody(),
  6944. statusCode: status,
  6945. method: method,
  6946. headers: {},
  6947. url: uri,
  6948. rawRequest: xhr
  6949. };
  6950. if (xhr.getAllResponseHeaders) {
  6951. //remember xhr can in fact be XDR for CORS in IE
  6952. response.headers = parseHeaders(xhr.getAllResponseHeaders());
  6953. }
  6954. } else {
  6955. err = new Error("Internal XMLHttpRequest Error");
  6956. }
  6957. return callback(err, response, response.body);
  6958. }
  6959. var xhr = options.xhr || null;
  6960. if (!xhr) {
  6961. if (options.cors || options.useXDR) {
  6962. xhr = new createXHR.XDomainRequest();
  6963. } else {
  6964. xhr = new createXHR.XMLHttpRequest();
  6965. }
  6966. }
  6967. var key;
  6968. var aborted;
  6969. var uri = xhr.url = options.uri || options.url;
  6970. var method = xhr.method = options.method || "GET";
  6971. var body = options.body || options.data;
  6972. var headers = xhr.headers = options.headers || {};
  6973. var sync = !!options.sync;
  6974. var isJson = false;
  6975. var timeoutTimer;
  6976. var failureResponse = {
  6977. body: undefined,
  6978. headers: {},
  6979. statusCode: 0,
  6980. method: method,
  6981. url: uri,
  6982. rawRequest: xhr
  6983. };
  6984. if ("json" in options && options.json !== false) {
  6985. isJson = true;
  6986. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json"); //Don't override existing accept header declared by user
  6987. if (method !== "GET" && method !== "HEAD") {
  6988. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json"); //Don't override existing accept header declared by user
  6989. body = JSON.stringify(options.json === true ? body : options.json);
  6990. }
  6991. }
  6992. xhr.onreadystatechange = readystatechange;
  6993. xhr.onload = loadFunc;
  6994. xhr.onerror = errorFunc; // IE9 must have onprogress be set to a unique function.
  6995. xhr.onprogress = function () {// IE must die
  6996. };
  6997. xhr.onabort = function () {
  6998. aborted = true;
  6999. };
  7000. xhr.ontimeout = errorFunc;
  7001. xhr.open(method, uri, !sync, options.username, options.password); //has to be after open
  7002. if (!sync) {
  7003. xhr.withCredentials = !!options.withCredentials;
  7004. } // Cannot set timeout with sync request
  7005. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  7006. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  7007. if (!sync && options.timeout > 0) {
  7008. timeoutTimer = setTimeout(function () {
  7009. if (aborted) return;
  7010. aborted = true; //IE9 may still call readystatechange
  7011. xhr.abort("timeout");
  7012. var e = new Error("XMLHttpRequest timeout");
  7013. e.code = "ETIMEDOUT";
  7014. errorFunc(e);
  7015. }, options.timeout);
  7016. }
  7017. if (xhr.setRequestHeader) {
  7018. for (key in headers) {
  7019. if (headers.hasOwnProperty(key)) {
  7020. xhr.setRequestHeader(key, headers[key]);
  7021. }
  7022. }
  7023. } else if (options.headers && !isEmpty(options.headers)) {
  7024. throw new Error("Headers cannot be set on an XDomainRequest object");
  7025. }
  7026. if ("responseType" in options) {
  7027. xhr.responseType = options.responseType;
  7028. }
  7029. if ("beforeSend" in options && typeof options.beforeSend === "function") {
  7030. options.beforeSend(xhr);
  7031. } // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  7032. // XMLHttpRequest spec says to pass null as body to indicate no body
  7033. // See https://github.com/naugtur/xhr/issues/100.
  7034. xhr.send(body || null);
  7035. return xhr;
  7036. }
  7037. function getXml(xhr) {
  7038. // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException"
  7039. // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.
  7040. try {
  7041. if (xhr.responseType === "document") {
  7042. return xhr.responseXML;
  7043. }
  7044. var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror";
  7045. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  7046. return xhr.responseXML;
  7047. }
  7048. } catch (e) {}
  7049. return null;
  7050. }
  7051. function noop$1() {}
  7052. lib["default"] = default_1;
  7053. /**
  7054. * Takes a webvtt file contents and parses it into cues
  7055. *
  7056. * @param {string} srcContent
  7057. * webVTT file contents
  7058. *
  7059. * @param {TextTrack} track
  7060. * TextTrack to add cues to. Cues come from the srcContent.
  7061. *
  7062. * @private
  7063. */
  7064. var parseCues = function parseCues(srcContent, track) {
  7065. var parser = new window.WebVTT.Parser(window, window.vttjs, window.WebVTT.StringDecoder());
  7066. var errors = [];
  7067. parser.oncue = function (cue) {
  7068. track.addCue(cue);
  7069. };
  7070. parser.onparsingerror = function (error) {
  7071. errors.push(error);
  7072. };
  7073. parser.onflush = function () {
  7074. track.trigger({
  7075. type: 'loadeddata',
  7076. target: track
  7077. });
  7078. };
  7079. parser.parse(srcContent);
  7080. if (errors.length > 0) {
  7081. if (window.console && window.console.groupCollapsed) {
  7082. window.console.groupCollapsed("Text Track parsing errors for " + track.src);
  7083. }
  7084. errors.forEach(function (error) {
  7085. return log$1.error(error);
  7086. });
  7087. if (window.console && window.console.groupEnd) {
  7088. window.console.groupEnd();
  7089. }
  7090. }
  7091. parser.flush();
  7092. };
  7093. /**
  7094. * Load a `TextTrack` from a specified url.
  7095. *
  7096. * @param {string} src
  7097. * Url to load track from.
  7098. *
  7099. * @param {TextTrack} track
  7100. * Track to add cues to. Comes from the content at the end of `url`.
  7101. *
  7102. * @private
  7103. */
  7104. var loadTrack = function loadTrack(src, track) {
  7105. var opts = {
  7106. uri: src
  7107. };
  7108. var crossOrigin = isCrossOrigin(src);
  7109. if (crossOrigin) {
  7110. opts.cors = crossOrigin;
  7111. }
  7112. var withCredentials = track.tech_.crossOrigin() === 'use-credentials';
  7113. if (withCredentials) {
  7114. opts.withCredentials = withCredentials;
  7115. }
  7116. lib(opts, bind(this, function (err, response, responseBody) {
  7117. if (err) {
  7118. return log$1.error(err, response);
  7119. }
  7120. track.loaded_ = true; // Make sure that vttjs has loaded, otherwise, wait till it finished loading
  7121. // NOTE: this is only used for the alt/video.novtt.js build
  7122. if (typeof window.WebVTT !== 'function') {
  7123. if (track.tech_) {
  7124. // to prevent use before define eslint error, we define loadHandler
  7125. // as a let here
  7126. track.tech_.any(['vttjsloaded', 'vttjserror'], function (event) {
  7127. if (event.type === 'vttjserror') {
  7128. log$1.error("vttjs failed to load, stopping trying to process " + track.src);
  7129. return;
  7130. }
  7131. return parseCues(responseBody, track);
  7132. });
  7133. }
  7134. } else {
  7135. parseCues(responseBody, track);
  7136. }
  7137. }));
  7138. };
  7139. /**
  7140. * A representation of a single `TextTrack`.
  7141. *
  7142. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack}
  7143. * @extends Track
  7144. */
  7145. var TextTrack = /*#__PURE__*/function (_Track) {
  7146. inheritsLoose(TextTrack, _Track);
  7147. /**
  7148. * Create an instance of this class.
  7149. *
  7150. * @param {Object} options={}
  7151. * Object of option names and values
  7152. *
  7153. * @param {Tech} options.tech
  7154. * A reference to the tech that owns this TextTrack.
  7155. *
  7156. * @param {TextTrack~Kind} [options.kind='subtitles']
  7157. * A valid text track kind.
  7158. *
  7159. * @param {TextTrack~Mode} [options.mode='disabled']
  7160. * A valid text track mode.
  7161. *
  7162. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7163. * A unique id for this TextTrack.
  7164. *
  7165. * @param {string} [options.label='']
  7166. * The menu label for this track.
  7167. *
  7168. * @param {string} [options.language='']
  7169. * A valid two character language code.
  7170. *
  7171. * @param {string} [options.srclang='']
  7172. * A valid two character language code. An alternative, but deprioritized
  7173. * version of `options.language`
  7174. *
  7175. * @param {string} [options.src]
  7176. * A url to TextTrack cues.
  7177. *
  7178. * @param {boolean} [options.default]
  7179. * If this track should default to on or off.
  7180. */
  7181. function TextTrack(options) {
  7182. var _this;
  7183. if (options === void 0) {
  7184. options = {};
  7185. }
  7186. if (!options.tech) {
  7187. throw new Error('A tech was not provided.');
  7188. }
  7189. var settings = mergeOptions$3(options, {
  7190. kind: TextTrackKind[options.kind] || 'subtitles',
  7191. language: options.language || options.srclang || ''
  7192. });
  7193. var mode = TextTrackMode[settings.mode] || 'disabled';
  7194. var default_ = settings["default"];
  7195. if (settings.kind === 'metadata' || settings.kind === 'chapters') {
  7196. mode = 'hidden';
  7197. }
  7198. _this = _Track.call(this, settings) || this;
  7199. _this.tech_ = settings.tech;
  7200. _this.cues_ = [];
  7201. _this.activeCues_ = [];
  7202. _this.preload_ = _this.tech_.preloadTextTracks !== false;
  7203. var cues = new TextTrackCueList(_this.cues_);
  7204. var activeCues = new TextTrackCueList(_this.activeCues_);
  7205. var changed = false;
  7206. _this.timeupdateHandler = bind(assertThisInitialized(_this), function (event) {
  7207. if (event === void 0) {
  7208. event = {};
  7209. }
  7210. if (this.tech_.isDisposed()) {
  7211. return;
  7212. }
  7213. if (!this.tech_.isReady_) {
  7214. if (event.type !== 'timeupdate') {
  7215. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  7216. }
  7217. return;
  7218. } // Accessing this.activeCues for the side-effects of updating itself
  7219. // due to its nature as a getter function. Do not remove or cues will
  7220. // stop updating!
  7221. // Use the setter to prevent deletion from uglify (pure_getters rule)
  7222. this.activeCues = this.activeCues;
  7223. if (changed) {
  7224. this.trigger('cuechange');
  7225. changed = false;
  7226. }
  7227. if (event.type !== 'timeupdate') {
  7228. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler);
  7229. }
  7230. });
  7231. var disposeHandler = function disposeHandler() {
  7232. _this.stopTracking();
  7233. };
  7234. _this.tech_.one('dispose', disposeHandler);
  7235. if (mode !== 'disabled') {
  7236. _this.startTracking();
  7237. }
  7238. Object.defineProperties(assertThisInitialized(_this), {
  7239. /**
  7240. * @memberof TextTrack
  7241. * @member {boolean} default
  7242. * If this track was set to be on or off by default. Cannot be changed after
  7243. * creation.
  7244. * @instance
  7245. *
  7246. * @readonly
  7247. */
  7248. "default": {
  7249. get: function get() {
  7250. return default_;
  7251. },
  7252. set: function set() {}
  7253. },
  7254. /**
  7255. * @memberof TextTrack
  7256. * @member {string} mode
  7257. * Set the mode of this TextTrack to a valid {@link TextTrack~Mode}. Will
  7258. * not be set if setting to an invalid mode.
  7259. * @instance
  7260. *
  7261. * @fires TextTrack#modechange
  7262. */
  7263. mode: {
  7264. get: function get() {
  7265. return mode;
  7266. },
  7267. set: function set(newMode) {
  7268. if (!TextTrackMode[newMode]) {
  7269. return;
  7270. }
  7271. if (mode === newMode) {
  7272. return;
  7273. }
  7274. mode = newMode;
  7275. if (!this.preload_ && mode !== 'disabled' && this.cues.length === 0) {
  7276. // On-demand load.
  7277. loadTrack(this.src, this);
  7278. }
  7279. this.stopTracking();
  7280. if (mode !== 'disabled') {
  7281. this.startTracking();
  7282. }
  7283. /**
  7284. * An event that fires when mode changes on this track. This allows
  7285. * the TextTrackList that holds this track to act accordingly.
  7286. *
  7287. * > Note: This is not part of the spec!
  7288. *
  7289. * @event TextTrack#modechange
  7290. * @type {EventTarget~Event}
  7291. */
  7292. this.trigger('modechange');
  7293. }
  7294. },
  7295. /**
  7296. * @memberof TextTrack
  7297. * @member {TextTrackCueList} cues
  7298. * The text track cue list for this TextTrack.
  7299. * @instance
  7300. */
  7301. cues: {
  7302. get: function get() {
  7303. if (!this.loaded_) {
  7304. return null;
  7305. }
  7306. return cues;
  7307. },
  7308. set: function set() {}
  7309. },
  7310. /**
  7311. * @memberof TextTrack
  7312. * @member {TextTrackCueList} activeCues
  7313. * The list text track cues that are currently active for this TextTrack.
  7314. * @instance
  7315. */
  7316. activeCues: {
  7317. get: function get() {
  7318. if (!this.loaded_) {
  7319. return null;
  7320. } // nothing to do
  7321. if (this.cues.length === 0) {
  7322. return activeCues;
  7323. }
  7324. var ct = this.tech_.currentTime();
  7325. var active = [];
  7326. for (var i = 0, l = this.cues.length; i < l; i++) {
  7327. var cue = this.cues[i];
  7328. if (cue.startTime <= ct && cue.endTime >= ct) {
  7329. active.push(cue);
  7330. } else if (cue.startTime === cue.endTime && cue.startTime <= ct && cue.startTime + 0.5 >= ct) {
  7331. active.push(cue);
  7332. }
  7333. }
  7334. changed = false;
  7335. if (active.length !== this.activeCues_.length) {
  7336. changed = true;
  7337. } else {
  7338. for (var _i = 0; _i < active.length; _i++) {
  7339. if (this.activeCues_.indexOf(active[_i]) === -1) {
  7340. changed = true;
  7341. }
  7342. }
  7343. }
  7344. this.activeCues_ = active;
  7345. activeCues.setCues_(this.activeCues_);
  7346. return activeCues;
  7347. },
  7348. // /!\ Keep this setter empty (see the timeupdate handler above)
  7349. set: function set() {}
  7350. }
  7351. });
  7352. if (settings.src) {
  7353. _this.src = settings.src;
  7354. if (!_this.preload_) {
  7355. // Tracks will load on-demand.
  7356. // Act like we're loaded for other purposes.
  7357. _this.loaded_ = true;
  7358. }
  7359. if (_this.preload_ || settings.kind !== 'subtitles' && settings.kind !== 'captions') {
  7360. loadTrack(_this.src, assertThisInitialized(_this));
  7361. }
  7362. } else {
  7363. _this.loaded_ = true;
  7364. }
  7365. return _this;
  7366. }
  7367. var _proto = TextTrack.prototype;
  7368. _proto.startTracking = function startTracking() {
  7369. // More precise cues based on requestVideoFrameCallback with a requestAnimationFram fallback
  7370. this.rvf_ = this.tech_.requestVideoFrameCallback(this.timeupdateHandler); // Also listen to timeupdate in case rVFC/rAF stops (window in background, audio in video el)
  7371. this.tech_.on('timeupdate', this.timeupdateHandler);
  7372. };
  7373. _proto.stopTracking = function stopTracking() {
  7374. if (this.rvf_) {
  7375. this.tech_.cancelVideoFrameCallback(this.rvf_);
  7376. this.rvf_ = undefined;
  7377. }
  7378. this.tech_.off('timeupdate', this.timeupdateHandler);
  7379. }
  7380. /**
  7381. * Add a cue to the internal list of cues.
  7382. *
  7383. * @param {TextTrack~Cue} cue
  7384. * The cue to add to our internal list
  7385. */
  7386. ;
  7387. _proto.addCue = function addCue(originalCue) {
  7388. var cue = originalCue;
  7389. if (window.vttjs && !(originalCue instanceof window.vttjs.VTTCue)) {
  7390. cue = new window.vttjs.VTTCue(originalCue.startTime, originalCue.endTime, originalCue.text);
  7391. for (var prop in originalCue) {
  7392. if (!(prop in cue)) {
  7393. cue[prop] = originalCue[prop];
  7394. }
  7395. } // make sure that `id` is copied over
  7396. cue.id = originalCue.id;
  7397. cue.originalCue_ = originalCue;
  7398. }
  7399. var tracks = this.tech_.textTracks();
  7400. for (var i = 0; i < tracks.length; i++) {
  7401. if (tracks[i] !== this) {
  7402. tracks[i].removeCue(cue);
  7403. }
  7404. }
  7405. this.cues_.push(cue);
  7406. this.cues.setCues_(this.cues_);
  7407. }
  7408. /**
  7409. * Remove a cue from our internal list
  7410. *
  7411. * @param {TextTrack~Cue} removeCue
  7412. * The cue to remove from our internal list
  7413. */
  7414. ;
  7415. _proto.removeCue = function removeCue(_removeCue) {
  7416. var i = this.cues_.length;
  7417. while (i--) {
  7418. var cue = this.cues_[i];
  7419. if (cue === _removeCue || cue.originalCue_ && cue.originalCue_ === _removeCue) {
  7420. this.cues_.splice(i, 1);
  7421. this.cues.setCues_(this.cues_);
  7422. break;
  7423. }
  7424. }
  7425. };
  7426. return TextTrack;
  7427. }(Track);
  7428. /**
  7429. * cuechange - One or more cues in the track have become active or stopped being active.
  7430. */
  7431. TextTrack.prototype.allowedEvents_ = {
  7432. cuechange: 'cuechange'
  7433. };
  7434. /**
  7435. * A representation of a single `AudioTrack`. If it is part of an {@link AudioTrackList}
  7436. * only one `AudioTrack` in the list will be enabled at a time.
  7437. *
  7438. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotrack}
  7439. * @extends Track
  7440. */
  7441. var AudioTrack = /*#__PURE__*/function (_Track) {
  7442. inheritsLoose(AudioTrack, _Track);
  7443. /**
  7444. * Create an instance of this class.
  7445. *
  7446. * @param {Object} [options={}]
  7447. * Object of option names and values
  7448. *
  7449. * @param {AudioTrack~Kind} [options.kind='']
  7450. * A valid audio track kind
  7451. *
  7452. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7453. * A unique id for this AudioTrack.
  7454. *
  7455. * @param {string} [options.label='']
  7456. * The menu label for this track.
  7457. *
  7458. * @param {string} [options.language='']
  7459. * A valid two character language code.
  7460. *
  7461. * @param {boolean} [options.enabled]
  7462. * If this track is the one that is currently playing. If this track is part of
  7463. * an {@link AudioTrackList}, only one {@link AudioTrack} will be enabled.
  7464. */
  7465. function AudioTrack(options) {
  7466. var _this;
  7467. if (options === void 0) {
  7468. options = {};
  7469. }
  7470. var settings = mergeOptions$3(options, {
  7471. kind: AudioTrackKind[options.kind] || ''
  7472. });
  7473. _this = _Track.call(this, settings) || this;
  7474. var enabled = false;
  7475. /**
  7476. * @memberof AudioTrack
  7477. * @member {boolean} enabled
  7478. * If this `AudioTrack` is enabled or not. When setting this will
  7479. * fire {@link AudioTrack#enabledchange} if the state of enabled is changed.
  7480. * @instance
  7481. *
  7482. * @fires VideoTrack#selectedchange
  7483. */
  7484. Object.defineProperty(assertThisInitialized(_this), 'enabled', {
  7485. get: function get() {
  7486. return enabled;
  7487. },
  7488. set: function set(newEnabled) {
  7489. // an invalid or unchanged value
  7490. if (typeof newEnabled !== 'boolean' || newEnabled === enabled) {
  7491. return;
  7492. }
  7493. enabled = newEnabled;
  7494. /**
  7495. * An event that fires when enabled changes on this track. This allows
  7496. * the AudioTrackList that holds this track to act accordingly.
  7497. *
  7498. * > Note: This is not part of the spec! Native tracks will do
  7499. * this internally without an event.
  7500. *
  7501. * @event AudioTrack#enabledchange
  7502. * @type {EventTarget~Event}
  7503. */
  7504. this.trigger('enabledchange');
  7505. }
  7506. }); // if the user sets this track to selected then
  7507. // set selected to that true value otherwise
  7508. // we keep it false
  7509. if (settings.enabled) {
  7510. _this.enabled = settings.enabled;
  7511. }
  7512. _this.loaded_ = true;
  7513. return _this;
  7514. }
  7515. return AudioTrack;
  7516. }(Track);
  7517. /**
  7518. * A representation of a single `VideoTrack`.
  7519. *
  7520. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#videotrack}
  7521. * @extends Track
  7522. */
  7523. var VideoTrack = /*#__PURE__*/function (_Track) {
  7524. inheritsLoose(VideoTrack, _Track);
  7525. /**
  7526. * Create an instance of this class.
  7527. *
  7528. * @param {Object} [options={}]
  7529. * Object of option names and values
  7530. *
  7531. * @param {string} [options.kind='']
  7532. * A valid {@link VideoTrack~Kind}
  7533. *
  7534. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7535. * A unique id for this AudioTrack.
  7536. *
  7537. * @param {string} [options.label='']
  7538. * The menu label for this track.
  7539. *
  7540. * @param {string} [options.language='']
  7541. * A valid two character language code.
  7542. *
  7543. * @param {boolean} [options.selected]
  7544. * If this track is the one that is currently playing.
  7545. */
  7546. function VideoTrack(options) {
  7547. var _this;
  7548. if (options === void 0) {
  7549. options = {};
  7550. }
  7551. var settings = mergeOptions$3(options, {
  7552. kind: VideoTrackKind[options.kind] || ''
  7553. });
  7554. _this = _Track.call(this, settings) || this;
  7555. var selected = false;
  7556. /**
  7557. * @memberof VideoTrack
  7558. * @member {boolean} selected
  7559. * If this `VideoTrack` is selected or not. When setting this will
  7560. * fire {@link VideoTrack#selectedchange} if the state of selected changed.
  7561. * @instance
  7562. *
  7563. * @fires VideoTrack#selectedchange
  7564. */
  7565. Object.defineProperty(assertThisInitialized(_this), 'selected', {
  7566. get: function get() {
  7567. return selected;
  7568. },
  7569. set: function set(newSelected) {
  7570. // an invalid or unchanged value
  7571. if (typeof newSelected !== 'boolean' || newSelected === selected) {
  7572. return;
  7573. }
  7574. selected = newSelected;
  7575. /**
  7576. * An event that fires when selected changes on this track. This allows
  7577. * the VideoTrackList that holds this track to act accordingly.
  7578. *
  7579. * > Note: This is not part of the spec! Native tracks will do
  7580. * this internally without an event.
  7581. *
  7582. * @event VideoTrack#selectedchange
  7583. * @type {EventTarget~Event}
  7584. */
  7585. this.trigger('selectedchange');
  7586. }
  7587. }); // if the user sets this track to selected then
  7588. // set selected to that true value otherwise
  7589. // we keep it false
  7590. if (settings.selected) {
  7591. _this.selected = settings.selected;
  7592. }
  7593. return _this;
  7594. }
  7595. return VideoTrack;
  7596. }(Track);
  7597. /**
  7598. * @memberof HTMLTrackElement
  7599. * @typedef {HTMLTrackElement~ReadyState}
  7600. * @enum {number}
  7601. */
  7602. var NONE = 0;
  7603. var LOADING = 1;
  7604. var LOADED = 2;
  7605. var ERROR = 3;
  7606. /**
  7607. * A single track represented in the DOM.
  7608. *
  7609. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#htmltrackelement}
  7610. * @extends EventTarget
  7611. */
  7612. var HTMLTrackElement = /*#__PURE__*/function (_EventTarget) {
  7613. inheritsLoose(HTMLTrackElement, _EventTarget);
  7614. /**
  7615. * Create an instance of this class.
  7616. *
  7617. * @param {Object} options={}
  7618. * Object of option names and values
  7619. *
  7620. * @param {Tech} options.tech
  7621. * A reference to the tech that owns this HTMLTrackElement.
  7622. *
  7623. * @param {TextTrack~Kind} [options.kind='subtitles']
  7624. * A valid text track kind.
  7625. *
  7626. * @param {TextTrack~Mode} [options.mode='disabled']
  7627. * A valid text track mode.
  7628. *
  7629. * @param {string} [options.id='vjs_track_' + Guid.newGUID()]
  7630. * A unique id for this TextTrack.
  7631. *
  7632. * @param {string} [options.label='']
  7633. * The menu label for this track.
  7634. *
  7635. * @param {string} [options.language='']
  7636. * A valid two character language code.
  7637. *
  7638. * @param {string} [options.srclang='']
  7639. * A valid two character language code. An alternative, but deprioritized
  7640. * version of `options.language`
  7641. *
  7642. * @param {string} [options.src]
  7643. * A url to TextTrack cues.
  7644. *
  7645. * @param {boolean} [options.default]
  7646. * If this track should default to on or off.
  7647. */
  7648. function HTMLTrackElement(options) {
  7649. var _this;
  7650. if (options === void 0) {
  7651. options = {};
  7652. }
  7653. _this = _EventTarget.call(this) || this;
  7654. var readyState;
  7655. var track = new TextTrack(options);
  7656. _this.kind = track.kind;
  7657. _this.src = track.src;
  7658. _this.srclang = track.language;
  7659. _this.label = track.label;
  7660. _this["default"] = track["default"];
  7661. Object.defineProperties(assertThisInitialized(_this), {
  7662. /**
  7663. * @memberof HTMLTrackElement
  7664. * @member {HTMLTrackElement~ReadyState} readyState
  7665. * The current ready state of the track element.
  7666. * @instance
  7667. */
  7668. readyState: {
  7669. get: function get() {
  7670. return readyState;
  7671. }
  7672. },
  7673. /**
  7674. * @memberof HTMLTrackElement
  7675. * @member {TextTrack} track
  7676. * The underlying TextTrack object.
  7677. * @instance
  7678. *
  7679. */
  7680. track: {
  7681. get: function get() {
  7682. return track;
  7683. }
  7684. }
  7685. });
  7686. readyState = NONE;
  7687. /**
  7688. * @listens TextTrack#loadeddata
  7689. * @fires HTMLTrackElement#load
  7690. */
  7691. track.addEventListener('loadeddata', function () {
  7692. readyState = LOADED;
  7693. _this.trigger({
  7694. type: 'load',
  7695. target: assertThisInitialized(_this)
  7696. });
  7697. });
  7698. return _this;
  7699. }
  7700. return HTMLTrackElement;
  7701. }(EventTarget$2);
  7702. HTMLTrackElement.prototype.allowedEvents_ = {
  7703. load: 'load'
  7704. };
  7705. HTMLTrackElement.NONE = NONE;
  7706. HTMLTrackElement.LOADING = LOADING;
  7707. HTMLTrackElement.LOADED = LOADED;
  7708. HTMLTrackElement.ERROR = ERROR;
  7709. /*
  7710. * This file contains all track properties that are used in
  7711. * player.js, tech.js, html5.js and possibly other techs in the future.
  7712. */
  7713. var NORMAL = {
  7714. audio: {
  7715. ListClass: AudioTrackList,
  7716. TrackClass: AudioTrack,
  7717. capitalName: 'Audio'
  7718. },
  7719. video: {
  7720. ListClass: VideoTrackList,
  7721. TrackClass: VideoTrack,
  7722. capitalName: 'Video'
  7723. },
  7724. text: {
  7725. ListClass: TextTrackList,
  7726. TrackClass: TextTrack,
  7727. capitalName: 'Text'
  7728. }
  7729. };
  7730. Object.keys(NORMAL).forEach(function (type) {
  7731. NORMAL[type].getterName = type + "Tracks";
  7732. NORMAL[type].privateName = type + "Tracks_";
  7733. });
  7734. var REMOTE = {
  7735. remoteText: {
  7736. ListClass: TextTrackList,
  7737. TrackClass: TextTrack,
  7738. capitalName: 'RemoteText',
  7739. getterName: 'remoteTextTracks',
  7740. privateName: 'remoteTextTracks_'
  7741. },
  7742. remoteTextEl: {
  7743. ListClass: HtmlTrackElementList,
  7744. TrackClass: HTMLTrackElement,
  7745. capitalName: 'RemoteTextTrackEls',
  7746. getterName: 'remoteTextTrackEls',
  7747. privateName: 'remoteTextTrackEls_'
  7748. }
  7749. };
  7750. var ALL = _extends_1({}, NORMAL, REMOTE);
  7751. REMOTE.names = Object.keys(REMOTE);
  7752. NORMAL.names = Object.keys(NORMAL);
  7753. ALL.names = [].concat(REMOTE.names).concat(NORMAL.names);
  7754. var minDoc = {};
  7755. var topLevel = typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : typeof window !== 'undefined' ? window : {};
  7756. var doccy;
  7757. if (typeof document !== 'undefined') {
  7758. doccy = document;
  7759. } else {
  7760. doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'];
  7761. if (!doccy) {
  7762. doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc;
  7763. }
  7764. }
  7765. var document_1 = doccy;
  7766. /**
  7767. * Copyright 2013 vtt.js Contributors
  7768. *
  7769. * Licensed under the Apache License, Version 2.0 (the "License");
  7770. * you may not use this file except in compliance with the License.
  7771. * You may obtain a copy of the License at
  7772. *
  7773. * http://www.apache.org/licenses/LICENSE-2.0
  7774. *
  7775. * Unless required by applicable law or agreed to in writing, software
  7776. * distributed under the License is distributed on an "AS IS" BASIS,
  7777. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  7778. * See the License for the specific language governing permissions and
  7779. * limitations under the License.
  7780. */
  7781. /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  7782. /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
  7783. var _objCreate = Object.create || function () {
  7784. function F() {}
  7785. return function (o) {
  7786. if (arguments.length !== 1) {
  7787. throw new Error('Object.create shim only accepts one parameter.');
  7788. }
  7789. F.prototype = o;
  7790. return new F();
  7791. };
  7792. }(); // Creates a new ParserError object from an errorData object. The errorData
  7793. // object should have default code and message properties. The default message
  7794. // property can be overriden by passing in a message parameter.
  7795. // See ParsingError.Errors below for acceptable errors.
  7796. function ParsingError(errorData, message) {
  7797. this.name = "ParsingError";
  7798. this.code = errorData.code;
  7799. this.message = message || errorData.message;
  7800. }
  7801. ParsingError.prototype = _objCreate(Error.prototype);
  7802. ParsingError.prototype.constructor = ParsingError; // ParsingError metadata for acceptable ParsingErrors.
  7803. ParsingError.Errors = {
  7804. BadSignature: {
  7805. code: 0,
  7806. message: "Malformed WebVTT signature."
  7807. },
  7808. BadTimeStamp: {
  7809. code: 1,
  7810. message: "Malformed time stamp."
  7811. }
  7812. }; // Try to parse input as a time stamp.
  7813. function parseTimeStamp(input) {
  7814. function computeSeconds(h, m, s, f) {
  7815. return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;
  7816. }
  7817. var m = input.match(/^(\d+):(\d{1,2})(:\d{1,2})?\.(\d{3})/);
  7818. if (!m) {
  7819. return null;
  7820. }
  7821. if (m[3]) {
  7822. // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]
  7823. return computeSeconds(m[1], m[2], m[3].replace(":", ""), m[4]);
  7824. } else if (m[1] > 59) {
  7825. // Timestamp takes the form of [hours]:[minutes].[milliseconds]
  7826. // First position is hours as it's over 59.
  7827. return computeSeconds(m[1], m[2], 0, m[4]);
  7828. } else {
  7829. // Timestamp takes the form of [minutes]:[seconds].[milliseconds]
  7830. return computeSeconds(0, m[1], m[2], m[4]);
  7831. }
  7832. } // A settings object holds key/value pairs and will ignore anything but the first
  7833. // assignment to a specific key.
  7834. function Settings() {
  7835. this.values = _objCreate(null);
  7836. }
  7837. Settings.prototype = {
  7838. // Only accept the first assignment to any key.
  7839. set: function set(k, v) {
  7840. if (!this.get(k) && v !== "") {
  7841. this.values[k] = v;
  7842. }
  7843. },
  7844. // Return the value for a key, or a default value.
  7845. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
  7846. // a number of possible default values as properties where 'defaultKey' is
  7847. // the key of the property that will be chosen; otherwise it's assumed to be
  7848. // a single value.
  7849. get: function get(k, dflt, defaultKey) {
  7850. if (defaultKey) {
  7851. return this.has(k) ? this.values[k] : dflt[defaultKey];
  7852. }
  7853. return this.has(k) ? this.values[k] : dflt;
  7854. },
  7855. // Check whether we have a value for a key.
  7856. has: function has(k) {
  7857. return k in this.values;
  7858. },
  7859. // Accept a setting if its one of the given alternatives.
  7860. alt: function alt(k, v, a) {
  7861. for (var n = 0; n < a.length; ++n) {
  7862. if (v === a[n]) {
  7863. this.set(k, v);
  7864. break;
  7865. }
  7866. }
  7867. },
  7868. // Accept a setting if its a valid (signed) integer.
  7869. integer: function integer(k, v) {
  7870. if (/^-?\d+$/.test(v)) {
  7871. // integer
  7872. this.set(k, parseInt(v, 10));
  7873. }
  7874. },
  7875. // Accept a setting if its a valid percentage.
  7876. percent: function percent(k, v) {
  7877. if (v.match(/^([\d]{1,3})(\.[\d]*)?%$/)) {
  7878. v = parseFloat(v);
  7879. if (v >= 0 && v <= 100) {
  7880. this.set(k, v);
  7881. return true;
  7882. }
  7883. }
  7884. return false;
  7885. }
  7886. }; // Helper function to parse input into groups separated by 'groupDelim', and
  7887. // interprete each group as a key/value pair separated by 'keyValueDelim'.
  7888. function parseOptions(input, callback, keyValueDelim, groupDelim) {
  7889. var groups = groupDelim ? input.split(groupDelim) : [input];
  7890. for (var i in groups) {
  7891. if (typeof groups[i] !== "string") {
  7892. continue;
  7893. }
  7894. var kv = groups[i].split(keyValueDelim);
  7895. if (kv.length !== 2) {
  7896. continue;
  7897. }
  7898. var k = kv[0].trim();
  7899. var v = kv[1].trim();
  7900. callback(k, v);
  7901. }
  7902. }
  7903. function parseCue(input, cue, regionList) {
  7904. // Remember the original input if we need to throw an error.
  7905. var oInput = input; // 4.1 WebVTT timestamp
  7906. function consumeTimeStamp() {
  7907. var ts = parseTimeStamp(input);
  7908. if (ts === null) {
  7909. throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed timestamp: " + oInput);
  7910. } // Remove time stamp from input.
  7911. input = input.replace(/^[^\sa-zA-Z-]+/, "");
  7912. return ts;
  7913. } // 4.4.2 WebVTT cue settings
  7914. function consumeCueSettings(input, cue) {
  7915. var settings = new Settings();
  7916. parseOptions(input, function (k, v) {
  7917. switch (k) {
  7918. case "region":
  7919. // Find the last region we parsed with the same region id.
  7920. for (var i = regionList.length - 1; i >= 0; i--) {
  7921. if (regionList[i].id === v) {
  7922. settings.set(k, regionList[i].region);
  7923. break;
  7924. }
  7925. }
  7926. break;
  7927. case "vertical":
  7928. settings.alt(k, v, ["rl", "lr"]);
  7929. break;
  7930. case "line":
  7931. var vals = v.split(","),
  7932. vals0 = vals[0];
  7933. settings.integer(k, vals0);
  7934. settings.percent(k, vals0) ? settings.set("snapToLines", false) : null;
  7935. settings.alt(k, vals0, ["auto"]);
  7936. if (vals.length === 2) {
  7937. settings.alt("lineAlign", vals[1], ["start", "center", "end"]);
  7938. }
  7939. break;
  7940. case "position":
  7941. vals = v.split(",");
  7942. settings.percent(k, vals[0]);
  7943. if (vals.length === 2) {
  7944. settings.alt("positionAlign", vals[1], ["start", "center", "end"]);
  7945. }
  7946. break;
  7947. case "size":
  7948. settings.percent(k, v);
  7949. break;
  7950. case "align":
  7951. settings.alt(k, v, ["start", "center", "end", "left", "right"]);
  7952. break;
  7953. }
  7954. }, /:/, /\s/); // Apply default values for any missing fields.
  7955. cue.region = settings.get("region", null);
  7956. cue.vertical = settings.get("vertical", "");
  7957. try {
  7958. cue.line = settings.get("line", "auto");
  7959. } catch (e) {}
  7960. cue.lineAlign = settings.get("lineAlign", "start");
  7961. cue.snapToLines = settings.get("snapToLines", true);
  7962. cue.size = settings.get("size", 100); // Safari still uses the old middle value and won't accept center
  7963. try {
  7964. cue.align = settings.get("align", "center");
  7965. } catch (e) {
  7966. cue.align = settings.get("align", "middle");
  7967. }
  7968. try {
  7969. cue.position = settings.get("position", "auto");
  7970. } catch (e) {
  7971. cue.position = settings.get("position", {
  7972. start: 0,
  7973. left: 0,
  7974. center: 50,
  7975. middle: 50,
  7976. end: 100,
  7977. right: 100
  7978. }, cue.align);
  7979. }
  7980. cue.positionAlign = settings.get("positionAlign", {
  7981. start: "start",
  7982. left: "start",
  7983. center: "center",
  7984. middle: "center",
  7985. end: "end",
  7986. right: "end"
  7987. }, cue.align);
  7988. }
  7989. function skipWhitespace() {
  7990. input = input.replace(/^\s+/, "");
  7991. } // 4.1 WebVTT cue timings.
  7992. skipWhitespace();
  7993. cue.startTime = consumeTimeStamp(); // (1) collect cue start time
  7994. skipWhitespace();
  7995. if (input.substr(0, 3) !== "-->") {
  7996. // (3) next characters must match "-->"
  7997. throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed time stamp (time stamps must be separated by '-->'): " + oInput);
  7998. }
  7999. input = input.substr(3);
  8000. skipWhitespace();
  8001. cue.endTime = consumeTimeStamp(); // (5) collect cue end time
  8002. // 4.1 WebVTT cue settings list.
  8003. skipWhitespace();
  8004. consumeCueSettings(input, cue);
  8005. } // When evaluating this file as part of a Webpack bundle for server
  8006. // side rendering, `document` is an empty object.
  8007. var TEXTAREA_ELEMENT = document_1.createElement && document_1.createElement("textarea");
  8008. var TAG_NAME = {
  8009. c: "span",
  8010. i: "i",
  8011. b: "b",
  8012. u: "u",
  8013. ruby: "ruby",
  8014. rt: "rt",
  8015. v: "span",
  8016. lang: "span"
  8017. }; // 5.1 default text color
  8018. // 5.2 default text background color is equivalent to text color with bg_ prefix
  8019. var DEFAULT_COLOR_CLASS = {
  8020. white: 'rgba(255,255,255,1)',
  8021. lime: 'rgba(0,255,0,1)',
  8022. cyan: 'rgba(0,255,255,1)',
  8023. red: 'rgba(255,0,0,1)',
  8024. yellow: 'rgba(255,255,0,1)',
  8025. magenta: 'rgba(255,0,255,1)',
  8026. blue: 'rgba(0,0,255,1)',
  8027. black: 'rgba(0,0,0,1)'
  8028. };
  8029. var TAG_ANNOTATION = {
  8030. v: "title",
  8031. lang: "lang"
  8032. };
  8033. var NEEDS_PARENT = {
  8034. rt: "ruby"
  8035. }; // Parse content into a document fragment.
  8036. function parseContent(window, input) {
  8037. function nextToken() {
  8038. // Check for end-of-string.
  8039. if (!input) {
  8040. return null;
  8041. } // Consume 'n' characters from the input.
  8042. function consume(result) {
  8043. input = input.substr(result.length);
  8044. return result;
  8045. }
  8046. var m = input.match(/^([^<]*)(<[^>]*>?)?/); // If there is some text before the next tag, return it, otherwise return
  8047. // the tag.
  8048. return consume(m[1] ? m[1] : m[2]);
  8049. }
  8050. function unescape(s) {
  8051. TEXTAREA_ELEMENT.innerHTML = s;
  8052. s = TEXTAREA_ELEMENT.textContent;
  8053. TEXTAREA_ELEMENT.textContent = "";
  8054. return s;
  8055. }
  8056. function shouldAdd(current, element) {
  8057. return !NEEDS_PARENT[element.localName] || NEEDS_PARENT[element.localName] === current.localName;
  8058. } // Create an element for this tag.
  8059. function createElement(type, annotation) {
  8060. var tagName = TAG_NAME[type];
  8061. if (!tagName) {
  8062. return null;
  8063. }
  8064. var element = window.document.createElement(tagName);
  8065. var name = TAG_ANNOTATION[type];
  8066. if (name && annotation) {
  8067. element[name] = annotation.trim();
  8068. }
  8069. return element;
  8070. }
  8071. var rootDiv = window.document.createElement("div"),
  8072. current = rootDiv,
  8073. t,
  8074. tagStack = [];
  8075. while ((t = nextToken()) !== null) {
  8076. if (t[0] === '<') {
  8077. if (t[1] === "/") {
  8078. // If the closing tag matches, move back up to the parent node.
  8079. if (tagStack.length && tagStack[tagStack.length - 1] === t.substr(2).replace(">", "")) {
  8080. tagStack.pop();
  8081. current = current.parentNode;
  8082. } // Otherwise just ignore the end tag.
  8083. continue;
  8084. }
  8085. var ts = parseTimeStamp(t.substr(1, t.length - 2));
  8086. var node;
  8087. if (ts) {
  8088. // Timestamps are lead nodes as well.
  8089. node = window.document.createProcessingInstruction("timestamp", ts);
  8090. current.appendChild(node);
  8091. continue;
  8092. }
  8093. var m = t.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/); // If we can't parse the tag, skip to the next tag.
  8094. if (!m) {
  8095. continue;
  8096. } // Try to construct an element, and ignore the tag if we couldn't.
  8097. node = createElement(m[1], m[3]);
  8098. if (!node) {
  8099. continue;
  8100. } // Determine if the tag should be added based on the context of where it
  8101. // is placed in the cuetext.
  8102. if (!shouldAdd(current, node)) {
  8103. continue;
  8104. } // Set the class list (as a list of classes, separated by space).
  8105. if (m[2]) {
  8106. var classes = m[2].split('.');
  8107. classes.forEach(function (cl) {
  8108. var bgColor = /^bg_/.test(cl); // slice out `bg_` if it's a background color
  8109. var colorName = bgColor ? cl.slice(3) : cl;
  8110. if (DEFAULT_COLOR_CLASS.hasOwnProperty(colorName)) {
  8111. var propName = bgColor ? 'background-color' : 'color';
  8112. var propValue = DEFAULT_COLOR_CLASS[colorName];
  8113. node.style[propName] = propValue;
  8114. }
  8115. });
  8116. node.className = classes.join(' ');
  8117. } // Append the node to the current node, and enter the scope of the new
  8118. // node.
  8119. tagStack.push(m[1]);
  8120. current.appendChild(node);
  8121. current = node;
  8122. continue;
  8123. } // Text nodes are leaf nodes.
  8124. current.appendChild(window.document.createTextNode(unescape(t)));
  8125. }
  8126. return rootDiv;
  8127. } // This is a list of all the Unicode characters that have a strong
  8128. // right-to-left category. What this means is that these characters are
  8129. // written right-to-left for sure. It was generated by pulling all the strong
  8130. // right-to-left characters out of the Unicode data table. That table can
  8131. // found at: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt
  8132. var strongRTLRanges = [[0x5be, 0x5be], [0x5c0, 0x5c0], [0x5c3, 0x5c3], [0x5c6, 0x5c6], [0x5d0, 0x5ea], [0x5f0, 0x5f4], [0x608, 0x608], [0x60b, 0x60b], [0x60d, 0x60d], [0x61b, 0x61b], [0x61e, 0x64a], [0x66d, 0x66f], [0x671, 0x6d5], [0x6e5, 0x6e6], [0x6ee, 0x6ef], [0x6fa, 0x70d], [0x70f, 0x710], [0x712, 0x72f], [0x74d, 0x7a5], [0x7b1, 0x7b1], [0x7c0, 0x7ea], [0x7f4, 0x7f5], [0x7fa, 0x7fa], [0x800, 0x815], [0x81a, 0x81a], [0x824, 0x824], [0x828, 0x828], [0x830, 0x83e], [0x840, 0x858], [0x85e, 0x85e], [0x8a0, 0x8a0], [0x8a2, 0x8ac], [0x200f, 0x200f], [0xfb1d, 0xfb1d], [0xfb1f, 0xfb28], [0xfb2a, 0xfb36], [0xfb38, 0xfb3c], [0xfb3e, 0xfb3e], [0xfb40, 0xfb41], [0xfb43, 0xfb44], [0xfb46, 0xfbc1], [0xfbd3, 0xfd3d], [0xfd50, 0xfd8f], [0xfd92, 0xfdc7], [0xfdf0, 0xfdfc], [0xfe70, 0xfe74], [0xfe76, 0xfefc], [0x10800, 0x10805], [0x10808, 0x10808], [0x1080a, 0x10835], [0x10837, 0x10838], [0x1083c, 0x1083c], [0x1083f, 0x10855], [0x10857, 0x1085f], [0x10900, 0x1091b], [0x10920, 0x10939], [0x1093f, 0x1093f], [0x10980, 0x109b7], [0x109be, 0x109bf], [0x10a00, 0x10a00], [0x10a10, 0x10a13], [0x10a15, 0x10a17], [0x10a19, 0x10a33], [0x10a40, 0x10a47], [0x10a50, 0x10a58], [0x10a60, 0x10a7f], [0x10b00, 0x10b35], [0x10b40, 0x10b55], [0x10b58, 0x10b72], [0x10b78, 0x10b7f], [0x10c00, 0x10c48], [0x1ee00, 0x1ee03], [0x1ee05, 0x1ee1f], [0x1ee21, 0x1ee22], [0x1ee24, 0x1ee24], [0x1ee27, 0x1ee27], [0x1ee29, 0x1ee32], [0x1ee34, 0x1ee37], [0x1ee39, 0x1ee39], [0x1ee3b, 0x1ee3b], [0x1ee42, 0x1ee42], [0x1ee47, 0x1ee47], [0x1ee49, 0x1ee49], [0x1ee4b, 0x1ee4b], [0x1ee4d, 0x1ee4f], [0x1ee51, 0x1ee52], [0x1ee54, 0x1ee54], [0x1ee57, 0x1ee57], [0x1ee59, 0x1ee59], [0x1ee5b, 0x1ee5b], [0x1ee5d, 0x1ee5d], [0x1ee5f, 0x1ee5f], [0x1ee61, 0x1ee62], [0x1ee64, 0x1ee64], [0x1ee67, 0x1ee6a], [0x1ee6c, 0x1ee72], [0x1ee74, 0x1ee77], [0x1ee79, 0x1ee7c], [0x1ee7e, 0x1ee7e], [0x1ee80, 0x1ee89], [0x1ee8b, 0x1ee9b], [0x1eea1, 0x1eea3], [0x1eea5, 0x1eea9], [0x1eeab, 0x1eebb], [0x10fffd, 0x10fffd]];
  8133. function isStrongRTLChar(charCode) {
  8134. for (var i = 0; i < strongRTLRanges.length; i++) {
  8135. var currentRange = strongRTLRanges[i];
  8136. if (charCode >= currentRange[0] && charCode <= currentRange[1]) {
  8137. return true;
  8138. }
  8139. }
  8140. return false;
  8141. }
  8142. function determineBidi(cueDiv) {
  8143. var nodeStack = [],
  8144. text = "",
  8145. charCode;
  8146. if (!cueDiv || !cueDiv.childNodes) {
  8147. return "ltr";
  8148. }
  8149. function pushNodes(nodeStack, node) {
  8150. for (var i = node.childNodes.length - 1; i >= 0; i--) {
  8151. nodeStack.push(node.childNodes[i]);
  8152. }
  8153. }
  8154. function nextTextNode(nodeStack) {
  8155. if (!nodeStack || !nodeStack.length) {
  8156. return null;
  8157. }
  8158. var node = nodeStack.pop(),
  8159. text = node.textContent || node.innerText;
  8160. if (text) {
  8161. // TODO: This should match all unicode type B characters (paragraph
  8162. // separator characters). See issue #115.
  8163. var m = text.match(/^.*(\n|\r)/);
  8164. if (m) {
  8165. nodeStack.length = 0;
  8166. return m[0];
  8167. }
  8168. return text;
  8169. }
  8170. if (node.tagName === "ruby") {
  8171. return nextTextNode(nodeStack);
  8172. }
  8173. if (node.childNodes) {
  8174. pushNodes(nodeStack, node);
  8175. return nextTextNode(nodeStack);
  8176. }
  8177. }
  8178. pushNodes(nodeStack, cueDiv);
  8179. while (text = nextTextNode(nodeStack)) {
  8180. for (var i = 0; i < text.length; i++) {
  8181. charCode = text.charCodeAt(i);
  8182. if (isStrongRTLChar(charCode)) {
  8183. return "rtl";
  8184. }
  8185. }
  8186. }
  8187. return "ltr";
  8188. }
  8189. function computeLinePos(cue) {
  8190. if (typeof cue.line === "number" && (cue.snapToLines || cue.line >= 0 && cue.line <= 100)) {
  8191. return cue.line;
  8192. }
  8193. if (!cue.track || !cue.track.textTrackList || !cue.track.textTrackList.mediaElement) {
  8194. return -1;
  8195. }
  8196. var track = cue.track,
  8197. trackList = track.textTrackList,
  8198. count = 0;
  8199. for (var i = 0; i < trackList.length && trackList[i] !== track; i++) {
  8200. if (trackList[i].mode === "showing") {
  8201. count++;
  8202. }
  8203. }
  8204. return ++count * -1;
  8205. }
  8206. function StyleBox() {} // Apply styles to a div. If there is no div passed then it defaults to the
  8207. // div on 'this'.
  8208. StyleBox.prototype.applyStyles = function (styles, div) {
  8209. div = div || this.div;
  8210. for (var prop in styles) {
  8211. if (styles.hasOwnProperty(prop)) {
  8212. div.style[prop] = styles[prop];
  8213. }
  8214. }
  8215. };
  8216. StyleBox.prototype.formatStyle = function (val, unit) {
  8217. return val === 0 ? 0 : val + unit;
  8218. }; // Constructs the computed display state of the cue (a div). Places the div
  8219. // into the overlay which should be a block level element (usually a div).
  8220. function CueStyleBox(window, cue, styleOptions) {
  8221. StyleBox.call(this);
  8222. this.cue = cue; // Parse our cue's text into a DOM tree rooted at 'cueDiv'. This div will
  8223. // have inline positioning and will function as the cue background box.
  8224. this.cueDiv = parseContent(window, cue.text);
  8225. var styles = {
  8226. color: "rgba(255, 255, 255, 1)",
  8227. backgroundColor: "rgba(0, 0, 0, 0.8)",
  8228. position: "relative",
  8229. left: 0,
  8230. right: 0,
  8231. top: 0,
  8232. bottom: 0,
  8233. display: "inline",
  8234. writingMode: cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl",
  8235. unicodeBidi: "plaintext"
  8236. };
  8237. this.applyStyles(styles, this.cueDiv); // Create an absolutely positioned div that will be used to position the cue
  8238. // div. Note, all WebVTT cue-setting alignments are equivalent to the CSS
  8239. // mirrors of them except middle instead of center on Safari.
  8240. this.div = window.document.createElement("div");
  8241. styles = {
  8242. direction: determineBidi(this.cueDiv),
  8243. writingMode: cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl",
  8244. unicodeBidi: "plaintext",
  8245. textAlign: cue.align === "middle" ? "center" : cue.align,
  8246. font: styleOptions.font,
  8247. whiteSpace: "pre-line",
  8248. position: "absolute"
  8249. };
  8250. this.applyStyles(styles);
  8251. this.div.appendChild(this.cueDiv); // Calculate the distance from the reference edge of the viewport to the text
  8252. // position of the cue box. The reference edge will be resolved later when
  8253. // the box orientation styles are applied.
  8254. var textPos = 0;
  8255. switch (cue.positionAlign) {
  8256. case "start":
  8257. textPos = cue.position;
  8258. break;
  8259. case "center":
  8260. textPos = cue.position - cue.size / 2;
  8261. break;
  8262. case "end":
  8263. textPos = cue.position - cue.size;
  8264. break;
  8265. } // Horizontal box orientation; textPos is the distance from the left edge of the
  8266. // area to the left edge of the box and cue.size is the distance extending to
  8267. // the right from there.
  8268. if (cue.vertical === "") {
  8269. this.applyStyles({
  8270. left: this.formatStyle(textPos, "%"),
  8271. width: this.formatStyle(cue.size, "%")
  8272. }); // Vertical box orientation; textPos is the distance from the top edge of the
  8273. // area to the top edge of the box and cue.size is the height extending
  8274. // downwards from there.
  8275. } else {
  8276. this.applyStyles({
  8277. top: this.formatStyle(textPos, "%"),
  8278. height: this.formatStyle(cue.size, "%")
  8279. });
  8280. }
  8281. this.move = function (box) {
  8282. this.applyStyles({
  8283. top: this.formatStyle(box.top, "px"),
  8284. bottom: this.formatStyle(box.bottom, "px"),
  8285. left: this.formatStyle(box.left, "px"),
  8286. right: this.formatStyle(box.right, "px"),
  8287. height: this.formatStyle(box.height, "px"),
  8288. width: this.formatStyle(box.width, "px")
  8289. });
  8290. };
  8291. }
  8292. CueStyleBox.prototype = _objCreate(StyleBox.prototype);
  8293. CueStyleBox.prototype.constructor = CueStyleBox; // Represents the co-ordinates of an Element in a way that we can easily
  8294. // compute things with such as if it overlaps or intersects with another Element.
  8295. // Can initialize it with either a StyleBox or another BoxPosition.
  8296. function BoxPosition(obj) {
  8297. // Either a BoxPosition was passed in and we need to copy it, or a StyleBox
  8298. // was passed in and we need to copy the results of 'getBoundingClientRect'
  8299. // as the object returned is readonly. All co-ordinate values are in reference
  8300. // to the viewport origin (top left).
  8301. var lh, height, width, top;
  8302. if (obj.div) {
  8303. height = obj.div.offsetHeight;
  8304. width = obj.div.offsetWidth;
  8305. top = obj.div.offsetTop;
  8306. var rects = (rects = obj.div.childNodes) && (rects = rects[0]) && rects.getClientRects && rects.getClientRects();
  8307. obj = obj.div.getBoundingClientRect(); // In certain cases the outter div will be slightly larger then the sum of
  8308. // the inner div's lines. This could be due to bold text, etc, on some platforms.
  8309. // In this case we should get the average line height and use that. This will
  8310. // result in the desired behaviour.
  8311. lh = rects ? Math.max(rects[0] && rects[0].height || 0, obj.height / rects.length) : 0;
  8312. }
  8313. this.left = obj.left;
  8314. this.right = obj.right;
  8315. this.top = obj.top || top;
  8316. this.height = obj.height || height;
  8317. this.bottom = obj.bottom || top + (obj.height || height);
  8318. this.width = obj.width || width;
  8319. this.lineHeight = lh !== undefined ? lh : obj.lineHeight;
  8320. } // Move the box along a particular axis. Optionally pass in an amount to move
  8321. // the box. If no amount is passed then the default is the line height of the
  8322. // box.
  8323. BoxPosition.prototype.move = function (axis, toMove) {
  8324. toMove = toMove !== undefined ? toMove : this.lineHeight;
  8325. switch (axis) {
  8326. case "+x":
  8327. this.left += toMove;
  8328. this.right += toMove;
  8329. break;
  8330. case "-x":
  8331. this.left -= toMove;
  8332. this.right -= toMove;
  8333. break;
  8334. case "+y":
  8335. this.top += toMove;
  8336. this.bottom += toMove;
  8337. break;
  8338. case "-y":
  8339. this.top -= toMove;
  8340. this.bottom -= toMove;
  8341. break;
  8342. }
  8343. }; // Check if this box overlaps another box, b2.
  8344. BoxPosition.prototype.overlaps = function (b2) {
  8345. return this.left < b2.right && this.right > b2.left && this.top < b2.bottom && this.bottom > b2.top;
  8346. }; // Check if this box overlaps any other boxes in boxes.
  8347. BoxPosition.prototype.overlapsAny = function (boxes) {
  8348. for (var i = 0; i < boxes.length; i++) {
  8349. if (this.overlaps(boxes[i])) {
  8350. return true;
  8351. }
  8352. }
  8353. return false;
  8354. }; // Check if this box is within another box.
  8355. BoxPosition.prototype.within = function (container) {
  8356. return this.top >= container.top && this.bottom <= container.bottom && this.left >= container.left && this.right <= container.right;
  8357. }; // Check if this box is entirely within the container or it is overlapping
  8358. // on the edge opposite of the axis direction passed. For example, if "+x" is
  8359. // passed and the box is overlapping on the left edge of the container, then
  8360. // return true.
  8361. BoxPosition.prototype.overlapsOppositeAxis = function (container, axis) {
  8362. switch (axis) {
  8363. case "+x":
  8364. return this.left < container.left;
  8365. case "-x":
  8366. return this.right > container.right;
  8367. case "+y":
  8368. return this.top < container.top;
  8369. case "-y":
  8370. return this.bottom > container.bottom;
  8371. }
  8372. }; // Find the percentage of the area that this box is overlapping with another
  8373. // box.
  8374. BoxPosition.prototype.intersectPercentage = function (b2) {
  8375. var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)),
  8376. y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)),
  8377. intersectArea = x * y;
  8378. return intersectArea / (this.height * this.width);
  8379. }; // Convert the positions from this box to CSS compatible positions using
  8380. // the reference container's positions. This has to be done because this
  8381. // box's positions are in reference to the viewport origin, whereas, CSS
  8382. // values are in referecne to their respective edges.
  8383. BoxPosition.prototype.toCSSCompatValues = function (reference) {
  8384. return {
  8385. top: this.top - reference.top,
  8386. bottom: reference.bottom - this.bottom,
  8387. left: this.left - reference.left,
  8388. right: reference.right - this.right,
  8389. height: this.height,
  8390. width: this.width
  8391. };
  8392. }; // Get an object that represents the box's position without anything extra.
  8393. // Can pass a StyleBox, HTMLElement, or another BoxPositon.
  8394. BoxPosition.getSimpleBoxPosition = function (obj) {
  8395. var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0;
  8396. var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0;
  8397. var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0;
  8398. obj = obj.div ? obj.div.getBoundingClientRect() : obj.tagName ? obj.getBoundingClientRect() : obj;
  8399. var ret = {
  8400. left: obj.left,
  8401. right: obj.right,
  8402. top: obj.top || top,
  8403. height: obj.height || height,
  8404. bottom: obj.bottom || top + (obj.height || height),
  8405. width: obj.width || width
  8406. };
  8407. return ret;
  8408. }; // Move a StyleBox to its specified, or next best, position. The containerBox
  8409. // is the box that contains the StyleBox, such as a div. boxPositions are
  8410. // a list of other boxes that the styleBox can't overlap with.
  8411. function moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) {
  8412. // Find the best position for a cue box, b, on the video. The axis parameter
  8413. // is a list of axis, the order of which, it will move the box along. For example:
  8414. // Passing ["+x", "-x"] will move the box first along the x axis in the positive
  8415. // direction. If it doesn't find a good position for it there it will then move
  8416. // it along the x axis in the negative direction.
  8417. function findBestPosition(b, axis) {
  8418. var bestPosition,
  8419. specifiedPosition = new BoxPosition(b),
  8420. percentage = 1; // Highest possible so the first thing we get is better.
  8421. for (var i = 0; i < axis.length; i++) {
  8422. while (b.overlapsOppositeAxis(containerBox, axis[i]) || b.within(containerBox) && b.overlapsAny(boxPositions)) {
  8423. b.move(axis[i]);
  8424. } // We found a spot where we aren't overlapping anything. This is our
  8425. // best position.
  8426. if (b.within(containerBox)) {
  8427. return b;
  8428. }
  8429. var p = b.intersectPercentage(containerBox); // If we're outside the container box less then we were on our last try
  8430. // then remember this position as the best position.
  8431. if (percentage > p) {
  8432. bestPosition = new BoxPosition(b);
  8433. percentage = p;
  8434. } // Reset the box position to the specified position.
  8435. b = new BoxPosition(specifiedPosition);
  8436. }
  8437. return bestPosition || specifiedPosition;
  8438. }
  8439. var boxPosition = new BoxPosition(styleBox),
  8440. cue = styleBox.cue,
  8441. linePos = computeLinePos(cue),
  8442. axis = []; // If we have a line number to align the cue to.
  8443. if (cue.snapToLines) {
  8444. var size;
  8445. switch (cue.vertical) {
  8446. case "":
  8447. axis = ["+y", "-y"];
  8448. size = "height";
  8449. break;
  8450. case "rl":
  8451. axis = ["+x", "-x"];
  8452. size = "width";
  8453. break;
  8454. case "lr":
  8455. axis = ["-x", "+x"];
  8456. size = "width";
  8457. break;
  8458. }
  8459. var step = boxPosition.lineHeight,
  8460. position = step * Math.round(linePos),
  8461. maxPosition = containerBox[size] + step,
  8462. initialAxis = axis[0]; // If the specified intial position is greater then the max position then
  8463. // clamp the box to the amount of steps it would take for the box to
  8464. // reach the max position.
  8465. if (Math.abs(position) > maxPosition) {
  8466. position = position < 0 ? -1 : 1;
  8467. position *= Math.ceil(maxPosition / step) * step;
  8468. } // If computed line position returns negative then line numbers are
  8469. // relative to the bottom of the video instead of the top. Therefore, we
  8470. // need to increase our initial position by the length or width of the
  8471. // video, depending on the writing direction, and reverse our axis directions.
  8472. if (linePos < 0) {
  8473. position += cue.vertical === "" ? containerBox.height : containerBox.width;
  8474. axis = axis.reverse();
  8475. } // Move the box to the specified position. This may not be its best
  8476. // position.
  8477. boxPosition.move(initialAxis, position);
  8478. } else {
  8479. // If we have a percentage line value for the cue.
  8480. var calculatedPercentage = boxPosition.lineHeight / containerBox.height * 100;
  8481. switch (cue.lineAlign) {
  8482. case "center":
  8483. linePos -= calculatedPercentage / 2;
  8484. break;
  8485. case "end":
  8486. linePos -= calculatedPercentage;
  8487. break;
  8488. } // Apply initial line position to the cue box.
  8489. switch (cue.vertical) {
  8490. case "":
  8491. styleBox.applyStyles({
  8492. top: styleBox.formatStyle(linePos, "%")
  8493. });
  8494. break;
  8495. case "rl":
  8496. styleBox.applyStyles({
  8497. left: styleBox.formatStyle(linePos, "%")
  8498. });
  8499. break;
  8500. case "lr":
  8501. styleBox.applyStyles({
  8502. right: styleBox.formatStyle(linePos, "%")
  8503. });
  8504. break;
  8505. }
  8506. axis = ["+y", "-x", "+x", "-y"]; // Get the box position again after we've applied the specified positioning
  8507. // to it.
  8508. boxPosition = new BoxPosition(styleBox);
  8509. }
  8510. var bestPosition = findBestPosition(boxPosition, axis);
  8511. styleBox.move(bestPosition.toCSSCompatValues(containerBox));
  8512. }
  8513. function WebVTT$1() {// Nothing
  8514. } // Helper to allow strings to be decoded instead of the default binary utf8 data.
  8515. WebVTT$1.StringDecoder = function () {
  8516. return {
  8517. decode: function decode(data) {
  8518. if (!data) {
  8519. return "";
  8520. }
  8521. if (typeof data !== "string") {
  8522. throw new Error("Error - expected string data.");
  8523. }
  8524. return decodeURIComponent(encodeURIComponent(data));
  8525. }
  8526. };
  8527. };
  8528. WebVTT$1.convertCueToDOMTree = function (window, cuetext) {
  8529. if (!window || !cuetext) {
  8530. return null;
  8531. }
  8532. return parseContent(window, cuetext);
  8533. };
  8534. var FONT_SIZE_PERCENT = 0.05;
  8535. var FONT_STYLE = "sans-serif";
  8536. var CUE_BACKGROUND_PADDING = "1.5%"; // Runs the processing model over the cues and regions passed to it.
  8537. // @param overlay A block level element (usually a div) that the computed cues
  8538. // and regions will be placed into.
  8539. WebVTT$1.processCues = function (window, cues, overlay) {
  8540. if (!window || !cues || !overlay) {
  8541. return null;
  8542. } // Remove all previous children.
  8543. while (overlay.firstChild) {
  8544. overlay.removeChild(overlay.firstChild);
  8545. }
  8546. var paddedOverlay = window.document.createElement("div");
  8547. paddedOverlay.style.position = "absolute";
  8548. paddedOverlay.style.left = "0";
  8549. paddedOverlay.style.right = "0";
  8550. paddedOverlay.style.top = "0";
  8551. paddedOverlay.style.bottom = "0";
  8552. paddedOverlay.style.margin = CUE_BACKGROUND_PADDING;
  8553. overlay.appendChild(paddedOverlay); // Determine if we need to compute the display states of the cues. This could
  8554. // be the case if a cue's state has been changed since the last computation or
  8555. // if it has not been computed yet.
  8556. function shouldCompute(cues) {
  8557. for (var i = 0; i < cues.length; i++) {
  8558. if (cues[i].hasBeenReset || !cues[i].displayState) {
  8559. return true;
  8560. }
  8561. }
  8562. return false;
  8563. } // We don't need to recompute the cues' display states. Just reuse them.
  8564. if (!shouldCompute(cues)) {
  8565. for (var i = 0; i < cues.length; i++) {
  8566. paddedOverlay.appendChild(cues[i].displayState);
  8567. }
  8568. return;
  8569. }
  8570. var boxPositions = [],
  8571. containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay),
  8572. fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100;
  8573. var styleOptions = {
  8574. font: fontSize + "px " + FONT_STYLE
  8575. };
  8576. (function () {
  8577. var styleBox, cue;
  8578. for (var i = 0; i < cues.length; i++) {
  8579. cue = cues[i]; // Compute the intial position and styles of the cue div.
  8580. styleBox = new CueStyleBox(window, cue, styleOptions);
  8581. paddedOverlay.appendChild(styleBox.div); // Move the cue div to it's correct line position.
  8582. moveBoxToLinePosition(window, styleBox, containerBox, boxPositions); // Remember the computed div so that we don't have to recompute it later
  8583. // if we don't have too.
  8584. cue.displayState = styleBox.div;
  8585. boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox));
  8586. }
  8587. })();
  8588. };
  8589. WebVTT$1.Parser = function (window, vttjs, decoder) {
  8590. if (!decoder) {
  8591. decoder = vttjs;
  8592. vttjs = {};
  8593. }
  8594. if (!vttjs) {
  8595. vttjs = {};
  8596. }
  8597. this.window = window;
  8598. this.vttjs = vttjs;
  8599. this.state = "INITIAL";
  8600. this.buffer = "";
  8601. this.decoder = decoder || new TextDecoder("utf8");
  8602. this.regionList = [];
  8603. };
  8604. WebVTT$1.Parser.prototype = {
  8605. // If the error is a ParsingError then report it to the consumer if
  8606. // possible. If it's not a ParsingError then throw it like normal.
  8607. reportOrThrowError: function reportOrThrowError(e) {
  8608. if (e instanceof ParsingError) {
  8609. this.onparsingerror && this.onparsingerror(e);
  8610. } else {
  8611. throw e;
  8612. }
  8613. },
  8614. parse: function parse(data) {
  8615. var self = this; // If there is no data then we won't decode it, but will just try to parse
  8616. // whatever is in buffer already. This may occur in circumstances, for
  8617. // example when flush() is called.
  8618. if (data) {
  8619. // Try to decode the data that we received.
  8620. self.buffer += self.decoder.decode(data, {
  8621. stream: true
  8622. });
  8623. }
  8624. function collectNextLine() {
  8625. var buffer = self.buffer;
  8626. var pos = 0;
  8627. while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
  8628. ++pos;
  8629. }
  8630. var line = buffer.substr(0, pos); // Advance the buffer early in case we fail below.
  8631. if (buffer[pos] === '\r') {
  8632. ++pos;
  8633. }
  8634. if (buffer[pos] === '\n') {
  8635. ++pos;
  8636. }
  8637. self.buffer = buffer.substr(pos);
  8638. return line;
  8639. } // 3.4 WebVTT region and WebVTT region settings syntax
  8640. function parseRegion(input) {
  8641. var settings = new Settings();
  8642. parseOptions(input, function (k, v) {
  8643. switch (k) {
  8644. case "id":
  8645. settings.set(k, v);
  8646. break;
  8647. case "width":
  8648. settings.percent(k, v);
  8649. break;
  8650. case "lines":
  8651. settings.integer(k, v);
  8652. break;
  8653. case "regionanchor":
  8654. case "viewportanchor":
  8655. var xy = v.split(',');
  8656. if (xy.length !== 2) {
  8657. break;
  8658. } // We have to make sure both x and y parse, so use a temporary
  8659. // settings object here.
  8660. var anchor = new Settings();
  8661. anchor.percent("x", xy[0]);
  8662. anchor.percent("y", xy[1]);
  8663. if (!anchor.has("x") || !anchor.has("y")) {
  8664. break;
  8665. }
  8666. settings.set(k + "X", anchor.get("x"));
  8667. settings.set(k + "Y", anchor.get("y"));
  8668. break;
  8669. case "scroll":
  8670. settings.alt(k, v, ["up"]);
  8671. break;
  8672. }
  8673. }, /=/, /\s/); // Create the region, using default values for any values that were not
  8674. // specified.
  8675. if (settings.has("id")) {
  8676. var region = new (self.vttjs.VTTRegion || self.window.VTTRegion)();
  8677. region.width = settings.get("width", 100);
  8678. region.lines = settings.get("lines", 3);
  8679. region.regionAnchorX = settings.get("regionanchorX", 0);
  8680. region.regionAnchorY = settings.get("regionanchorY", 100);
  8681. region.viewportAnchorX = settings.get("viewportanchorX", 0);
  8682. region.viewportAnchorY = settings.get("viewportanchorY", 100);
  8683. region.scroll = settings.get("scroll", ""); // Register the region.
  8684. self.onregion && self.onregion(region); // Remember the VTTRegion for later in case we parse any VTTCues that
  8685. // reference it.
  8686. self.regionList.push({
  8687. id: settings.get("id"),
  8688. region: region
  8689. });
  8690. }
  8691. } // draft-pantos-http-live-streaming-20
  8692. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-20#section-3.5
  8693. // 3.5 WebVTT
  8694. function parseTimestampMap(input) {
  8695. var settings = new Settings();
  8696. parseOptions(input, function (k, v) {
  8697. switch (k) {
  8698. case "MPEGT":
  8699. settings.integer(k + 'S', v);
  8700. break;
  8701. case "LOCA":
  8702. settings.set(k + 'L', parseTimeStamp(v));
  8703. break;
  8704. }
  8705. }, /[^\d]:/, /,/);
  8706. self.ontimestampmap && self.ontimestampmap({
  8707. "MPEGTS": settings.get("MPEGTS"),
  8708. "LOCAL": settings.get("LOCAL")
  8709. });
  8710. } // 3.2 WebVTT metadata header syntax
  8711. function parseHeader(input) {
  8712. if (input.match(/X-TIMESTAMP-MAP/)) {
  8713. // This line contains HLS X-TIMESTAMP-MAP metadata
  8714. parseOptions(input, function (k, v) {
  8715. switch (k) {
  8716. case "X-TIMESTAMP-MAP":
  8717. parseTimestampMap(v);
  8718. break;
  8719. }
  8720. }, /=/);
  8721. } else {
  8722. parseOptions(input, function (k, v) {
  8723. switch (k) {
  8724. case "Region":
  8725. // 3.3 WebVTT region metadata header syntax
  8726. parseRegion(v);
  8727. break;
  8728. }
  8729. }, /:/);
  8730. }
  8731. } // 5.1 WebVTT file parsing.
  8732. try {
  8733. var line;
  8734. if (self.state === "INITIAL") {
  8735. // We can't start parsing until we have the first line.
  8736. if (!/\r\n|\n/.test(self.buffer)) {
  8737. return this;
  8738. }
  8739. line = collectNextLine();
  8740. var m = line.match(/^WEBVTT([ \t].*)?$/);
  8741. if (!m || !m[0]) {
  8742. throw new ParsingError(ParsingError.Errors.BadSignature);
  8743. }
  8744. self.state = "HEADER";
  8745. }
  8746. var alreadyCollectedLine = false;
  8747. while (self.buffer) {
  8748. // We can't parse a line until we have the full line.
  8749. if (!/\r\n|\n/.test(self.buffer)) {
  8750. return this;
  8751. }
  8752. if (!alreadyCollectedLine) {
  8753. line = collectNextLine();
  8754. } else {
  8755. alreadyCollectedLine = false;
  8756. }
  8757. switch (self.state) {
  8758. case "HEADER":
  8759. // 13-18 - Allow a header (metadata) under the WEBVTT line.
  8760. if (/:/.test(line)) {
  8761. parseHeader(line);
  8762. } else if (!line) {
  8763. // An empty line terminates the header and starts the body (cues).
  8764. self.state = "ID";
  8765. }
  8766. continue;
  8767. case "NOTE":
  8768. // Ignore NOTE blocks.
  8769. if (!line) {
  8770. self.state = "ID";
  8771. }
  8772. continue;
  8773. case "ID":
  8774. // Check for the start of NOTE blocks.
  8775. if (/^NOTE($|[ \t])/.test(line)) {
  8776. self.state = "NOTE";
  8777. break;
  8778. } // 19-29 - Allow any number of line terminators, then initialize new cue values.
  8779. if (!line) {
  8780. continue;
  8781. }
  8782. self.cue = new (self.vttjs.VTTCue || self.window.VTTCue)(0, 0, ""); // Safari still uses the old middle value and won't accept center
  8783. try {
  8784. self.cue.align = "center";
  8785. } catch (e) {
  8786. self.cue.align = "middle";
  8787. }
  8788. self.state = "CUE"; // 30-39 - Check if self line contains an optional identifier or timing data.
  8789. if (line.indexOf("-->") === -1) {
  8790. self.cue.id = line;
  8791. continue;
  8792. }
  8793. // Process line as start of a cue.
  8794. /*falls through*/
  8795. case "CUE":
  8796. // 40 - Collect cue timings and settings.
  8797. try {
  8798. parseCue(line, self.cue, self.regionList);
  8799. } catch (e) {
  8800. self.reportOrThrowError(e); // In case of an error ignore rest of the cue.
  8801. self.cue = null;
  8802. self.state = "BADCUE";
  8803. continue;
  8804. }
  8805. self.state = "CUETEXT";
  8806. continue;
  8807. case "CUETEXT":
  8808. var hasSubstring = line.indexOf("-->") !== -1; // 34 - If we have an empty line then report the cue.
  8809. // 35 - If we have the special substring '-->' then report the cue,
  8810. // but do not collect the line as we need to process the current
  8811. // one as a new cue.
  8812. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  8813. // We are done parsing self cue.
  8814. self.oncue && self.oncue(self.cue);
  8815. self.cue = null;
  8816. self.state = "ID";
  8817. continue;
  8818. }
  8819. if (self.cue.text) {
  8820. self.cue.text += "\n";
  8821. }
  8822. self.cue.text += line.replace(/\u2028/g, '\n').replace(/u2029/g, '\n');
  8823. continue;
  8824. case "BADCUE":
  8825. // BADCUE
  8826. // 54-62 - Collect and discard the remaining cue.
  8827. if (!line) {
  8828. self.state = "ID";
  8829. }
  8830. continue;
  8831. }
  8832. }
  8833. } catch (e) {
  8834. self.reportOrThrowError(e); // If we are currently parsing a cue, report what we have.
  8835. if (self.state === "CUETEXT" && self.cue && self.oncue) {
  8836. self.oncue(self.cue);
  8837. }
  8838. self.cue = null; // Enter BADWEBVTT state if header was not parsed correctly otherwise
  8839. // another exception occurred so enter BADCUE state.
  8840. self.state = self.state === "INITIAL" ? "BADWEBVTT" : "BADCUE";
  8841. }
  8842. return this;
  8843. },
  8844. flush: function flush() {
  8845. var self = this;
  8846. try {
  8847. // Finish decoding the stream.
  8848. self.buffer += self.decoder.decode(); // Synthesize the end of the current cue or region.
  8849. if (self.cue || self.state === "HEADER") {
  8850. self.buffer += "\n\n";
  8851. self.parse();
  8852. } // If we've flushed, parsed, and we're still on the INITIAL state then
  8853. // that means we don't have enough of the stream to parse the first
  8854. // line.
  8855. if (self.state === "INITIAL") {
  8856. throw new ParsingError(ParsingError.Errors.BadSignature);
  8857. }
  8858. } catch (e) {
  8859. self.reportOrThrowError(e);
  8860. }
  8861. self.onflush && self.onflush();
  8862. return this;
  8863. }
  8864. };
  8865. var vtt = WebVTT$1;
  8866. /**
  8867. * Copyright 2013 vtt.js Contributors
  8868. *
  8869. * Licensed under the Apache License, Version 2.0 (the "License");
  8870. * you may not use this file except in compliance with the License.
  8871. * You may obtain a copy of the License at
  8872. *
  8873. * http://www.apache.org/licenses/LICENSE-2.0
  8874. *
  8875. * Unless required by applicable law or agreed to in writing, software
  8876. * distributed under the License is distributed on an "AS IS" BASIS,
  8877. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8878. * See the License for the specific language governing permissions and
  8879. * limitations under the License.
  8880. */
  8881. var autoKeyword = "auto";
  8882. var directionSetting = {
  8883. "": 1,
  8884. "lr": 1,
  8885. "rl": 1
  8886. };
  8887. var alignSetting = {
  8888. "start": 1,
  8889. "center": 1,
  8890. "end": 1,
  8891. "left": 1,
  8892. "right": 1,
  8893. "auto": 1,
  8894. "line-left": 1,
  8895. "line-right": 1
  8896. };
  8897. function findDirectionSetting(value) {
  8898. if (typeof value !== "string") {
  8899. return false;
  8900. }
  8901. var dir = directionSetting[value.toLowerCase()];
  8902. return dir ? value.toLowerCase() : false;
  8903. }
  8904. function findAlignSetting(value) {
  8905. if (typeof value !== "string") {
  8906. return false;
  8907. }
  8908. var align = alignSetting[value.toLowerCase()];
  8909. return align ? value.toLowerCase() : false;
  8910. }
  8911. function VTTCue(startTime, endTime, text) {
  8912. /**
  8913. * Shim implementation specific properties. These properties are not in
  8914. * the spec.
  8915. */
  8916. // Lets us know when the VTTCue's data has changed in such a way that we need
  8917. // to recompute its display state. This lets us compute its display state
  8918. // lazily.
  8919. this.hasBeenReset = false;
  8920. /**
  8921. * VTTCue and TextTrackCue properties
  8922. * http://dev.w3.org/html5/webvtt/#vttcue-interface
  8923. */
  8924. var _id = "";
  8925. var _pauseOnExit = false;
  8926. var _startTime = startTime;
  8927. var _endTime = endTime;
  8928. var _text = text;
  8929. var _region = null;
  8930. var _vertical = "";
  8931. var _snapToLines = true;
  8932. var _line = "auto";
  8933. var _lineAlign = "start";
  8934. var _position = "auto";
  8935. var _positionAlign = "auto";
  8936. var _size = 100;
  8937. var _align = "center";
  8938. Object.defineProperties(this, {
  8939. "id": {
  8940. enumerable: true,
  8941. get: function get() {
  8942. return _id;
  8943. },
  8944. set: function set(value) {
  8945. _id = "" + value;
  8946. }
  8947. },
  8948. "pauseOnExit": {
  8949. enumerable: true,
  8950. get: function get() {
  8951. return _pauseOnExit;
  8952. },
  8953. set: function set(value) {
  8954. _pauseOnExit = !!value;
  8955. }
  8956. },
  8957. "startTime": {
  8958. enumerable: true,
  8959. get: function get() {
  8960. return _startTime;
  8961. },
  8962. set: function set(value) {
  8963. if (typeof value !== "number") {
  8964. throw new TypeError("Start time must be set to a number.");
  8965. }
  8966. _startTime = value;
  8967. this.hasBeenReset = true;
  8968. }
  8969. },
  8970. "endTime": {
  8971. enumerable: true,
  8972. get: function get() {
  8973. return _endTime;
  8974. },
  8975. set: function set(value) {
  8976. if (typeof value !== "number") {
  8977. throw new TypeError("End time must be set to a number.");
  8978. }
  8979. _endTime = value;
  8980. this.hasBeenReset = true;
  8981. }
  8982. },
  8983. "text": {
  8984. enumerable: true,
  8985. get: function get() {
  8986. return _text;
  8987. },
  8988. set: function set(value) {
  8989. _text = "" + value;
  8990. this.hasBeenReset = true;
  8991. }
  8992. },
  8993. "region": {
  8994. enumerable: true,
  8995. get: function get() {
  8996. return _region;
  8997. },
  8998. set: function set(value) {
  8999. _region = value;
  9000. this.hasBeenReset = true;
  9001. }
  9002. },
  9003. "vertical": {
  9004. enumerable: true,
  9005. get: function get() {
  9006. return _vertical;
  9007. },
  9008. set: function set(value) {
  9009. var setting = findDirectionSetting(value); // Have to check for false because the setting an be an empty string.
  9010. if (setting === false) {
  9011. throw new SyntaxError("Vertical: an invalid or illegal direction string was specified.");
  9012. }
  9013. _vertical = setting;
  9014. this.hasBeenReset = true;
  9015. }
  9016. },
  9017. "snapToLines": {
  9018. enumerable: true,
  9019. get: function get() {
  9020. return _snapToLines;
  9021. },
  9022. set: function set(value) {
  9023. _snapToLines = !!value;
  9024. this.hasBeenReset = true;
  9025. }
  9026. },
  9027. "line": {
  9028. enumerable: true,
  9029. get: function get() {
  9030. return _line;
  9031. },
  9032. set: function set(value) {
  9033. if (typeof value !== "number" && value !== autoKeyword) {
  9034. throw new SyntaxError("Line: an invalid number or illegal string was specified.");
  9035. }
  9036. _line = value;
  9037. this.hasBeenReset = true;
  9038. }
  9039. },
  9040. "lineAlign": {
  9041. enumerable: true,
  9042. get: function get() {
  9043. return _lineAlign;
  9044. },
  9045. set: function set(value) {
  9046. var setting = findAlignSetting(value);
  9047. if (!setting) {
  9048. console.warn("lineAlign: an invalid or illegal string was specified.");
  9049. } else {
  9050. _lineAlign = setting;
  9051. this.hasBeenReset = true;
  9052. }
  9053. }
  9054. },
  9055. "position": {
  9056. enumerable: true,
  9057. get: function get() {
  9058. return _position;
  9059. },
  9060. set: function set(value) {
  9061. if (value < 0 || value > 100) {
  9062. throw new Error("Position must be between 0 and 100.");
  9063. }
  9064. _position = value;
  9065. this.hasBeenReset = true;
  9066. }
  9067. },
  9068. "positionAlign": {
  9069. enumerable: true,
  9070. get: function get() {
  9071. return _positionAlign;
  9072. },
  9073. set: function set(value) {
  9074. var setting = findAlignSetting(value);
  9075. if (!setting) {
  9076. console.warn("positionAlign: an invalid or illegal string was specified.");
  9077. } else {
  9078. _positionAlign = setting;
  9079. this.hasBeenReset = true;
  9080. }
  9081. }
  9082. },
  9083. "size": {
  9084. enumerable: true,
  9085. get: function get() {
  9086. return _size;
  9087. },
  9088. set: function set(value) {
  9089. if (value < 0 || value > 100) {
  9090. throw new Error("Size must be between 0 and 100.");
  9091. }
  9092. _size = value;
  9093. this.hasBeenReset = true;
  9094. }
  9095. },
  9096. "align": {
  9097. enumerable: true,
  9098. get: function get() {
  9099. return _align;
  9100. },
  9101. set: function set(value) {
  9102. var setting = findAlignSetting(value);
  9103. if (!setting) {
  9104. throw new SyntaxError("align: an invalid or illegal alignment string was specified.");
  9105. }
  9106. _align = setting;
  9107. this.hasBeenReset = true;
  9108. }
  9109. }
  9110. });
  9111. /**
  9112. * Other <track> spec defined properties
  9113. */
  9114. // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
  9115. this.displayState = undefined;
  9116. }
  9117. /**
  9118. * VTTCue methods
  9119. */
  9120. VTTCue.prototype.getCueAsHTML = function () {
  9121. // Assume WebVTT.convertCueToDOMTree is on the global.
  9122. return WebVTT.convertCueToDOMTree(window, this.text);
  9123. };
  9124. var vttcue = VTTCue;
  9125. /**
  9126. * Copyright 2013 vtt.js Contributors
  9127. *
  9128. * Licensed under the Apache License, Version 2.0 (the "License");
  9129. * you may not use this file except in compliance with the License.
  9130. * You may obtain a copy of the License at
  9131. *
  9132. * http://www.apache.org/licenses/LICENSE-2.0
  9133. *
  9134. * Unless required by applicable law or agreed to in writing, software
  9135. * distributed under the License is distributed on an "AS IS" BASIS,
  9136. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9137. * See the License for the specific language governing permissions and
  9138. * limitations under the License.
  9139. */
  9140. var scrollSetting = {
  9141. "": true,
  9142. "up": true
  9143. };
  9144. function findScrollSetting(value) {
  9145. if (typeof value !== "string") {
  9146. return false;
  9147. }
  9148. var scroll = scrollSetting[value.toLowerCase()];
  9149. return scroll ? value.toLowerCase() : false;
  9150. }
  9151. function isValidPercentValue(value) {
  9152. return typeof value === "number" && value >= 0 && value <= 100;
  9153. } // VTTRegion shim http://dev.w3.org/html5/webvtt/#vttregion-interface
  9154. function VTTRegion() {
  9155. var _width = 100;
  9156. var _lines = 3;
  9157. var _regionAnchorX = 0;
  9158. var _regionAnchorY = 100;
  9159. var _viewportAnchorX = 0;
  9160. var _viewportAnchorY = 100;
  9161. var _scroll = "";
  9162. Object.defineProperties(this, {
  9163. "width": {
  9164. enumerable: true,
  9165. get: function get() {
  9166. return _width;
  9167. },
  9168. set: function set(value) {
  9169. if (!isValidPercentValue(value)) {
  9170. throw new Error("Width must be between 0 and 100.");
  9171. }
  9172. _width = value;
  9173. }
  9174. },
  9175. "lines": {
  9176. enumerable: true,
  9177. get: function get() {
  9178. return _lines;
  9179. },
  9180. set: function set(value) {
  9181. if (typeof value !== "number") {
  9182. throw new TypeError("Lines must be set to a number.");
  9183. }
  9184. _lines = value;
  9185. }
  9186. },
  9187. "regionAnchorY": {
  9188. enumerable: true,
  9189. get: function get() {
  9190. return _regionAnchorY;
  9191. },
  9192. set: function set(value) {
  9193. if (!isValidPercentValue(value)) {
  9194. throw new Error("RegionAnchorX must be between 0 and 100.");
  9195. }
  9196. _regionAnchorY = value;
  9197. }
  9198. },
  9199. "regionAnchorX": {
  9200. enumerable: true,
  9201. get: function get() {
  9202. return _regionAnchorX;
  9203. },
  9204. set: function set(value) {
  9205. if (!isValidPercentValue(value)) {
  9206. throw new Error("RegionAnchorY must be between 0 and 100.");
  9207. }
  9208. _regionAnchorX = value;
  9209. }
  9210. },
  9211. "viewportAnchorY": {
  9212. enumerable: true,
  9213. get: function get() {
  9214. return _viewportAnchorY;
  9215. },
  9216. set: function set(value) {
  9217. if (!isValidPercentValue(value)) {
  9218. throw new Error("ViewportAnchorY must be between 0 and 100.");
  9219. }
  9220. _viewportAnchorY = value;
  9221. }
  9222. },
  9223. "viewportAnchorX": {
  9224. enumerable: true,
  9225. get: function get() {
  9226. return _viewportAnchorX;
  9227. },
  9228. set: function set(value) {
  9229. if (!isValidPercentValue(value)) {
  9230. throw new Error("ViewportAnchorX must be between 0 and 100.");
  9231. }
  9232. _viewportAnchorX = value;
  9233. }
  9234. },
  9235. "scroll": {
  9236. enumerable: true,
  9237. get: function get() {
  9238. return _scroll;
  9239. },
  9240. set: function set(value) {
  9241. var setting = findScrollSetting(value); // Have to check for false as an empty string is a legal value.
  9242. if (setting === false) {
  9243. console.warn("Scroll: an invalid or illegal string was specified.");
  9244. } else {
  9245. _scroll = setting;
  9246. }
  9247. }
  9248. }
  9249. });
  9250. }
  9251. var vttregion = VTTRegion;
  9252. var browserIndex = createCommonjsModule(function (module) {
  9253. /**
  9254. * Copyright 2013 vtt.js Contributors
  9255. *
  9256. * Licensed under the Apache License, Version 2.0 (the "License");
  9257. * you may not use this file except in compliance with the License.
  9258. * You may obtain a copy of the License at
  9259. *
  9260. * http://www.apache.org/licenses/LICENSE-2.0
  9261. *
  9262. * Unless required by applicable law or agreed to in writing, software
  9263. * distributed under the License is distributed on an "AS IS" BASIS,
  9264. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9265. * See the License for the specific language governing permissions and
  9266. * limitations under the License.
  9267. */
  9268. // Default exports for Node. Export the extended versions of VTTCue and
  9269. // VTTRegion in Node since we likely want the capability to convert back and
  9270. // forth between JSON. If we don't then it's not that big of a deal since we're
  9271. // off browser.
  9272. var vttjs = module.exports = {
  9273. WebVTT: vtt,
  9274. VTTCue: vttcue,
  9275. VTTRegion: vttregion
  9276. };
  9277. window_1.vttjs = vttjs;
  9278. window_1.WebVTT = vttjs.WebVTT;
  9279. var cueShim = vttjs.VTTCue;
  9280. var regionShim = vttjs.VTTRegion;
  9281. var nativeVTTCue = window_1.VTTCue;
  9282. var nativeVTTRegion = window_1.VTTRegion;
  9283. vttjs.shim = function () {
  9284. window_1.VTTCue = cueShim;
  9285. window_1.VTTRegion = regionShim;
  9286. };
  9287. vttjs.restore = function () {
  9288. window_1.VTTCue = nativeVTTCue;
  9289. window_1.VTTRegion = nativeVTTRegion;
  9290. };
  9291. if (!window_1.VTTCue) {
  9292. vttjs.shim();
  9293. }
  9294. });
  9295. browserIndex.WebVTT;
  9296. browserIndex.VTTCue;
  9297. browserIndex.VTTRegion;
  9298. /**
  9299. * An Object containing a structure like: `{src: 'url', type: 'mimetype'}` or string
  9300. * that just contains the src url alone.
  9301. * * `var SourceObject = {src: 'http://ex.com/video.mp4', type: 'video/mp4'};`
  9302. * `var SourceString = 'http://example.com/some-video.mp4';`
  9303. *
  9304. * @typedef {Object|string} Tech~SourceObject
  9305. *
  9306. * @property {string} src
  9307. * The url to the source
  9308. *
  9309. * @property {string} type
  9310. * The mime type of the source
  9311. */
  9312. /**
  9313. * A function used by {@link Tech} to create a new {@link TextTrack}.
  9314. *
  9315. * @private
  9316. *
  9317. * @param {Tech} self
  9318. * An instance of the Tech class.
  9319. *
  9320. * @param {string} kind
  9321. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  9322. *
  9323. * @param {string} [label]
  9324. * Label to identify the text track
  9325. *
  9326. * @param {string} [language]
  9327. * Two letter language abbreviation
  9328. *
  9329. * @param {Object} [options={}]
  9330. * An object with additional text track options
  9331. *
  9332. * @return {TextTrack}
  9333. * The text track that was created.
  9334. */
  9335. function createTrackHelper(self, kind, label, language, options) {
  9336. if (options === void 0) {
  9337. options = {};
  9338. }
  9339. var tracks = self.textTracks();
  9340. options.kind = kind;
  9341. if (label) {
  9342. options.label = label;
  9343. }
  9344. if (language) {
  9345. options.language = language;
  9346. }
  9347. options.tech = self;
  9348. var track = new ALL.text.TrackClass(options);
  9349. tracks.addTrack(track);
  9350. return track;
  9351. }
  9352. /**
  9353. * This is the base class for media playback technology controllers, such as
  9354. * {@link HTML5}
  9355. *
  9356. * @extends Component
  9357. */
  9358. var Tech = /*#__PURE__*/function (_Component) {
  9359. inheritsLoose(Tech, _Component);
  9360. /**
  9361. * Create an instance of this Tech.
  9362. *
  9363. * @param {Object} [options]
  9364. * The key/value store of player options.
  9365. *
  9366. * @param {Component~ReadyCallback} ready
  9367. * Callback function to call when the `HTML5` Tech is ready.
  9368. */
  9369. function Tech(options, ready) {
  9370. var _this;
  9371. if (options === void 0) {
  9372. options = {};
  9373. }
  9374. if (ready === void 0) {
  9375. ready = function ready() {};
  9376. }
  9377. // we don't want the tech to report user activity automatically.
  9378. // This is done manually in addControlsListeners
  9379. options.reportTouchActivity = false;
  9380. _this = _Component.call(this, null, options, ready) || this;
  9381. _this.onDurationChange_ = function (e) {
  9382. return _this.onDurationChange(e);
  9383. };
  9384. _this.trackProgress_ = function (e) {
  9385. return _this.trackProgress(e);
  9386. };
  9387. _this.trackCurrentTime_ = function (e) {
  9388. return _this.trackCurrentTime(e);
  9389. };
  9390. _this.stopTrackingCurrentTime_ = function (e) {
  9391. return _this.stopTrackingCurrentTime(e);
  9392. };
  9393. _this.disposeSourceHandler_ = function (e) {
  9394. return _this.disposeSourceHandler(e);
  9395. };
  9396. _this.queuedHanders_ = new Set(); // keep track of whether the current source has played at all to
  9397. // implement a very limited played()
  9398. _this.hasStarted_ = false;
  9399. _this.on('playing', function () {
  9400. this.hasStarted_ = true;
  9401. });
  9402. _this.on('loadstart', function () {
  9403. this.hasStarted_ = false;
  9404. });
  9405. ALL.names.forEach(function (name) {
  9406. var props = ALL[name];
  9407. if (options && options[props.getterName]) {
  9408. _this[props.privateName] = options[props.getterName];
  9409. }
  9410. }); // Manually track progress in cases where the browser/tech doesn't report it.
  9411. if (!_this.featuresProgressEvents) {
  9412. _this.manualProgressOn();
  9413. } // Manually track timeupdates in cases where the browser/tech doesn't report it.
  9414. if (!_this.featuresTimeupdateEvents) {
  9415. _this.manualTimeUpdatesOn();
  9416. }
  9417. ['Text', 'Audio', 'Video'].forEach(function (track) {
  9418. if (options["native" + track + "Tracks"] === false) {
  9419. _this["featuresNative" + track + "Tracks"] = false;
  9420. }
  9421. });
  9422. if (options.nativeCaptions === false || options.nativeTextTracks === false) {
  9423. _this.featuresNativeTextTracks = false;
  9424. } else if (options.nativeCaptions === true || options.nativeTextTracks === true) {
  9425. _this.featuresNativeTextTracks = true;
  9426. }
  9427. if (!_this.featuresNativeTextTracks) {
  9428. _this.emulateTextTracks();
  9429. }
  9430. _this.preloadTextTracks = options.preloadTextTracks !== false;
  9431. _this.autoRemoteTextTracks_ = new ALL.text.ListClass();
  9432. _this.initTrackListeners(); // Turn on component tap events only if not using native controls
  9433. if (!options.nativeControlsForTouch) {
  9434. _this.emitTapEvents();
  9435. }
  9436. if (_this.constructor) {
  9437. _this.name_ = _this.constructor.name || 'Unknown Tech';
  9438. }
  9439. return _this;
  9440. }
  9441. /**
  9442. * A special function to trigger source set in a way that will allow player
  9443. * to re-trigger if the player or tech are not ready yet.
  9444. *
  9445. * @fires Tech#sourceset
  9446. * @param {string} src The source string at the time of the source changing.
  9447. */
  9448. var _proto = Tech.prototype;
  9449. _proto.triggerSourceset = function triggerSourceset(src) {
  9450. var _this2 = this;
  9451. if (!this.isReady_) {
  9452. // on initial ready we have to trigger source set
  9453. // 1ms after ready so that player can watch for it.
  9454. this.one('ready', function () {
  9455. return _this2.setTimeout(function () {
  9456. return _this2.triggerSourceset(src);
  9457. }, 1);
  9458. });
  9459. }
  9460. /**
  9461. * Fired when the source is set on the tech causing the media element
  9462. * to reload.
  9463. *
  9464. * @see {@link Player#event:sourceset}
  9465. * @event Tech#sourceset
  9466. * @type {EventTarget~Event}
  9467. */
  9468. this.trigger({
  9469. src: src,
  9470. type: 'sourceset'
  9471. });
  9472. }
  9473. /* Fallbacks for unsupported event types
  9474. ================================================================================ */
  9475. /**
  9476. * Polyfill the `progress` event for browsers that don't support it natively.
  9477. *
  9478. * @see {@link Tech#trackProgress}
  9479. */
  9480. ;
  9481. _proto.manualProgressOn = function manualProgressOn() {
  9482. this.on('durationchange', this.onDurationChange_);
  9483. this.manualProgress = true; // Trigger progress watching when a source begins loading
  9484. this.one('ready', this.trackProgress_);
  9485. }
  9486. /**
  9487. * Turn off the polyfill for `progress` events that was created in
  9488. * {@link Tech#manualProgressOn}
  9489. */
  9490. ;
  9491. _proto.manualProgressOff = function manualProgressOff() {
  9492. this.manualProgress = false;
  9493. this.stopTrackingProgress();
  9494. this.off('durationchange', this.onDurationChange_);
  9495. }
  9496. /**
  9497. * This is used to trigger a `progress` event when the buffered percent changes. It
  9498. * sets an interval function that will be called every 500 milliseconds to check if the
  9499. * buffer end percent has changed.
  9500. *
  9501. * > This function is called by {@link Tech#manualProgressOn}
  9502. *
  9503. * @param {EventTarget~Event} event
  9504. * The `ready` event that caused this to run.
  9505. *
  9506. * @listens Tech#ready
  9507. * @fires Tech#progress
  9508. */
  9509. ;
  9510. _proto.trackProgress = function trackProgress(event) {
  9511. this.stopTrackingProgress();
  9512. this.progressInterval = this.setInterval(bind(this, function () {
  9513. // Don't trigger unless buffered amount is greater than last time
  9514. var numBufferedPercent = this.bufferedPercent();
  9515. if (this.bufferedPercent_ !== numBufferedPercent) {
  9516. /**
  9517. * See {@link Player#progress}
  9518. *
  9519. * @event Tech#progress
  9520. * @type {EventTarget~Event}
  9521. */
  9522. this.trigger('progress');
  9523. }
  9524. this.bufferedPercent_ = numBufferedPercent;
  9525. if (numBufferedPercent === 1) {
  9526. this.stopTrackingProgress();
  9527. }
  9528. }), 500);
  9529. }
  9530. /**
  9531. * Update our internal duration on a `durationchange` event by calling
  9532. * {@link Tech#duration}.
  9533. *
  9534. * @param {EventTarget~Event} event
  9535. * The `durationchange` event that caused this to run.
  9536. *
  9537. * @listens Tech#durationchange
  9538. */
  9539. ;
  9540. _proto.onDurationChange = function onDurationChange(event) {
  9541. this.duration_ = this.duration();
  9542. }
  9543. /**
  9544. * Get and create a `TimeRange` object for buffering.
  9545. *
  9546. * @return {TimeRange}
  9547. * The time range object that was created.
  9548. */
  9549. ;
  9550. _proto.buffered = function buffered() {
  9551. return createTimeRanges(0, 0);
  9552. }
  9553. /**
  9554. * Get the percentage of the current video that is currently buffered.
  9555. *
  9556. * @return {number}
  9557. * A number from 0 to 1 that represents the decimal percentage of the
  9558. * video that is buffered.
  9559. *
  9560. */
  9561. ;
  9562. _proto.bufferedPercent = function bufferedPercent$1() {
  9563. return bufferedPercent(this.buffered(), this.duration_);
  9564. }
  9565. /**
  9566. * Turn off the polyfill for `progress` events that was created in
  9567. * {@link Tech#manualProgressOn}
  9568. * Stop manually tracking progress events by clearing the interval that was set in
  9569. * {@link Tech#trackProgress}.
  9570. */
  9571. ;
  9572. _proto.stopTrackingProgress = function stopTrackingProgress() {
  9573. this.clearInterval(this.progressInterval);
  9574. }
  9575. /**
  9576. * Polyfill the `timeupdate` event for browsers that don't support it.
  9577. *
  9578. * @see {@link Tech#trackCurrentTime}
  9579. */
  9580. ;
  9581. _proto.manualTimeUpdatesOn = function manualTimeUpdatesOn() {
  9582. this.manualTimeUpdates = true;
  9583. this.on('play', this.trackCurrentTime_);
  9584. this.on('pause', this.stopTrackingCurrentTime_);
  9585. }
  9586. /**
  9587. * Turn off the polyfill for `timeupdate` events that was created in
  9588. * {@link Tech#manualTimeUpdatesOn}
  9589. */
  9590. ;
  9591. _proto.manualTimeUpdatesOff = function manualTimeUpdatesOff() {
  9592. this.manualTimeUpdates = false;
  9593. this.stopTrackingCurrentTime();
  9594. this.off('play', this.trackCurrentTime_);
  9595. this.off('pause', this.stopTrackingCurrentTime_);
  9596. }
  9597. /**
  9598. * Sets up an interval function to track current time and trigger `timeupdate` every
  9599. * 250 milliseconds.
  9600. *
  9601. * @listens Tech#play
  9602. * @triggers Tech#timeupdate
  9603. */
  9604. ;
  9605. _proto.trackCurrentTime = function trackCurrentTime() {
  9606. if (this.currentTimeInterval) {
  9607. this.stopTrackingCurrentTime();
  9608. }
  9609. this.currentTimeInterval = this.setInterval(function () {
  9610. /**
  9611. * Triggered at an interval of 250ms to indicated that time is passing in the video.
  9612. *
  9613. * @event Tech#timeupdate
  9614. * @type {EventTarget~Event}
  9615. */
  9616. this.trigger({
  9617. type: 'timeupdate',
  9618. target: this,
  9619. manuallyTriggered: true
  9620. }); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  9621. }, 250);
  9622. }
  9623. /**
  9624. * Stop the interval function created in {@link Tech#trackCurrentTime} so that the
  9625. * `timeupdate` event is no longer triggered.
  9626. *
  9627. * @listens {Tech#pause}
  9628. */
  9629. ;
  9630. _proto.stopTrackingCurrentTime = function stopTrackingCurrentTime() {
  9631. this.clearInterval(this.currentTimeInterval); // #1002 - if the video ends right before the next timeupdate would happen,
  9632. // the progress bar won't make it all the way to the end
  9633. this.trigger({
  9634. type: 'timeupdate',
  9635. target: this,
  9636. manuallyTriggered: true
  9637. });
  9638. }
  9639. /**
  9640. * Turn off all event polyfills, clear the `Tech`s {@link AudioTrackList},
  9641. * {@link VideoTrackList}, and {@link TextTrackList}, and dispose of this Tech.
  9642. *
  9643. * @fires Component#dispose
  9644. */
  9645. ;
  9646. _proto.dispose = function dispose() {
  9647. // clear out all tracks because we can't reuse them between techs
  9648. this.clearTracks(NORMAL.names); // Turn off any manual progress or timeupdate tracking
  9649. if (this.manualProgress) {
  9650. this.manualProgressOff();
  9651. }
  9652. if (this.manualTimeUpdates) {
  9653. this.manualTimeUpdatesOff();
  9654. }
  9655. _Component.prototype.dispose.call(this);
  9656. }
  9657. /**
  9658. * Clear out a single `TrackList` or an array of `TrackLists` given their names.
  9659. *
  9660. * > Note: Techs without source handlers should call this between sources for `video`
  9661. * & `audio` tracks. You don't want to use them between tracks!
  9662. *
  9663. * @param {string[]|string} types
  9664. * TrackList names to clear, valid names are `video`, `audio`, and
  9665. * `text`.
  9666. */
  9667. ;
  9668. _proto.clearTracks = function clearTracks(types) {
  9669. var _this3 = this;
  9670. types = [].concat(types); // clear out all tracks because we can't reuse them between techs
  9671. types.forEach(function (type) {
  9672. var list = _this3[type + "Tracks"]() || [];
  9673. var i = list.length;
  9674. while (i--) {
  9675. var track = list[i];
  9676. if (type === 'text') {
  9677. _this3.removeRemoteTextTrack(track);
  9678. }
  9679. list.removeTrack(track);
  9680. }
  9681. });
  9682. }
  9683. /**
  9684. * Remove any TextTracks added via addRemoteTextTrack that are
  9685. * flagged for automatic garbage collection
  9686. */
  9687. ;
  9688. _proto.cleanupAutoTextTracks = function cleanupAutoTextTracks() {
  9689. var list = this.autoRemoteTextTracks_ || [];
  9690. var i = list.length;
  9691. while (i--) {
  9692. var track = list[i];
  9693. this.removeRemoteTextTrack(track);
  9694. }
  9695. }
  9696. /**
  9697. * Reset the tech, which will removes all sources and reset the internal readyState.
  9698. *
  9699. * @abstract
  9700. */
  9701. ;
  9702. _proto.reset = function reset() {}
  9703. /**
  9704. * Get the value of `crossOrigin` from the tech.
  9705. *
  9706. * @abstract
  9707. *
  9708. * @see {Html5#crossOrigin}
  9709. */
  9710. ;
  9711. _proto.crossOrigin = function crossOrigin() {}
  9712. /**
  9713. * Set the value of `crossOrigin` on the tech.
  9714. *
  9715. * @abstract
  9716. *
  9717. * @param {string} crossOrigin the crossOrigin value
  9718. * @see {Html5#setCrossOrigin}
  9719. */
  9720. ;
  9721. _proto.setCrossOrigin = function setCrossOrigin() {}
  9722. /**
  9723. * Get or set an error on the Tech.
  9724. *
  9725. * @param {MediaError} [err]
  9726. * Error to set on the Tech
  9727. *
  9728. * @return {MediaError|null}
  9729. * The current error object on the tech, or null if there isn't one.
  9730. */
  9731. ;
  9732. _proto.error = function error(err) {
  9733. if (err !== undefined) {
  9734. this.error_ = new MediaError(err);
  9735. this.trigger('error');
  9736. }
  9737. return this.error_;
  9738. }
  9739. /**
  9740. * Returns the `TimeRange`s that have been played through for the current source.
  9741. *
  9742. * > NOTE: This implementation is incomplete. It does not track the played `TimeRange`.
  9743. * It only checks whether the source has played at all or not.
  9744. *
  9745. * @return {TimeRange}
  9746. * - A single time range if this video has played
  9747. * - An empty set of ranges if not.
  9748. */
  9749. ;
  9750. _proto.played = function played() {
  9751. if (this.hasStarted_) {
  9752. return createTimeRanges(0, 0);
  9753. }
  9754. return createTimeRanges();
  9755. }
  9756. /**
  9757. * Start playback
  9758. *
  9759. * @abstract
  9760. *
  9761. * @see {Html5#play}
  9762. */
  9763. ;
  9764. _proto.play = function play() {}
  9765. /**
  9766. * Set whether we are scrubbing or not
  9767. *
  9768. * @abstract
  9769. *
  9770. * @see {Html5#setScrubbing}
  9771. */
  9772. ;
  9773. _proto.setScrubbing = function setScrubbing() {}
  9774. /**
  9775. * Get whether we are scrubbing or not
  9776. *
  9777. * @abstract
  9778. *
  9779. * @see {Html5#scrubbing}
  9780. */
  9781. ;
  9782. _proto.scrubbing = function scrubbing() {}
  9783. /**
  9784. * Causes a manual time update to occur if {@link Tech#manualTimeUpdatesOn} was
  9785. * previously called.
  9786. *
  9787. * @fires Tech#timeupdate
  9788. */
  9789. ;
  9790. _proto.setCurrentTime = function setCurrentTime() {
  9791. // improve the accuracy of manual timeupdates
  9792. if (this.manualTimeUpdates) {
  9793. /**
  9794. * A manual `timeupdate` event.
  9795. *
  9796. * @event Tech#timeupdate
  9797. * @type {EventTarget~Event}
  9798. */
  9799. this.trigger({
  9800. type: 'timeupdate',
  9801. target: this,
  9802. manuallyTriggered: true
  9803. });
  9804. }
  9805. }
  9806. /**
  9807. * Turn on listeners for {@link VideoTrackList}, {@link {AudioTrackList}, and
  9808. * {@link TextTrackList} events.
  9809. *
  9810. * This adds {@link EventTarget~EventListeners} for `addtrack`, and `removetrack`.
  9811. *
  9812. * @fires Tech#audiotrackchange
  9813. * @fires Tech#videotrackchange
  9814. * @fires Tech#texttrackchange
  9815. */
  9816. ;
  9817. _proto.initTrackListeners = function initTrackListeners() {
  9818. var _this4 = this;
  9819. /**
  9820. * Triggered when tracks are added or removed on the Tech {@link AudioTrackList}
  9821. *
  9822. * @event Tech#audiotrackchange
  9823. * @type {EventTarget~Event}
  9824. */
  9825. /**
  9826. * Triggered when tracks are added or removed on the Tech {@link VideoTrackList}
  9827. *
  9828. * @event Tech#videotrackchange
  9829. * @type {EventTarget~Event}
  9830. */
  9831. /**
  9832. * Triggered when tracks are added or removed on the Tech {@link TextTrackList}
  9833. *
  9834. * @event Tech#texttrackchange
  9835. * @type {EventTarget~Event}
  9836. */
  9837. NORMAL.names.forEach(function (name) {
  9838. var props = NORMAL[name];
  9839. var trackListChanges = function trackListChanges() {
  9840. _this4.trigger(name + "trackchange");
  9841. };
  9842. var tracks = _this4[props.getterName]();
  9843. tracks.addEventListener('removetrack', trackListChanges);
  9844. tracks.addEventListener('addtrack', trackListChanges);
  9845. _this4.on('dispose', function () {
  9846. tracks.removeEventListener('removetrack', trackListChanges);
  9847. tracks.removeEventListener('addtrack', trackListChanges);
  9848. });
  9849. });
  9850. }
  9851. /**
  9852. * Emulate TextTracks using vtt.js if necessary
  9853. *
  9854. * @fires Tech#vttjsloaded
  9855. * @fires Tech#vttjserror
  9856. */
  9857. ;
  9858. _proto.addWebVttScript_ = function addWebVttScript_() {
  9859. var _this5 = this;
  9860. if (window.WebVTT) {
  9861. return;
  9862. } // Initially, Tech.el_ is a child of a dummy-div wait until the Component system
  9863. // signals that the Tech is ready at which point Tech.el_ is part of the DOM
  9864. // before inserting the WebVTT script
  9865. if (document.body.contains(this.el())) {
  9866. // load via require if available and vtt.js script location was not passed in
  9867. // as an option. novtt builds will turn the above require call into an empty object
  9868. // which will cause this if check to always fail.
  9869. if (!this.options_['vtt.js'] && isPlain(browserIndex) && Object.keys(browserIndex).length > 0) {
  9870. this.trigger('vttjsloaded');
  9871. return;
  9872. } // load vtt.js via the script location option or the cdn of no location was
  9873. // passed in
  9874. var script = document.createElement('script');
  9875. script.src = this.options_['vtt.js'] || 'https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js';
  9876. script.onload = function () {
  9877. /**
  9878. * Fired when vtt.js is loaded.
  9879. *
  9880. * @event Tech#vttjsloaded
  9881. * @type {EventTarget~Event}
  9882. */
  9883. _this5.trigger('vttjsloaded');
  9884. };
  9885. script.onerror = function () {
  9886. /**
  9887. * Fired when vtt.js was not loaded due to an error
  9888. *
  9889. * @event Tech#vttjsloaded
  9890. * @type {EventTarget~Event}
  9891. */
  9892. _this5.trigger('vttjserror');
  9893. };
  9894. this.on('dispose', function () {
  9895. script.onload = null;
  9896. script.onerror = null;
  9897. }); // but have not loaded yet and we set it to true before the inject so that
  9898. // we don't overwrite the injected window.WebVTT if it loads right away
  9899. window.WebVTT = true;
  9900. this.el().parentNode.appendChild(script);
  9901. } else {
  9902. this.ready(this.addWebVttScript_);
  9903. }
  9904. }
  9905. /**
  9906. * Emulate texttracks
  9907. *
  9908. */
  9909. ;
  9910. _proto.emulateTextTracks = function emulateTextTracks() {
  9911. var _this6 = this;
  9912. var tracks = this.textTracks();
  9913. var remoteTracks = this.remoteTextTracks();
  9914. var handleAddTrack = function handleAddTrack(e) {
  9915. return tracks.addTrack(e.track);
  9916. };
  9917. var handleRemoveTrack = function handleRemoveTrack(e) {
  9918. return tracks.removeTrack(e.track);
  9919. };
  9920. remoteTracks.on('addtrack', handleAddTrack);
  9921. remoteTracks.on('removetrack', handleRemoveTrack);
  9922. this.addWebVttScript_();
  9923. var updateDisplay = function updateDisplay() {
  9924. return _this6.trigger('texttrackchange');
  9925. };
  9926. var textTracksChanges = function textTracksChanges() {
  9927. updateDisplay();
  9928. for (var i = 0; i < tracks.length; i++) {
  9929. var track = tracks[i];
  9930. track.removeEventListener('cuechange', updateDisplay);
  9931. if (track.mode === 'showing') {
  9932. track.addEventListener('cuechange', updateDisplay);
  9933. }
  9934. }
  9935. };
  9936. textTracksChanges();
  9937. tracks.addEventListener('change', textTracksChanges);
  9938. tracks.addEventListener('addtrack', textTracksChanges);
  9939. tracks.addEventListener('removetrack', textTracksChanges);
  9940. this.on('dispose', function () {
  9941. remoteTracks.off('addtrack', handleAddTrack);
  9942. remoteTracks.off('removetrack', handleRemoveTrack);
  9943. tracks.removeEventListener('change', textTracksChanges);
  9944. tracks.removeEventListener('addtrack', textTracksChanges);
  9945. tracks.removeEventListener('removetrack', textTracksChanges);
  9946. for (var i = 0; i < tracks.length; i++) {
  9947. var track = tracks[i];
  9948. track.removeEventListener('cuechange', updateDisplay);
  9949. }
  9950. });
  9951. }
  9952. /**
  9953. * Create and returns a remote {@link TextTrack} object.
  9954. *
  9955. * @param {string} kind
  9956. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  9957. *
  9958. * @param {string} [label]
  9959. * Label to identify the text track
  9960. *
  9961. * @param {string} [language]
  9962. * Two letter language abbreviation
  9963. *
  9964. * @return {TextTrack}
  9965. * The TextTrack that gets created.
  9966. */
  9967. ;
  9968. _proto.addTextTrack = function addTextTrack(kind, label, language) {
  9969. if (!kind) {
  9970. throw new Error('TextTrack kind is required but was not provided');
  9971. }
  9972. return createTrackHelper(this, kind, label, language);
  9973. }
  9974. /**
  9975. * Create an emulated TextTrack for use by addRemoteTextTrack
  9976. *
  9977. * This is intended to be overridden by classes that inherit from
  9978. * Tech in order to create native or custom TextTracks.
  9979. *
  9980. * @param {Object} options
  9981. * The object should contain the options to initialize the TextTrack with.
  9982. *
  9983. * @param {string} [options.kind]
  9984. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
  9985. *
  9986. * @param {string} [options.label].
  9987. * Label to identify the text track
  9988. *
  9989. * @param {string} [options.language]
  9990. * Two letter language abbreviation.
  9991. *
  9992. * @return {HTMLTrackElement}
  9993. * The track element that gets created.
  9994. */
  9995. ;
  9996. _proto.createRemoteTextTrack = function createRemoteTextTrack(options) {
  9997. var track = mergeOptions$3(options, {
  9998. tech: this
  9999. });
  10000. return new REMOTE.remoteTextEl.TrackClass(track);
  10001. }
  10002. /**
  10003. * Creates a remote text track object and returns an html track element.
  10004. *
  10005. * > Note: This can be an emulated {@link HTMLTrackElement} or a native one.
  10006. *
  10007. * @param {Object} options
  10008. * See {@link Tech#createRemoteTextTrack} for more detailed properties.
  10009. *
  10010. * @param {boolean} [manualCleanup=true]
  10011. * - When false: the TextTrack will be automatically removed from the video
  10012. * element whenever the source changes
  10013. * - When True: The TextTrack will have to be cleaned up manually
  10014. *
  10015. * @return {HTMLTrackElement}
  10016. * An Html Track Element.
  10017. *
  10018. * @deprecated The default functionality for this function will be equivalent
  10019. * to "manualCleanup=false" in the future. The manualCleanup parameter will
  10020. * also be removed.
  10021. */
  10022. ;
  10023. _proto.addRemoteTextTrack = function addRemoteTextTrack(options, manualCleanup) {
  10024. var _this7 = this;
  10025. if (options === void 0) {
  10026. options = {};
  10027. }
  10028. var htmlTrackElement = this.createRemoteTextTrack(options);
  10029. if (manualCleanup !== true && manualCleanup !== false) {
  10030. // deprecation warning
  10031. log$1.warn('Calling addRemoteTextTrack without explicitly setting the "manualCleanup" parameter to `true` is deprecated and default to `false` in future version of video.js');
  10032. manualCleanup = true;
  10033. } // store HTMLTrackElement and TextTrack to remote list
  10034. this.remoteTextTrackEls().addTrackElement_(htmlTrackElement);
  10035. this.remoteTextTracks().addTrack(htmlTrackElement.track);
  10036. if (manualCleanup !== true) {
  10037. // create the TextTrackList if it doesn't exist
  10038. this.ready(function () {
  10039. return _this7.autoRemoteTextTracks_.addTrack(htmlTrackElement.track);
  10040. });
  10041. }
  10042. return htmlTrackElement;
  10043. }
  10044. /**
  10045. * Remove a remote text track from the remote `TextTrackList`.
  10046. *
  10047. * @param {TextTrack} track
  10048. * `TextTrack` to remove from the `TextTrackList`
  10049. */
  10050. ;
  10051. _proto.removeRemoteTextTrack = function removeRemoteTextTrack(track) {
  10052. var trackElement = this.remoteTextTrackEls().getTrackElementByTrack_(track); // remove HTMLTrackElement and TextTrack from remote list
  10053. this.remoteTextTrackEls().removeTrackElement_(trackElement);
  10054. this.remoteTextTracks().removeTrack(track);
  10055. this.autoRemoteTextTracks_.removeTrack(track);
  10056. }
  10057. /**
  10058. * Gets available media playback quality metrics as specified by the W3C's Media
  10059. * Playback Quality API.
  10060. *
  10061. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  10062. *
  10063. * @return {Object}
  10064. * An object with supported media playback quality metrics
  10065. *
  10066. * @abstract
  10067. */
  10068. ;
  10069. _proto.getVideoPlaybackQuality = function getVideoPlaybackQuality() {
  10070. return {};
  10071. }
  10072. /**
  10073. * Attempt to create a floating video window always on top of other windows
  10074. * so that users may continue consuming media while they interact with other
  10075. * content sites, or applications on their device.
  10076. *
  10077. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  10078. *
  10079. * @return {Promise|undefined}
  10080. * A promise with a Picture-in-Picture window if the browser supports
  10081. * Promises (or one was passed in as an option). It returns undefined
  10082. * otherwise.
  10083. *
  10084. * @abstract
  10085. */
  10086. ;
  10087. _proto.requestPictureInPicture = function requestPictureInPicture() {
  10088. var PromiseClass = this.options_.Promise || window.Promise;
  10089. if (PromiseClass) {
  10090. return PromiseClass.reject();
  10091. }
  10092. }
  10093. /**
  10094. * A method to check for the value of the 'disablePictureInPicture' <video> property.
  10095. * Defaults to true, as it should be considered disabled if the tech does not support pip
  10096. *
  10097. * @abstract
  10098. */
  10099. ;
  10100. _proto.disablePictureInPicture = function disablePictureInPicture() {
  10101. return true;
  10102. }
  10103. /**
  10104. * A method to set or unset the 'disablePictureInPicture' <video> property.
  10105. *
  10106. * @abstract
  10107. */
  10108. ;
  10109. _proto.setDisablePictureInPicture = function setDisablePictureInPicture() {}
  10110. /**
  10111. * A fallback implementation of requestVideoFrameCallback using requestAnimationFrame
  10112. *
  10113. * @param {function} cb
  10114. * @return {number} request id
  10115. */
  10116. ;
  10117. _proto.requestVideoFrameCallback = function requestVideoFrameCallback(cb) {
  10118. var _this8 = this;
  10119. var id = newGUID();
  10120. if (!this.isReady_ || this.paused()) {
  10121. this.queuedHanders_.add(id);
  10122. this.one('playing', function () {
  10123. if (_this8.queuedHanders_.has(id)) {
  10124. _this8.queuedHanders_["delete"](id);
  10125. cb();
  10126. }
  10127. });
  10128. } else {
  10129. this.requestNamedAnimationFrame(id, cb);
  10130. }
  10131. return id;
  10132. }
  10133. /**
  10134. * A fallback implementation of cancelVideoFrameCallback
  10135. *
  10136. * @param {number} id id of callback to be cancelled
  10137. */
  10138. ;
  10139. _proto.cancelVideoFrameCallback = function cancelVideoFrameCallback(id) {
  10140. if (this.queuedHanders_.has(id)) {
  10141. this.queuedHanders_["delete"](id);
  10142. } else {
  10143. this.cancelNamedAnimationFrame(id);
  10144. }
  10145. }
  10146. /**
  10147. * A method to set a poster from a `Tech`.
  10148. *
  10149. * @abstract
  10150. */
  10151. ;
  10152. _proto.setPoster = function setPoster() {}
  10153. /**
  10154. * A method to check for the presence of the 'playsinline' <video> attribute.
  10155. *
  10156. * @abstract
  10157. */
  10158. ;
  10159. _proto.playsinline = function playsinline() {}
  10160. /**
  10161. * A method to set or unset the 'playsinline' <video> attribute.
  10162. *
  10163. * @abstract
  10164. */
  10165. ;
  10166. _proto.setPlaysinline = function setPlaysinline() {}
  10167. /**
  10168. * Attempt to force override of native audio tracks.
  10169. *
  10170. * @param {boolean} override - If set to true native audio will be overridden,
  10171. * otherwise native audio will potentially be used.
  10172. *
  10173. * @abstract
  10174. */
  10175. ;
  10176. _proto.overrideNativeAudioTracks = function overrideNativeAudioTracks() {}
  10177. /**
  10178. * Attempt to force override of native video tracks.
  10179. *
  10180. * @param {boolean} override - If set to true native video will be overridden,
  10181. * otherwise native video will potentially be used.
  10182. *
  10183. * @abstract
  10184. */
  10185. ;
  10186. _proto.overrideNativeVideoTracks = function overrideNativeVideoTracks() {}
  10187. /*
  10188. * Check if the tech can support the given mime-type.
  10189. *
  10190. * The base tech does not support any type, but source handlers might
  10191. * overwrite this.
  10192. *
  10193. * @param {string} type
  10194. * The mimetype to check for support
  10195. *
  10196. * @return {string}
  10197. * 'probably', 'maybe', or empty string
  10198. *
  10199. * @see [Spec]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType}
  10200. *
  10201. * @abstract
  10202. */
  10203. ;
  10204. _proto.canPlayType = function canPlayType() {
  10205. return '';
  10206. }
  10207. /**
  10208. * Check if the type is supported by this tech.
  10209. *
  10210. * The base tech does not support any type, but source handlers might
  10211. * overwrite this.
  10212. *
  10213. * @param {string} type
  10214. * The media type to check
  10215. * @return {string} Returns the native video element's response
  10216. */
  10217. ;
  10218. Tech.canPlayType = function canPlayType() {
  10219. return '';
  10220. }
  10221. /**
  10222. * Check if the tech can support the given source
  10223. *
  10224. * @param {Object} srcObj
  10225. * The source object
  10226. * @param {Object} options
  10227. * The options passed to the tech
  10228. * @return {string} 'probably', 'maybe', or '' (empty string)
  10229. */
  10230. ;
  10231. Tech.canPlaySource = function canPlaySource(srcObj, options) {
  10232. return Tech.canPlayType(srcObj.type);
  10233. }
  10234. /*
  10235. * Return whether the argument is a Tech or not.
  10236. * Can be passed either a Class like `Html5` or a instance like `player.tech_`
  10237. *
  10238. * @param {Object} component
  10239. * The item to check
  10240. *
  10241. * @return {boolean}
  10242. * Whether it is a tech or not
  10243. * - True if it is a tech
  10244. * - False if it is not
  10245. */
  10246. ;
  10247. Tech.isTech = function isTech(component) {
  10248. return component.prototype instanceof Tech || component instanceof Tech || component === Tech;
  10249. }
  10250. /**
  10251. * Registers a `Tech` into a shared list for videojs.
  10252. *
  10253. * @param {string} name
  10254. * Name of the `Tech` to register.
  10255. *
  10256. * @param {Object} tech
  10257. * The `Tech` class to register.
  10258. */
  10259. ;
  10260. Tech.registerTech = function registerTech(name, tech) {
  10261. if (!Tech.techs_) {
  10262. Tech.techs_ = {};
  10263. }
  10264. if (!Tech.isTech(tech)) {
  10265. throw new Error("Tech " + name + " must be a Tech");
  10266. }
  10267. if (!Tech.canPlayType) {
  10268. throw new Error('Techs must have a static canPlayType method on them');
  10269. }
  10270. if (!Tech.canPlaySource) {
  10271. throw new Error('Techs must have a static canPlaySource method on them');
  10272. }
  10273. name = toTitleCase$1(name);
  10274. Tech.techs_[name] = tech;
  10275. Tech.techs_[toLowerCase(name)] = tech;
  10276. if (name !== 'Tech') {
  10277. // camel case the techName for use in techOrder
  10278. Tech.defaultTechOrder_.push(name);
  10279. }
  10280. return tech;
  10281. }
  10282. /**
  10283. * Get a `Tech` from the shared list by name.
  10284. *
  10285. * @param {string} name
  10286. * `camelCase` or `TitleCase` name of the Tech to get
  10287. *
  10288. * @return {Tech|undefined}
  10289. * The `Tech` or undefined if there was no tech with the name requested.
  10290. */
  10291. ;
  10292. Tech.getTech = function getTech(name) {
  10293. if (!name) {
  10294. return;
  10295. }
  10296. if (Tech.techs_ && Tech.techs_[name]) {
  10297. return Tech.techs_[name];
  10298. }
  10299. name = toTitleCase$1(name);
  10300. if (window && window.videojs && window.videojs[name]) {
  10301. log$1.warn("The " + name + " tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)");
  10302. return window.videojs[name];
  10303. }
  10304. };
  10305. return Tech;
  10306. }(Component$1);
  10307. /**
  10308. * Get the {@link VideoTrackList}
  10309. *
  10310. * @returns {VideoTrackList}
  10311. * @method Tech.prototype.videoTracks
  10312. */
  10313. /**
  10314. * Get the {@link AudioTrackList}
  10315. *
  10316. * @returns {AudioTrackList}
  10317. * @method Tech.prototype.audioTracks
  10318. */
  10319. /**
  10320. * Get the {@link TextTrackList}
  10321. *
  10322. * @returns {TextTrackList}
  10323. * @method Tech.prototype.textTracks
  10324. */
  10325. /**
  10326. * Get the remote element {@link TextTrackList}
  10327. *
  10328. * @returns {TextTrackList}
  10329. * @method Tech.prototype.remoteTextTracks
  10330. */
  10331. /**
  10332. * Get the remote element {@link HtmlTrackElementList}
  10333. *
  10334. * @returns {HtmlTrackElementList}
  10335. * @method Tech.prototype.remoteTextTrackEls
  10336. */
  10337. ALL.names.forEach(function (name) {
  10338. var props = ALL[name];
  10339. Tech.prototype[props.getterName] = function () {
  10340. this[props.privateName] = this[props.privateName] || new props.ListClass();
  10341. return this[props.privateName];
  10342. };
  10343. });
  10344. /**
  10345. * List of associated text tracks
  10346. *
  10347. * @type {TextTrackList}
  10348. * @private
  10349. * @property Tech#textTracks_
  10350. */
  10351. /**
  10352. * List of associated audio tracks.
  10353. *
  10354. * @type {AudioTrackList}
  10355. * @private
  10356. * @property Tech#audioTracks_
  10357. */
  10358. /**
  10359. * List of associated video tracks.
  10360. *
  10361. * @type {VideoTrackList}
  10362. * @private
  10363. * @property Tech#videoTracks_
  10364. */
  10365. /**
  10366. * Boolean indicating whether the `Tech` supports volume control.
  10367. *
  10368. * @type {boolean}
  10369. * @default
  10370. */
  10371. Tech.prototype.featuresVolumeControl = true;
  10372. /**
  10373. * Boolean indicating whether the `Tech` supports muting volume.
  10374. *
  10375. * @type {bolean}
  10376. * @default
  10377. */
  10378. Tech.prototype.featuresMuteControl = true;
  10379. /**
  10380. * Boolean indicating whether the `Tech` supports fullscreen resize control.
  10381. * Resizing plugins using request fullscreen reloads the plugin
  10382. *
  10383. * @type {boolean}
  10384. * @default
  10385. */
  10386. Tech.prototype.featuresFullscreenResize = false;
  10387. /**
  10388. * Boolean indicating whether the `Tech` supports changing the speed at which the video
  10389. * plays. Examples:
  10390. * - Set player to play 2x (twice) as fast
  10391. * - Set player to play 0.5x (half) as fast
  10392. *
  10393. * @type {boolean}
  10394. * @default
  10395. */
  10396. Tech.prototype.featuresPlaybackRate = false;
  10397. /**
  10398. * Boolean indicating whether the `Tech` supports the `progress` event. This is currently
  10399. * not triggered by video-js-swf. This will be used to determine if
  10400. * {@link Tech#manualProgressOn} should be called.
  10401. *
  10402. * @type {boolean}
  10403. * @default
  10404. */
  10405. Tech.prototype.featuresProgressEvents = false;
  10406. /**
  10407. * Boolean indicating whether the `Tech` supports the `sourceset` event.
  10408. *
  10409. * A tech should set this to `true` and then use {@link Tech#triggerSourceset}
  10410. * to trigger a {@link Tech#event:sourceset} at the earliest time after getting
  10411. * a new source.
  10412. *
  10413. * @type {boolean}
  10414. * @default
  10415. */
  10416. Tech.prototype.featuresSourceset = false;
  10417. /**
  10418. * Boolean indicating whether the `Tech` supports the `timeupdate` event. This is currently
  10419. * not triggered by video-js-swf. This will be used to determine if
  10420. * {@link Tech#manualTimeUpdates} should be called.
  10421. *
  10422. * @type {boolean}
  10423. * @default
  10424. */
  10425. Tech.prototype.featuresTimeupdateEvents = false;
  10426. /**
  10427. * Boolean indicating whether the `Tech` supports the native `TextTrack`s.
  10428. * This will help us integrate with native `TextTrack`s if the browser supports them.
  10429. *
  10430. * @type {boolean}
  10431. * @default
  10432. */
  10433. Tech.prototype.featuresNativeTextTracks = false;
  10434. /**
  10435. * Boolean indicating whether the `Tech` supports `requestVideoFrameCallback`.
  10436. *
  10437. * @type {boolean}
  10438. * @default
  10439. */
  10440. Tech.prototype.featuresVideoFrameCallback = false;
  10441. /**
  10442. * A functional mixin for techs that want to use the Source Handler pattern.
  10443. * Source handlers are scripts for handling specific formats.
  10444. * The source handler pattern is used for adaptive formats (HLS, DASH) that
  10445. * manually load video data and feed it into a Source Buffer (Media Source Extensions)
  10446. * Example: `Tech.withSourceHandlers.call(MyTech);`
  10447. *
  10448. * @param {Tech} _Tech
  10449. * The tech to add source handler functions to.
  10450. *
  10451. * @mixes Tech~SourceHandlerAdditions
  10452. */
  10453. Tech.withSourceHandlers = function (_Tech) {
  10454. /**
  10455. * Register a source handler
  10456. *
  10457. * @param {Function} handler
  10458. * The source handler class
  10459. *
  10460. * @param {number} [index]
  10461. * Register it at the following index
  10462. */
  10463. _Tech.registerSourceHandler = function (handler, index) {
  10464. var handlers = _Tech.sourceHandlers;
  10465. if (!handlers) {
  10466. handlers = _Tech.sourceHandlers = [];
  10467. }
  10468. if (index === undefined) {
  10469. // add to the end of the list
  10470. index = handlers.length;
  10471. }
  10472. handlers.splice(index, 0, handler);
  10473. };
  10474. /**
  10475. * Check if the tech can support the given type. Also checks the
  10476. * Techs sourceHandlers.
  10477. *
  10478. * @param {string} type
  10479. * The mimetype to check.
  10480. *
  10481. * @return {string}
  10482. * 'probably', 'maybe', or '' (empty string)
  10483. */
  10484. _Tech.canPlayType = function (type) {
  10485. var handlers = _Tech.sourceHandlers || [];
  10486. var can;
  10487. for (var i = 0; i < handlers.length; i++) {
  10488. can = handlers[i].canPlayType(type);
  10489. if (can) {
  10490. return can;
  10491. }
  10492. }
  10493. return '';
  10494. };
  10495. /**
  10496. * Returns the first source handler that supports the source.
  10497. *
  10498. * TODO: Answer question: should 'probably' be prioritized over 'maybe'
  10499. *
  10500. * @param {Tech~SourceObject} source
  10501. * The source object
  10502. *
  10503. * @param {Object} options
  10504. * The options passed to the tech
  10505. *
  10506. * @return {SourceHandler|null}
  10507. * The first source handler that supports the source or null if
  10508. * no SourceHandler supports the source
  10509. */
  10510. _Tech.selectSourceHandler = function (source, options) {
  10511. var handlers = _Tech.sourceHandlers || [];
  10512. var can;
  10513. for (var i = 0; i < handlers.length; i++) {
  10514. can = handlers[i].canHandleSource(source, options);
  10515. if (can) {
  10516. return handlers[i];
  10517. }
  10518. }
  10519. return null;
  10520. };
  10521. /**
  10522. * Check if the tech can support the given source.
  10523. *
  10524. * @param {Tech~SourceObject} srcObj
  10525. * The source object
  10526. *
  10527. * @param {Object} options
  10528. * The options passed to the tech
  10529. *
  10530. * @return {string}
  10531. * 'probably', 'maybe', or '' (empty string)
  10532. */
  10533. _Tech.canPlaySource = function (srcObj, options) {
  10534. var sh = _Tech.selectSourceHandler(srcObj, options);
  10535. if (sh) {
  10536. return sh.canHandleSource(srcObj, options);
  10537. }
  10538. return '';
  10539. };
  10540. /**
  10541. * When using a source handler, prefer its implementation of
  10542. * any function normally provided by the tech.
  10543. */
  10544. var deferrable = ['seekable', 'seeking', 'duration'];
  10545. /**
  10546. * A wrapper around {@link Tech#seekable} that will call a `SourceHandler`s seekable
  10547. * function if it exists, with a fallback to the Techs seekable function.
  10548. *
  10549. * @method _Tech.seekable
  10550. */
  10551. /**
  10552. * A wrapper around {@link Tech#duration} that will call a `SourceHandler`s duration
  10553. * function if it exists, otherwise it will fallback to the techs duration function.
  10554. *
  10555. * @method _Tech.duration
  10556. */
  10557. deferrable.forEach(function (fnName) {
  10558. var originalFn = this[fnName];
  10559. if (typeof originalFn !== 'function') {
  10560. return;
  10561. }
  10562. this[fnName] = function () {
  10563. if (this.sourceHandler_ && this.sourceHandler_[fnName]) {
  10564. return this.sourceHandler_[fnName].apply(this.sourceHandler_, arguments);
  10565. }
  10566. return originalFn.apply(this, arguments);
  10567. };
  10568. }, _Tech.prototype);
  10569. /**
  10570. * Create a function for setting the source using a source object
  10571. * and source handlers.
  10572. * Should never be called unless a source handler was found.
  10573. *
  10574. * @param {Tech~SourceObject} source
  10575. * A source object with src and type keys
  10576. */
  10577. _Tech.prototype.setSource = function (source) {
  10578. var sh = _Tech.selectSourceHandler(source, this.options_);
  10579. if (!sh) {
  10580. // Fall back to a native source hander when unsupported sources are
  10581. // deliberately set
  10582. if (_Tech.nativeSourceHandler) {
  10583. sh = _Tech.nativeSourceHandler;
  10584. } else {
  10585. log$1.error('No source handler found for the current source.');
  10586. }
  10587. } // Dispose any existing source handler
  10588. this.disposeSourceHandler();
  10589. this.off('dispose', this.disposeSourceHandler_);
  10590. if (sh !== _Tech.nativeSourceHandler) {
  10591. this.currentSource_ = source;
  10592. }
  10593. this.sourceHandler_ = sh.handleSource(source, this, this.options_);
  10594. this.one('dispose', this.disposeSourceHandler_);
  10595. };
  10596. /**
  10597. * Clean up any existing SourceHandlers and listeners when the Tech is disposed.
  10598. *
  10599. * @listens Tech#dispose
  10600. */
  10601. _Tech.prototype.disposeSourceHandler = function () {
  10602. // if we have a source and get another one
  10603. // then we are loading something new
  10604. // than clear all of our current tracks
  10605. if (this.currentSource_) {
  10606. this.clearTracks(['audio', 'video']);
  10607. this.currentSource_ = null;
  10608. } // always clean up auto-text tracks
  10609. this.cleanupAutoTextTracks();
  10610. if (this.sourceHandler_) {
  10611. if (this.sourceHandler_.dispose) {
  10612. this.sourceHandler_.dispose();
  10613. }
  10614. this.sourceHandler_ = null;
  10615. }
  10616. };
  10617. }; // The base Tech class needs to be registered as a Component. It is the only
  10618. // Tech that can be registered as a Component.
  10619. Component$1.registerComponent('Tech', Tech);
  10620. Tech.registerTech('Tech', Tech);
  10621. /**
  10622. * A list of techs that should be added to techOrder on Players
  10623. *
  10624. * @private
  10625. */
  10626. Tech.defaultTechOrder_ = [];
  10627. /**
  10628. * @file middleware.js
  10629. * @module middleware
  10630. */
  10631. var middlewares = {};
  10632. var middlewareInstances = {};
  10633. var TERMINATOR = {};
  10634. /**
  10635. * A middleware object is a plain JavaScript object that has methods that
  10636. * match the {@link Tech} methods found in the lists of allowed
  10637. * {@link module:middleware.allowedGetters|getters},
  10638. * {@link module:middleware.allowedSetters|setters}, and
  10639. * {@link module:middleware.allowedMediators|mediators}.
  10640. *
  10641. * @typedef {Object} MiddlewareObject
  10642. */
  10643. /**
  10644. * A middleware factory function that should return a
  10645. * {@link module:middleware~MiddlewareObject|MiddlewareObject}.
  10646. *
  10647. * This factory will be called for each player when needed, with the player
  10648. * passed in as an argument.
  10649. *
  10650. * @callback MiddlewareFactory
  10651. * @param {Player} player
  10652. * A Video.js player.
  10653. */
  10654. /**
  10655. * Define a middleware that the player should use by way of a factory function
  10656. * that returns a middleware object.
  10657. *
  10658. * @param {string} type
  10659. * The MIME type to match or `"*"` for all MIME types.
  10660. *
  10661. * @param {MiddlewareFactory} middleware
  10662. * A middleware factory function that will be executed for
  10663. * matching types.
  10664. */
  10665. function use(type, middleware) {
  10666. middlewares[type] = middlewares[type] || [];
  10667. middlewares[type].push(middleware);
  10668. }
  10669. /**
  10670. * Asynchronously sets a source using middleware by recursing through any
  10671. * matching middlewares and calling `setSource` on each, passing along the
  10672. * previous returned value each time.
  10673. *
  10674. * @param {Player} player
  10675. * A {@link Player} instance.
  10676. *
  10677. * @param {Tech~SourceObject} src
  10678. * A source object.
  10679. *
  10680. * @param {Function}
  10681. * The next middleware to run.
  10682. */
  10683. function setSource(player, src, next) {
  10684. player.setTimeout(function () {
  10685. return setSourceHelper(src, middlewares[src.type], next, player);
  10686. }, 1);
  10687. }
  10688. /**
  10689. * When the tech is set, passes the tech to each middleware's `setTech` method.
  10690. *
  10691. * @param {Object[]} middleware
  10692. * An array of middleware instances.
  10693. *
  10694. * @param {Tech} tech
  10695. * A Video.js tech.
  10696. */
  10697. function setTech(middleware, tech) {
  10698. middleware.forEach(function (mw) {
  10699. return mw.setTech && mw.setTech(tech);
  10700. });
  10701. }
  10702. /**
  10703. * Calls a getter on the tech first, through each middleware
  10704. * from right to left to the player.
  10705. *
  10706. * @param {Object[]} middleware
  10707. * An array of middleware instances.
  10708. *
  10709. * @param {Tech} tech
  10710. * The current tech.
  10711. *
  10712. * @param {string} method
  10713. * A method name.
  10714. *
  10715. * @return {Mixed}
  10716. * The final value from the tech after middleware has intercepted it.
  10717. */
  10718. function get(middleware, tech, method) {
  10719. return middleware.reduceRight(middlewareIterator(method), tech[method]());
  10720. }
  10721. /**
  10722. * Takes the argument given to the player and calls the setter method on each
  10723. * middleware from left to right to the tech.
  10724. *
  10725. * @param {Object[]} middleware
  10726. * An array of middleware instances.
  10727. *
  10728. * @param {Tech} tech
  10729. * The current tech.
  10730. *
  10731. * @param {string} method
  10732. * A method name.
  10733. *
  10734. * @param {Mixed} arg
  10735. * The value to set on the tech.
  10736. *
  10737. * @return {Mixed}
  10738. * The return value of the `method` of the `tech`.
  10739. */
  10740. function set(middleware, tech, method, arg) {
  10741. return tech[method](middleware.reduce(middlewareIterator(method), arg));
  10742. }
  10743. /**
  10744. * Takes the argument given to the player and calls the `call` version of the
  10745. * method on each middleware from left to right.
  10746. *
  10747. * Then, call the passed in method on the tech and return the result unchanged
  10748. * back to the player, through middleware, this time from right to left.
  10749. *
  10750. * @param {Object[]} middleware
  10751. * An array of middleware instances.
  10752. *
  10753. * @param {Tech} tech
  10754. * The current tech.
  10755. *
  10756. * @param {string} method
  10757. * A method name.
  10758. *
  10759. * @param {Mixed} arg
  10760. * The value to set on the tech.
  10761. *
  10762. * @return {Mixed}
  10763. * The return value of the `method` of the `tech`, regardless of the
  10764. * return values of middlewares.
  10765. */
  10766. function mediate(middleware, tech, method, arg) {
  10767. if (arg === void 0) {
  10768. arg = null;
  10769. }
  10770. var callMethod = 'call' + toTitleCase$1(method);
  10771. var middlewareValue = middleware.reduce(middlewareIterator(callMethod), arg);
  10772. var terminated = middlewareValue === TERMINATOR; // deprecated. The `null` return value should instead return TERMINATOR to
  10773. // prevent confusion if a techs method actually returns null.
  10774. var returnValue = terminated ? null : tech[method](middlewareValue);
  10775. executeRight(middleware, method, returnValue, terminated);
  10776. return returnValue;
  10777. }
  10778. /**
  10779. * Enumeration of allowed getters where the keys are method names.
  10780. *
  10781. * @type {Object}
  10782. */
  10783. var allowedGetters = {
  10784. buffered: 1,
  10785. currentTime: 1,
  10786. duration: 1,
  10787. muted: 1,
  10788. played: 1,
  10789. paused: 1,
  10790. seekable: 1,
  10791. volume: 1,
  10792. ended: 1
  10793. };
  10794. /**
  10795. * Enumeration of allowed setters where the keys are method names.
  10796. *
  10797. * @type {Object}
  10798. */
  10799. var allowedSetters = {
  10800. setCurrentTime: 1,
  10801. setMuted: 1,
  10802. setVolume: 1
  10803. };
  10804. /**
  10805. * Enumeration of allowed mediators where the keys are method names.
  10806. *
  10807. * @type {Object}
  10808. */
  10809. var allowedMediators = {
  10810. play: 1,
  10811. pause: 1
  10812. };
  10813. function middlewareIterator(method) {
  10814. return function (value, mw) {
  10815. // if the previous middleware terminated, pass along the termination
  10816. if (value === TERMINATOR) {
  10817. return TERMINATOR;
  10818. }
  10819. if (mw[method]) {
  10820. return mw[method](value);
  10821. }
  10822. return value;
  10823. };
  10824. }
  10825. function executeRight(mws, method, value, terminated) {
  10826. for (var i = mws.length - 1; i >= 0; i--) {
  10827. var mw = mws[i];
  10828. if (mw[method]) {
  10829. mw[method](terminated, value);
  10830. }
  10831. }
  10832. }
  10833. /**
  10834. * Clear the middleware cache for a player.
  10835. *
  10836. * @param {Player} player
  10837. * A {@link Player} instance.
  10838. */
  10839. function clearCacheForPlayer(player) {
  10840. middlewareInstances[player.id()] = null;
  10841. }
  10842. /**
  10843. * {
  10844. * [playerId]: [[mwFactory, mwInstance], ...]
  10845. * }
  10846. *
  10847. * @private
  10848. */
  10849. function getOrCreateFactory(player, mwFactory) {
  10850. var mws = middlewareInstances[player.id()];
  10851. var mw = null;
  10852. if (mws === undefined || mws === null) {
  10853. mw = mwFactory(player);
  10854. middlewareInstances[player.id()] = [[mwFactory, mw]];
  10855. return mw;
  10856. }
  10857. for (var i = 0; i < mws.length; i++) {
  10858. var _mws$i = mws[i],
  10859. mwf = _mws$i[0],
  10860. mwi = _mws$i[1];
  10861. if (mwf !== mwFactory) {
  10862. continue;
  10863. }
  10864. mw = mwi;
  10865. }
  10866. if (mw === null) {
  10867. mw = mwFactory(player);
  10868. mws.push([mwFactory, mw]);
  10869. }
  10870. return mw;
  10871. }
  10872. function setSourceHelper(src, middleware, next, player, acc, lastRun) {
  10873. if (src === void 0) {
  10874. src = {};
  10875. }
  10876. if (middleware === void 0) {
  10877. middleware = [];
  10878. }
  10879. if (acc === void 0) {
  10880. acc = [];
  10881. }
  10882. if (lastRun === void 0) {
  10883. lastRun = false;
  10884. }
  10885. var _middleware = middleware,
  10886. mwFactory = _middleware[0],
  10887. mwrest = _middleware.slice(1); // if mwFactory is a string, then we're at a fork in the road
  10888. if (typeof mwFactory === 'string') {
  10889. setSourceHelper(src, middlewares[mwFactory], next, player, acc, lastRun); // if we have an mwFactory, call it with the player to get the mw,
  10890. // then call the mw's setSource method
  10891. } else if (mwFactory) {
  10892. var mw = getOrCreateFactory(player, mwFactory); // if setSource isn't present, implicitly select this middleware
  10893. if (!mw.setSource) {
  10894. acc.push(mw);
  10895. return setSourceHelper(src, mwrest, next, player, acc, lastRun);
  10896. }
  10897. mw.setSource(assign$1({}, src), function (err, _src) {
  10898. // something happened, try the next middleware on the current level
  10899. // make sure to use the old src
  10900. if (err) {
  10901. return setSourceHelper(src, mwrest, next, player, acc, lastRun);
  10902. } // we've succeeded, now we need to go deeper
  10903. acc.push(mw); // if it's the same type, continue down the current chain
  10904. // otherwise, we want to go down the new chain
  10905. setSourceHelper(_src, src.type === _src.type ? mwrest : middlewares[_src.type], next, player, acc, lastRun);
  10906. });
  10907. } else if (mwrest.length) {
  10908. setSourceHelper(src, mwrest, next, player, acc, lastRun);
  10909. } else if (lastRun) {
  10910. next(src, acc);
  10911. } else {
  10912. setSourceHelper(src, middlewares['*'], next, player, acc, true);
  10913. }
  10914. }
  10915. /**
  10916. * Mimetypes
  10917. *
  10918. * @see https://www.iana.org/assignments/media-types/media-types.xhtml
  10919. * @typedef Mimetypes~Kind
  10920. * @enum
  10921. */
  10922. var MimetypesKind = {
  10923. opus: 'video/ogg',
  10924. ogv: 'video/ogg',
  10925. mp4: 'video/mp4',
  10926. mov: 'video/mp4',
  10927. m4v: 'video/mp4',
  10928. mkv: 'video/x-matroska',
  10929. m4a: 'audio/mp4',
  10930. mp3: 'audio/mpeg',
  10931. aac: 'audio/aac',
  10932. caf: 'audio/x-caf',
  10933. flac: 'audio/flac',
  10934. oga: 'audio/ogg',
  10935. wav: 'audio/wav',
  10936. m3u8: 'application/x-mpegURL',
  10937. mpd: 'application/dash+xml',
  10938. jpg: 'image/jpeg',
  10939. jpeg: 'image/jpeg',
  10940. gif: 'image/gif',
  10941. png: 'image/png',
  10942. svg: 'image/svg+xml',
  10943. webp: 'image/webp'
  10944. };
  10945. /**
  10946. * Get the mimetype of a given src url if possible
  10947. *
  10948. * @param {string} src
  10949. * The url to the src
  10950. *
  10951. * @return {string}
  10952. * return the mimetype if it was known or empty string otherwise
  10953. */
  10954. var getMimetype = function getMimetype(src) {
  10955. if (src === void 0) {
  10956. src = '';
  10957. }
  10958. var ext = getFileExtension(src);
  10959. var mimetype = MimetypesKind[ext.toLowerCase()];
  10960. return mimetype || '';
  10961. };
  10962. /**
  10963. * Find the mime type of a given source string if possible. Uses the player
  10964. * source cache.
  10965. *
  10966. * @param {Player} player
  10967. * The player object
  10968. *
  10969. * @param {string} src
  10970. * The source string
  10971. *
  10972. * @return {string}
  10973. * The type that was found
  10974. */
  10975. var findMimetype = function findMimetype(player, src) {
  10976. if (!src) {
  10977. return '';
  10978. } // 1. check for the type in the `source` cache
  10979. if (player.cache_.source.src === src && player.cache_.source.type) {
  10980. return player.cache_.source.type;
  10981. } // 2. see if we have this source in our `currentSources` cache
  10982. var matchingSources = player.cache_.sources.filter(function (s) {
  10983. return s.src === src;
  10984. });
  10985. if (matchingSources.length) {
  10986. return matchingSources[0].type;
  10987. } // 3. look for the src url in source elements and use the type there
  10988. var sources = player.$$('source');
  10989. for (var i = 0; i < sources.length; i++) {
  10990. var s = sources[i];
  10991. if (s.type && s.src && s.src === src) {
  10992. return s.type;
  10993. }
  10994. } // 4. finally fallback to our list of mime types based on src url extension
  10995. return getMimetype(src);
  10996. };
  10997. /**
  10998. * @module filter-source
  10999. */
  11000. /**
  11001. * Filter out single bad source objects or multiple source objects in an
  11002. * array. Also flattens nested source object arrays into a 1 dimensional
  11003. * array of source objects.
  11004. *
  11005. * @param {Tech~SourceObject|Tech~SourceObject[]} src
  11006. * The src object to filter
  11007. *
  11008. * @return {Tech~SourceObject[]}
  11009. * An array of sourceobjects containing only valid sources
  11010. *
  11011. * @private
  11012. */
  11013. var filterSource = function filterSource(src) {
  11014. // traverse array
  11015. if (Array.isArray(src)) {
  11016. var newsrc = [];
  11017. src.forEach(function (srcobj) {
  11018. srcobj = filterSource(srcobj);
  11019. if (Array.isArray(srcobj)) {
  11020. newsrc = newsrc.concat(srcobj);
  11021. } else if (isObject$1(srcobj)) {
  11022. newsrc.push(srcobj);
  11023. }
  11024. });
  11025. src = newsrc;
  11026. } else if (typeof src === 'string' && src.trim()) {
  11027. // convert string into object
  11028. src = [fixSource({
  11029. src: src
  11030. })];
  11031. } else if (isObject$1(src) && typeof src.src === 'string' && src.src && src.src.trim()) {
  11032. // src is already valid
  11033. src = [fixSource(src)];
  11034. } else {
  11035. // invalid source, turn it into an empty array
  11036. src = [];
  11037. }
  11038. return src;
  11039. };
  11040. /**
  11041. * Checks src mimetype, adding it when possible
  11042. *
  11043. * @param {Tech~SourceObject} src
  11044. * The src object to check
  11045. * @return {Tech~SourceObject}
  11046. * src Object with known type
  11047. */
  11048. function fixSource(src) {
  11049. if (!src.type) {
  11050. var mimetype = getMimetype(src.src);
  11051. if (mimetype) {
  11052. src.type = mimetype;
  11053. }
  11054. }
  11055. return src;
  11056. }
  11057. /**
  11058. * The `MediaLoader` is the `Component` that decides which playback technology to load
  11059. * when a player is initialized.
  11060. *
  11061. * @extends Component
  11062. */
  11063. var MediaLoader = /*#__PURE__*/function (_Component) {
  11064. inheritsLoose(MediaLoader, _Component);
  11065. /**
  11066. * Create an instance of this class.
  11067. *
  11068. * @param {Player} player
  11069. * The `Player` that this class should attach to.
  11070. *
  11071. * @param {Object} [options]
  11072. * The key/value store of player options.
  11073. *
  11074. * @param {Component~ReadyCallback} [ready]
  11075. * The function that is run when this component is ready.
  11076. */
  11077. function MediaLoader(player, options, ready) {
  11078. var _this;
  11079. // MediaLoader has no element
  11080. var options_ = mergeOptions$3({
  11081. createEl: false
  11082. }, options);
  11083. _this = _Component.call(this, player, options_, ready) || this; // If there are no sources when the player is initialized,
  11084. // load the first supported playback technology.
  11085. if (!options.playerOptions.sources || options.playerOptions.sources.length === 0) {
  11086. for (var i = 0, j = options.playerOptions.techOrder; i < j.length; i++) {
  11087. var techName = toTitleCase$1(j[i]);
  11088. var tech = Tech.getTech(techName); // Support old behavior of techs being registered as components.
  11089. // Remove once that deprecated behavior is removed.
  11090. if (!techName) {
  11091. tech = Component$1.getComponent(techName);
  11092. } // Check if the browser supports this technology
  11093. if (tech && tech.isSupported()) {
  11094. player.loadTech_(techName);
  11095. break;
  11096. }
  11097. }
  11098. } else {
  11099. // Loop through playback technologies (e.g. HTML5) and check for support.
  11100. // Then load the best source.
  11101. // A few assumptions here:
  11102. // All playback technologies respect preload false.
  11103. player.src(options.playerOptions.sources);
  11104. }
  11105. return _this;
  11106. }
  11107. return MediaLoader;
  11108. }(Component$1);
  11109. Component$1.registerComponent('MediaLoader', MediaLoader);
  11110. /**
  11111. * Component which is clickable or keyboard actionable, but is not a
  11112. * native HTML button.
  11113. *
  11114. * @extends Component
  11115. */
  11116. var ClickableComponent = /*#__PURE__*/function (_Component) {
  11117. inheritsLoose(ClickableComponent, _Component);
  11118. /**
  11119. * Creates an instance of this class.
  11120. *
  11121. * @param {Player} player
  11122. * The `Player` that this class should be attached to.
  11123. *
  11124. * @param {Object} [options]
  11125. * The key/value store of component options.
  11126. *
  11127. * @param {function} [options.clickHandler]
  11128. * The function to call when the button is clicked / activated
  11129. *
  11130. * @param {string} [options.controlText]
  11131. * The text to set on the button
  11132. *
  11133. * @param {string} [options.className]
  11134. * A class or space separated list of classes to add the component
  11135. *
  11136. */
  11137. function ClickableComponent(player, options) {
  11138. var _this;
  11139. _this = _Component.call(this, player, options) || this;
  11140. if (_this.options_.controlText) {
  11141. _this.controlText(_this.options_.controlText);
  11142. }
  11143. _this.handleMouseOver_ = function (e) {
  11144. return _this.handleMouseOver(e);
  11145. };
  11146. _this.handleMouseOut_ = function (e) {
  11147. return _this.handleMouseOut(e);
  11148. };
  11149. _this.handleClick_ = function (e) {
  11150. return _this.handleClick(e);
  11151. };
  11152. _this.handleKeyDown_ = function (e) {
  11153. return _this.handleKeyDown(e);
  11154. };
  11155. _this.emitTapEvents();
  11156. _this.enable();
  11157. return _this;
  11158. }
  11159. /**
  11160. * Create the `ClickableComponent`s DOM element.
  11161. *
  11162. * @param {string} [tag=div]
  11163. * The element's node type.
  11164. *
  11165. * @param {Object} [props={}]
  11166. * An object of properties that should be set on the element.
  11167. *
  11168. * @param {Object} [attributes={}]
  11169. * An object of attributes that should be set on the element.
  11170. *
  11171. * @return {Element}
  11172. * The element that gets created.
  11173. */
  11174. var _proto = ClickableComponent.prototype;
  11175. _proto.createEl = function createEl$1(tag, props, attributes) {
  11176. if (tag === void 0) {
  11177. tag = 'div';
  11178. }
  11179. if (props === void 0) {
  11180. props = {};
  11181. }
  11182. if (attributes === void 0) {
  11183. attributes = {};
  11184. }
  11185. props = assign$1({
  11186. className: this.buildCSSClass(),
  11187. tabIndex: 0
  11188. }, props);
  11189. if (tag === 'button') {
  11190. log$1.error("Creating a ClickableComponent with an HTML element of " + tag + " is not supported; use a Button instead.");
  11191. } // Add ARIA attributes for clickable element which is not a native HTML button
  11192. attributes = assign$1({
  11193. role: 'button'
  11194. }, attributes);
  11195. this.tabIndex_ = props.tabIndex;
  11196. var el = createEl(tag, props, attributes);
  11197. el.appendChild(createEl('span', {
  11198. className: 'vjs-icon-placeholder'
  11199. }, {
  11200. 'aria-hidden': true
  11201. }));
  11202. this.createControlTextEl(el);
  11203. return el;
  11204. };
  11205. _proto.dispose = function dispose() {
  11206. // remove controlTextEl_ on dispose
  11207. this.controlTextEl_ = null;
  11208. _Component.prototype.dispose.call(this);
  11209. }
  11210. /**
  11211. * Create a control text element on this `ClickableComponent`
  11212. *
  11213. * @param {Element} [el]
  11214. * Parent element for the control text.
  11215. *
  11216. * @return {Element}
  11217. * The control text element that gets created.
  11218. */
  11219. ;
  11220. _proto.createControlTextEl = function createControlTextEl(el) {
  11221. this.controlTextEl_ = createEl('span', {
  11222. className: 'vjs-control-text'
  11223. }, {
  11224. // let the screen reader user know that the text of the element may change
  11225. 'aria-live': 'polite'
  11226. });
  11227. if (el) {
  11228. el.appendChild(this.controlTextEl_);
  11229. }
  11230. this.controlText(this.controlText_, el);
  11231. return this.controlTextEl_;
  11232. }
  11233. /**
  11234. * Get or set the localize text to use for the controls on the `ClickableComponent`.
  11235. *
  11236. * @param {string} [text]
  11237. * Control text for element.
  11238. *
  11239. * @param {Element} [el=this.el()]
  11240. * Element to set the title on.
  11241. *
  11242. * @return {string}
  11243. * - The control text when getting
  11244. */
  11245. ;
  11246. _proto.controlText = function controlText(text, el) {
  11247. if (el === void 0) {
  11248. el = this.el();
  11249. }
  11250. if (text === undefined) {
  11251. return this.controlText_ || 'Need Text';
  11252. }
  11253. var localizedText = this.localize(text);
  11254. this.controlText_ = text;
  11255. textContent(this.controlTextEl_, localizedText);
  11256. if (!this.nonIconControl && !this.player_.options_.noUITitleAttributes) {
  11257. // Set title attribute if only an icon is shown
  11258. el.setAttribute('title', localizedText);
  11259. }
  11260. }
  11261. /**
  11262. * Builds the default DOM `className`.
  11263. *
  11264. * @return {string}
  11265. * The DOM `className` for this object.
  11266. */
  11267. ;
  11268. _proto.buildCSSClass = function buildCSSClass() {
  11269. return "vjs-control vjs-button " + _Component.prototype.buildCSSClass.call(this);
  11270. }
  11271. /**
  11272. * Enable this `ClickableComponent`
  11273. */
  11274. ;
  11275. _proto.enable = function enable() {
  11276. if (!this.enabled_) {
  11277. this.enabled_ = true;
  11278. this.removeClass('vjs-disabled');
  11279. this.el_.setAttribute('aria-disabled', 'false');
  11280. if (typeof this.tabIndex_ !== 'undefined') {
  11281. this.el_.setAttribute('tabIndex', this.tabIndex_);
  11282. }
  11283. this.on(['tap', 'click'], this.handleClick_);
  11284. this.on('keydown', this.handleKeyDown_);
  11285. }
  11286. }
  11287. /**
  11288. * Disable this `ClickableComponent`
  11289. */
  11290. ;
  11291. _proto.disable = function disable() {
  11292. this.enabled_ = false;
  11293. this.addClass('vjs-disabled');
  11294. this.el_.setAttribute('aria-disabled', 'true');
  11295. if (typeof this.tabIndex_ !== 'undefined') {
  11296. this.el_.removeAttribute('tabIndex');
  11297. }
  11298. this.off('mouseover', this.handleMouseOver_);
  11299. this.off('mouseout', this.handleMouseOut_);
  11300. this.off(['tap', 'click'], this.handleClick_);
  11301. this.off('keydown', this.handleKeyDown_);
  11302. }
  11303. /**
  11304. * Handles language change in ClickableComponent for the player in components
  11305. *
  11306. *
  11307. */
  11308. ;
  11309. _proto.handleLanguagechange = function handleLanguagechange() {
  11310. this.controlText(this.controlText_);
  11311. }
  11312. /**
  11313. * Event handler that is called when a `ClickableComponent` receives a
  11314. * `click` or `tap` event.
  11315. *
  11316. * @param {EventTarget~Event} event
  11317. * The `tap` or `click` event that caused this function to be called.
  11318. *
  11319. * @listens tap
  11320. * @listens click
  11321. * @abstract
  11322. */
  11323. ;
  11324. _proto.handleClick = function handleClick(event) {
  11325. if (this.options_.clickHandler) {
  11326. this.options_.clickHandler.call(this, arguments);
  11327. }
  11328. }
  11329. /**
  11330. * Event handler that is called when a `ClickableComponent` receives a
  11331. * `keydown` event.
  11332. *
  11333. * By default, if the key is Space or Enter, it will trigger a `click` event.
  11334. *
  11335. * @param {EventTarget~Event} event
  11336. * The `keydown` event that caused this function to be called.
  11337. *
  11338. * @listens keydown
  11339. */
  11340. ;
  11341. _proto.handleKeyDown = function handleKeyDown(event) {
  11342. // Support Space or Enter key operation to fire a click event. Also,
  11343. // prevent the event from propagating through the DOM and triggering
  11344. // Player hotkeys.
  11345. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) {
  11346. event.preventDefault();
  11347. event.stopPropagation();
  11348. this.trigger('click');
  11349. } else {
  11350. // Pass keypress handling up for unsupported keys
  11351. _Component.prototype.handleKeyDown.call(this, event);
  11352. }
  11353. };
  11354. return ClickableComponent;
  11355. }(Component$1);
  11356. Component$1.registerComponent('ClickableComponent', ClickableComponent);
  11357. /**
  11358. * A `ClickableComponent` that handles showing the poster image for the player.
  11359. *
  11360. * @extends ClickableComponent
  11361. */
  11362. var PosterImage = /*#__PURE__*/function (_ClickableComponent) {
  11363. inheritsLoose(PosterImage, _ClickableComponent);
  11364. /**
  11365. * Create an instance of this class.
  11366. *
  11367. * @param {Player} player
  11368. * The `Player` that this class should attach to.
  11369. *
  11370. * @param {Object} [options]
  11371. * The key/value store of player options.
  11372. */
  11373. function PosterImage(player, options) {
  11374. var _this;
  11375. _this = _ClickableComponent.call(this, player, options) || this;
  11376. _this.update();
  11377. _this.update_ = function (e) {
  11378. return _this.update(e);
  11379. };
  11380. player.on('posterchange', _this.update_);
  11381. return _this;
  11382. }
  11383. /**
  11384. * Clean up and dispose of the `PosterImage`.
  11385. */
  11386. var _proto = PosterImage.prototype;
  11387. _proto.dispose = function dispose() {
  11388. this.player().off('posterchange', this.update_);
  11389. _ClickableComponent.prototype.dispose.call(this);
  11390. }
  11391. /**
  11392. * Create the `PosterImage`s DOM element.
  11393. *
  11394. * @return {Element}
  11395. * The element that gets created.
  11396. */
  11397. ;
  11398. _proto.createEl = function createEl$1() {
  11399. var el = createEl('div', {
  11400. className: 'vjs-poster',
  11401. // Don't want poster to be tabbable.
  11402. tabIndex: -1
  11403. });
  11404. return el;
  11405. }
  11406. /**
  11407. * An {@link EventTarget~EventListener} for {@link Player#posterchange} events.
  11408. *
  11409. * @listens Player#posterchange
  11410. *
  11411. * @param {EventTarget~Event} [event]
  11412. * The `Player#posterchange` event that triggered this function.
  11413. */
  11414. ;
  11415. _proto.update = function update(event) {
  11416. var url = this.player().poster();
  11417. this.setSrc(url); // If there's no poster source we should display:none on this component
  11418. // so it's not still clickable or right-clickable
  11419. if (url) {
  11420. this.show();
  11421. } else {
  11422. this.hide();
  11423. }
  11424. }
  11425. /**
  11426. * Set the source of the `PosterImage` depending on the display method.
  11427. *
  11428. * @param {string} url
  11429. * The URL to the source for the `PosterImage`.
  11430. */
  11431. ;
  11432. _proto.setSrc = function setSrc(url) {
  11433. var backgroundImage = ''; // Any falsy value should stay as an empty string, otherwise
  11434. // this will throw an extra error
  11435. if (url) {
  11436. backgroundImage = "url(\"" + url + "\")";
  11437. }
  11438. this.el_.style.backgroundImage = backgroundImage;
  11439. }
  11440. /**
  11441. * An {@link EventTarget~EventListener} for clicks on the `PosterImage`. See
  11442. * {@link ClickableComponent#handleClick} for instances where this will be triggered.
  11443. *
  11444. * @listens tap
  11445. * @listens click
  11446. * @listens keydown
  11447. *
  11448. * @param {EventTarget~Event} event
  11449. + The `click`, `tap` or `keydown` event that caused this function to be called.
  11450. */
  11451. ;
  11452. _proto.handleClick = function handleClick(event) {
  11453. // We don't want a click to trigger playback when controls are disabled
  11454. if (!this.player_.controls()) {
  11455. return;
  11456. }
  11457. var sourceIsEncrypted = this.player_.usingPlugin('eme') && this.player_.eme.sessions && this.player_.eme.sessions.length > 0;
  11458. if (this.player_.tech(true) && // We've observed a bug in IE and Edge when playing back DRM content where
  11459. // calling .focus() on the video element causes the video to go black,
  11460. // so we avoid it in that specific case
  11461. !((IE_VERSION || IS_EDGE) && sourceIsEncrypted)) {
  11462. this.player_.tech(true).focus();
  11463. }
  11464. if (this.player_.paused()) {
  11465. silencePromise(this.player_.play());
  11466. } else {
  11467. this.player_.pause();
  11468. }
  11469. };
  11470. return PosterImage;
  11471. }(ClickableComponent);
  11472. Component$1.registerComponent('PosterImage', PosterImage);
  11473. var darkGray = '#222';
  11474. var lightGray = '#ccc';
  11475. var fontMap = {
  11476. monospace: 'monospace',
  11477. sansSerif: 'sans-serif',
  11478. serif: 'serif',
  11479. monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace',
  11480. monospaceSerif: '"Courier New", monospace',
  11481. proportionalSansSerif: 'sans-serif',
  11482. proportionalSerif: 'serif',
  11483. casual: '"Comic Sans MS", Impact, fantasy',
  11484. script: '"Monotype Corsiva", cursive',
  11485. smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif'
  11486. };
  11487. /**
  11488. * Construct an rgba color from a given hex color code.
  11489. *
  11490. * @param {number} color
  11491. * Hex number for color, like #f0e or #f604e2.
  11492. *
  11493. * @param {number} opacity
  11494. * Value for opacity, 0.0 - 1.0.
  11495. *
  11496. * @return {string}
  11497. * The rgba color that was created, like 'rgba(255, 0, 0, 0.3)'.
  11498. */
  11499. function constructColor(color, opacity) {
  11500. var hex;
  11501. if (color.length === 4) {
  11502. // color looks like "#f0e"
  11503. hex = color[1] + color[1] + color[2] + color[2] + color[3] + color[3];
  11504. } else if (color.length === 7) {
  11505. // color looks like "#f604e2"
  11506. hex = color.slice(1);
  11507. } else {
  11508. throw new Error('Invalid color code provided, ' + color + '; must be formatted as e.g. #f0e or #f604e2.');
  11509. }
  11510. return 'rgba(' + parseInt(hex.slice(0, 2), 16) + ',' + parseInt(hex.slice(2, 4), 16) + ',' + parseInt(hex.slice(4, 6), 16) + ',' + opacity + ')';
  11511. }
  11512. /**
  11513. * Try to update the style of a DOM element. Some style changes will throw an error,
  11514. * particularly in IE8. Those should be noops.
  11515. *
  11516. * @param {Element} el
  11517. * The DOM element to be styled.
  11518. *
  11519. * @param {string} style
  11520. * The CSS property on the element that should be styled.
  11521. *
  11522. * @param {string} rule
  11523. * The style rule that should be applied to the property.
  11524. *
  11525. * @private
  11526. */
  11527. function tryUpdateStyle(el, style, rule) {
  11528. try {
  11529. el.style[style] = rule;
  11530. } catch (e) {
  11531. // Satisfies linter.
  11532. return;
  11533. }
  11534. }
  11535. /**
  11536. * The component for displaying text track cues.
  11537. *
  11538. * @extends Component
  11539. */
  11540. var TextTrackDisplay = /*#__PURE__*/function (_Component) {
  11541. inheritsLoose(TextTrackDisplay, _Component);
  11542. /**
  11543. * Creates an instance of this class.
  11544. *
  11545. * @param {Player} player
  11546. * The `Player` that this class should be attached to.
  11547. *
  11548. * @param {Object} [options]
  11549. * The key/value store of player options.
  11550. *
  11551. * @param {Component~ReadyCallback} [ready]
  11552. * The function to call when `TextTrackDisplay` is ready.
  11553. */
  11554. function TextTrackDisplay(player, options, ready) {
  11555. var _this;
  11556. _this = _Component.call(this, player, options, ready) || this;
  11557. var updateDisplayHandler = function updateDisplayHandler(e) {
  11558. return _this.updateDisplay(e);
  11559. };
  11560. player.on('loadstart', function (e) {
  11561. return _this.toggleDisplay(e);
  11562. });
  11563. player.on('texttrackchange', updateDisplayHandler);
  11564. player.on('loadedmetadata', function (e) {
  11565. return _this.preselectTrack(e);
  11566. }); // This used to be called during player init, but was causing an error
  11567. // if a track should show by default and the display hadn't loaded yet.
  11568. // Should probably be moved to an external track loader when we support
  11569. // tracks that don't need a display.
  11570. player.ready(bind(assertThisInitialized(_this), function () {
  11571. if (player.tech_ && player.tech_.featuresNativeTextTracks) {
  11572. this.hide();
  11573. return;
  11574. }
  11575. player.on('fullscreenchange', updateDisplayHandler);
  11576. player.on('playerresize', updateDisplayHandler);
  11577. window.addEventListener('orientationchange', updateDisplayHandler);
  11578. player.on('dispose', function () {
  11579. return window.removeEventListener('orientationchange', updateDisplayHandler);
  11580. });
  11581. var tracks = this.options_.playerOptions.tracks || [];
  11582. for (var i = 0; i < tracks.length; i++) {
  11583. this.player_.addRemoteTextTrack(tracks[i], true);
  11584. }
  11585. this.preselectTrack();
  11586. }));
  11587. return _this;
  11588. }
  11589. /**
  11590. * Preselect a track following this precedence:
  11591. * - matches the previously selected {@link TextTrack}'s language and kind
  11592. * - matches the previously selected {@link TextTrack}'s language only
  11593. * - is the first default captions track
  11594. * - is the first default descriptions track
  11595. *
  11596. * @listens Player#loadstart
  11597. */
  11598. var _proto = TextTrackDisplay.prototype;
  11599. _proto.preselectTrack = function preselectTrack() {
  11600. var modes = {
  11601. captions: 1,
  11602. subtitles: 1
  11603. };
  11604. var trackList = this.player_.textTracks();
  11605. var userPref = this.player_.cache_.selectedLanguage;
  11606. var firstDesc;
  11607. var firstCaptions;
  11608. var preferredTrack;
  11609. for (var i = 0; i < trackList.length; i++) {
  11610. var track = trackList[i];
  11611. if (userPref && userPref.enabled && userPref.language && userPref.language === track.language && track.kind in modes) {
  11612. // Always choose the track that matches both language and kind
  11613. if (track.kind === userPref.kind) {
  11614. preferredTrack = track; // or choose the first track that matches language
  11615. } else if (!preferredTrack) {
  11616. preferredTrack = track;
  11617. } // clear everything if offTextTrackMenuItem was clicked
  11618. } else if (userPref && !userPref.enabled) {
  11619. preferredTrack = null;
  11620. firstDesc = null;
  11621. firstCaptions = null;
  11622. } else if (track["default"]) {
  11623. if (track.kind === 'descriptions' && !firstDesc) {
  11624. firstDesc = track;
  11625. } else if (track.kind in modes && !firstCaptions) {
  11626. firstCaptions = track;
  11627. }
  11628. }
  11629. } // The preferredTrack matches the user preference and takes
  11630. // precedence over all the other tracks.
  11631. // So, display the preferredTrack before the first default track
  11632. // and the subtitles/captions track before the descriptions track
  11633. if (preferredTrack) {
  11634. preferredTrack.mode = 'showing';
  11635. } else if (firstCaptions) {
  11636. firstCaptions.mode = 'showing';
  11637. } else if (firstDesc) {
  11638. firstDesc.mode = 'showing';
  11639. }
  11640. }
  11641. /**
  11642. * Turn display of {@link TextTrack}'s from the current state into the other state.
  11643. * There are only two states:
  11644. * - 'shown'
  11645. * - 'hidden'
  11646. *
  11647. * @listens Player#loadstart
  11648. */
  11649. ;
  11650. _proto.toggleDisplay = function toggleDisplay() {
  11651. if (this.player_.tech_ && this.player_.tech_.featuresNativeTextTracks) {
  11652. this.hide();
  11653. } else {
  11654. this.show();
  11655. }
  11656. }
  11657. /**
  11658. * Create the {@link Component}'s DOM element.
  11659. *
  11660. * @return {Element}
  11661. * The element that was created.
  11662. */
  11663. ;
  11664. _proto.createEl = function createEl() {
  11665. return _Component.prototype.createEl.call(this, 'div', {
  11666. className: 'vjs-text-track-display'
  11667. }, {
  11668. 'translate': 'yes',
  11669. 'aria-live': 'off',
  11670. 'aria-atomic': 'true'
  11671. });
  11672. }
  11673. /**
  11674. * Clear all displayed {@link TextTrack}s.
  11675. */
  11676. ;
  11677. _proto.clearDisplay = function clearDisplay() {
  11678. if (typeof window.WebVTT === 'function') {
  11679. window.WebVTT.processCues(window, [], this.el_);
  11680. }
  11681. }
  11682. /**
  11683. * Update the displayed TextTrack when a either a {@link Player#texttrackchange} or
  11684. * a {@link Player#fullscreenchange} is fired.
  11685. *
  11686. * @listens Player#texttrackchange
  11687. * @listens Player#fullscreenchange
  11688. */
  11689. ;
  11690. _proto.updateDisplay = function updateDisplay() {
  11691. var tracks = this.player_.textTracks();
  11692. var allowMultipleShowingTracks = this.options_.allowMultipleShowingTracks;
  11693. this.clearDisplay();
  11694. if (allowMultipleShowingTracks) {
  11695. var showingTracks = [];
  11696. for (var _i = 0; _i < tracks.length; ++_i) {
  11697. var track = tracks[_i];
  11698. if (track.mode !== 'showing') {
  11699. continue;
  11700. }
  11701. showingTracks.push(track);
  11702. }
  11703. this.updateForTrack(showingTracks);
  11704. return;
  11705. } // Track display prioritization model: if multiple tracks are 'showing',
  11706. // display the first 'subtitles' or 'captions' track which is 'showing',
  11707. // otherwise display the first 'descriptions' track which is 'showing'
  11708. var descriptionsTrack = null;
  11709. var captionsSubtitlesTrack = null;
  11710. var i = tracks.length;
  11711. while (i--) {
  11712. var _track = tracks[i];
  11713. if (_track.mode === 'showing') {
  11714. if (_track.kind === 'descriptions') {
  11715. descriptionsTrack = _track;
  11716. } else {
  11717. captionsSubtitlesTrack = _track;
  11718. }
  11719. }
  11720. }
  11721. if (captionsSubtitlesTrack) {
  11722. if (this.getAttribute('aria-live') !== 'off') {
  11723. this.setAttribute('aria-live', 'off');
  11724. }
  11725. this.updateForTrack(captionsSubtitlesTrack);
  11726. } else if (descriptionsTrack) {
  11727. if (this.getAttribute('aria-live') !== 'assertive') {
  11728. this.setAttribute('aria-live', 'assertive');
  11729. }
  11730. this.updateForTrack(descriptionsTrack);
  11731. }
  11732. }
  11733. /**
  11734. * Style {@Link TextTrack} activeCues according to {@Link TextTrackSettings}.
  11735. *
  11736. * @param {TextTrack} track
  11737. * Text track object containing active cues to style.
  11738. */
  11739. ;
  11740. _proto.updateDisplayState = function updateDisplayState(track) {
  11741. var overrides = this.player_.textTrackSettings.getValues();
  11742. var cues = track.activeCues;
  11743. var i = cues.length;
  11744. while (i--) {
  11745. var cue = cues[i];
  11746. if (!cue) {
  11747. continue;
  11748. }
  11749. var cueDiv = cue.displayState;
  11750. if (overrides.color) {
  11751. cueDiv.firstChild.style.color = overrides.color;
  11752. }
  11753. if (overrides.textOpacity) {
  11754. tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity));
  11755. }
  11756. if (overrides.backgroundColor) {
  11757. cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor;
  11758. }
  11759. if (overrides.backgroundOpacity) {
  11760. tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity));
  11761. }
  11762. if (overrides.windowColor) {
  11763. if (overrides.windowOpacity) {
  11764. tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity));
  11765. } else {
  11766. cueDiv.style.backgroundColor = overrides.windowColor;
  11767. }
  11768. }
  11769. if (overrides.edgeStyle) {
  11770. if (overrides.edgeStyle === 'dropshadow') {
  11771. cueDiv.firstChild.style.textShadow = "2px 2px 3px " + darkGray + ", 2px 2px 4px " + darkGray + ", 2px 2px 5px " + darkGray;
  11772. } else if (overrides.edgeStyle === 'raised') {
  11773. cueDiv.firstChild.style.textShadow = "1px 1px " + darkGray + ", 2px 2px " + darkGray + ", 3px 3px " + darkGray;
  11774. } else if (overrides.edgeStyle === 'depressed') {
  11775. cueDiv.firstChild.style.textShadow = "1px 1px " + lightGray + ", 0 1px " + lightGray + ", -1px -1px " + darkGray + ", 0 -1px " + darkGray;
  11776. } else if (overrides.edgeStyle === 'uniform') {
  11777. cueDiv.firstChild.style.textShadow = "0 0 4px " + darkGray + ", 0 0 4px " + darkGray + ", 0 0 4px " + darkGray + ", 0 0 4px " + darkGray;
  11778. }
  11779. }
  11780. if (overrides.fontPercent && overrides.fontPercent !== 1) {
  11781. var fontSize = window.parseFloat(cueDiv.style.fontSize);
  11782. cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px';
  11783. cueDiv.style.height = 'auto';
  11784. cueDiv.style.top = 'auto';
  11785. }
  11786. if (overrides.fontFamily && overrides.fontFamily !== 'default') {
  11787. if (overrides.fontFamily === 'small-caps') {
  11788. cueDiv.firstChild.style.fontVariant = 'small-caps';
  11789. } else {
  11790. cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily];
  11791. }
  11792. }
  11793. }
  11794. }
  11795. /**
  11796. * Add an {@link TextTrack} to to the {@link Tech}s {@link TextTrackList}.
  11797. *
  11798. * @param {TextTrack|TextTrack[]} tracks
  11799. * Text track object or text track array to be added to the list.
  11800. */
  11801. ;
  11802. _proto.updateForTrack = function updateForTrack(tracks) {
  11803. if (!Array.isArray(tracks)) {
  11804. tracks = [tracks];
  11805. }
  11806. if (typeof window.WebVTT !== 'function' || tracks.every(function (track) {
  11807. return !track.activeCues;
  11808. })) {
  11809. return;
  11810. }
  11811. var cues = []; // push all active track cues
  11812. for (var i = 0; i < tracks.length; ++i) {
  11813. var track = tracks[i];
  11814. for (var j = 0; j < track.activeCues.length; ++j) {
  11815. cues.push(track.activeCues[j]);
  11816. }
  11817. } // removes all cues before it processes new ones
  11818. window.WebVTT.processCues(window, cues, this.el_); // add unique class to each language text track & add settings styling if necessary
  11819. for (var _i2 = 0; _i2 < tracks.length; ++_i2) {
  11820. var _track2 = tracks[_i2];
  11821. for (var _j = 0; _j < _track2.activeCues.length; ++_j) {
  11822. var cueEl = _track2.activeCues[_j].displayState;
  11823. addClass(cueEl, 'vjs-text-track-cue');
  11824. addClass(cueEl, 'vjs-text-track-cue-' + (_track2.language ? _track2.language : _i2));
  11825. if (_track2.language) {
  11826. setAttribute(cueEl, 'lang', _track2.language);
  11827. }
  11828. }
  11829. if (this.player_.textTrackSettings) {
  11830. this.updateDisplayState(_track2);
  11831. }
  11832. }
  11833. };
  11834. return TextTrackDisplay;
  11835. }(Component$1);
  11836. Component$1.registerComponent('TextTrackDisplay', TextTrackDisplay);
  11837. /**
  11838. * A loading spinner for use during waiting/loading events.
  11839. *
  11840. * @extends Component
  11841. */
  11842. var LoadingSpinner = /*#__PURE__*/function (_Component) {
  11843. inheritsLoose(LoadingSpinner, _Component);
  11844. function LoadingSpinner() {
  11845. return _Component.apply(this, arguments) || this;
  11846. }
  11847. var _proto = LoadingSpinner.prototype;
  11848. /**
  11849. * Create the `LoadingSpinner`s DOM element.
  11850. *
  11851. * @return {Element}
  11852. * The dom element that gets created.
  11853. */
  11854. _proto.createEl = function createEl$1() {
  11855. var isAudio = this.player_.isAudio();
  11856. var playerType = this.localize(isAudio ? 'Audio Player' : 'Video Player');
  11857. var controlText = createEl('span', {
  11858. className: 'vjs-control-text',
  11859. textContent: this.localize('{1} is loading.', [playerType])
  11860. });
  11861. var el = _Component.prototype.createEl.call(this, 'div', {
  11862. className: 'vjs-loading-spinner',
  11863. dir: 'ltr'
  11864. });
  11865. el.appendChild(controlText);
  11866. return el;
  11867. };
  11868. return LoadingSpinner;
  11869. }(Component$1);
  11870. Component$1.registerComponent('LoadingSpinner', LoadingSpinner);
  11871. /**
  11872. * Base class for all buttons.
  11873. *
  11874. * @extends ClickableComponent
  11875. */
  11876. var Button = /*#__PURE__*/function (_ClickableComponent) {
  11877. inheritsLoose(Button, _ClickableComponent);
  11878. function Button() {
  11879. return _ClickableComponent.apply(this, arguments) || this;
  11880. }
  11881. var _proto = Button.prototype;
  11882. /**
  11883. * Create the `Button`s DOM element.
  11884. *
  11885. * @param {string} [tag="button"]
  11886. * The element's node type. This argument is IGNORED: no matter what
  11887. * is passed, it will always create a `button` element.
  11888. *
  11889. * @param {Object} [props={}]
  11890. * An object of properties that should be set on the element.
  11891. *
  11892. * @param {Object} [attributes={}]
  11893. * An object of attributes that should be set on the element.
  11894. *
  11895. * @return {Element}
  11896. * The element that gets created.
  11897. */
  11898. _proto.createEl = function createEl$1(tag, props, attributes) {
  11899. if (props === void 0) {
  11900. props = {};
  11901. }
  11902. if (attributes === void 0) {
  11903. attributes = {};
  11904. }
  11905. tag = 'button';
  11906. props = assign$1({
  11907. className: this.buildCSSClass()
  11908. }, props); // Add attributes for button element
  11909. attributes = assign$1({
  11910. // Necessary since the default button type is "submit"
  11911. type: 'button'
  11912. }, attributes);
  11913. var el = createEl(tag, props, attributes);
  11914. el.appendChild(createEl('span', {
  11915. className: 'vjs-icon-placeholder'
  11916. }, {
  11917. 'aria-hidden': true
  11918. }));
  11919. this.createControlTextEl(el);
  11920. return el;
  11921. }
  11922. /**
  11923. * Add a child `Component` inside of this `Button`.
  11924. *
  11925. * @param {string|Component} child
  11926. * The name or instance of a child to add.
  11927. *
  11928. * @param {Object} [options={}]
  11929. * The key/value store of options that will get passed to children of
  11930. * the child.
  11931. *
  11932. * @return {Component}
  11933. * The `Component` that gets added as a child. When using a string the
  11934. * `Component` will get created by this process.
  11935. *
  11936. * @deprecated since version 5
  11937. */
  11938. ;
  11939. _proto.addChild = function addChild(child, options) {
  11940. if (options === void 0) {
  11941. options = {};
  11942. }
  11943. var className = this.constructor.name;
  11944. log$1.warn("Adding an actionable (user controllable) child to a Button (" + className + ") is not supported; use a ClickableComponent instead."); // Avoid the error message generated by ClickableComponent's addChild method
  11945. return Component$1.prototype.addChild.call(this, child, options);
  11946. }
  11947. /**
  11948. * Enable the `Button` element so that it can be activated or clicked. Use this with
  11949. * {@link Button#disable}.
  11950. */
  11951. ;
  11952. _proto.enable = function enable() {
  11953. _ClickableComponent.prototype.enable.call(this);
  11954. this.el_.removeAttribute('disabled');
  11955. }
  11956. /**
  11957. * Disable the `Button` element so that it cannot be activated or clicked. Use this with
  11958. * {@link Button#enable}.
  11959. */
  11960. ;
  11961. _proto.disable = function disable() {
  11962. _ClickableComponent.prototype.disable.call(this);
  11963. this.el_.setAttribute('disabled', 'disabled');
  11964. }
  11965. /**
  11966. * This gets called when a `Button` has focus and `keydown` is triggered via a key
  11967. * press.
  11968. *
  11969. * @param {EventTarget~Event} event
  11970. * The event that caused this function to get called.
  11971. *
  11972. * @listens keydown
  11973. */
  11974. ;
  11975. _proto.handleKeyDown = function handleKeyDown(event) {
  11976. // Ignore Space or Enter key operation, which is handled by the browser for
  11977. // a button - though not for its super class, ClickableComponent. Also,
  11978. // prevent the event from propagating through the DOM and triggering Player
  11979. // hotkeys. We do not preventDefault here because we _want_ the browser to
  11980. // handle it.
  11981. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) {
  11982. event.stopPropagation();
  11983. return;
  11984. } // Pass keypress handling up for unsupported keys
  11985. _ClickableComponent.prototype.handleKeyDown.call(this, event);
  11986. };
  11987. return Button;
  11988. }(ClickableComponent);
  11989. Component$1.registerComponent('Button', Button);
  11990. /**
  11991. * The initial play button that shows before the video has played. The hiding of the
  11992. * `BigPlayButton` get done via CSS and `Player` states.
  11993. *
  11994. * @extends Button
  11995. */
  11996. var BigPlayButton = /*#__PURE__*/function (_Button) {
  11997. inheritsLoose(BigPlayButton, _Button);
  11998. function BigPlayButton(player, options) {
  11999. var _this;
  12000. _this = _Button.call(this, player, options) || this;
  12001. _this.mouseused_ = false;
  12002. _this.on('mousedown', function (e) {
  12003. return _this.handleMouseDown(e);
  12004. });
  12005. return _this;
  12006. }
  12007. /**
  12008. * Builds the default DOM `className`.
  12009. *
  12010. * @return {string}
  12011. * The DOM `className` for this object. Always returns 'vjs-big-play-button'.
  12012. */
  12013. var _proto = BigPlayButton.prototype;
  12014. _proto.buildCSSClass = function buildCSSClass() {
  12015. return 'vjs-big-play-button';
  12016. }
  12017. /**
  12018. * This gets called when a `BigPlayButton` "clicked". See {@link ClickableComponent}
  12019. * for more detailed information on what a click can be.
  12020. *
  12021. * @param {EventTarget~Event} event
  12022. * The `keydown`, `tap`, or `click` event that caused this function to be
  12023. * called.
  12024. *
  12025. * @listens tap
  12026. * @listens click
  12027. */
  12028. ;
  12029. _proto.handleClick = function handleClick(event) {
  12030. var playPromise = this.player_.play(); // exit early if clicked via the mouse
  12031. if (this.mouseused_ && event.clientX && event.clientY) {
  12032. var sourceIsEncrypted = this.player_.usingPlugin('eme') && this.player_.eme.sessions && this.player_.eme.sessions.length > 0;
  12033. silencePromise(playPromise);
  12034. if (this.player_.tech(true) && // We've observed a bug in IE and Edge when playing back DRM content where
  12035. // calling .focus() on the video element causes the video to go black,
  12036. // so we avoid it in that specific case
  12037. !((IE_VERSION || IS_EDGE) && sourceIsEncrypted)) {
  12038. this.player_.tech(true).focus();
  12039. }
  12040. return;
  12041. }
  12042. var cb = this.player_.getChild('controlBar');
  12043. var playToggle = cb && cb.getChild('playToggle');
  12044. if (!playToggle) {
  12045. this.player_.tech(true).focus();
  12046. return;
  12047. }
  12048. var playFocus = function playFocus() {
  12049. return playToggle.focus();
  12050. };
  12051. if (isPromise(playPromise)) {
  12052. playPromise.then(playFocus, function () {});
  12053. } else {
  12054. this.setTimeout(playFocus, 1);
  12055. }
  12056. };
  12057. _proto.handleKeyDown = function handleKeyDown(event) {
  12058. this.mouseused_ = false;
  12059. _Button.prototype.handleKeyDown.call(this, event);
  12060. };
  12061. _proto.handleMouseDown = function handleMouseDown(event) {
  12062. this.mouseused_ = true;
  12063. };
  12064. return BigPlayButton;
  12065. }(Button);
  12066. /**
  12067. * The text that should display over the `BigPlayButton`s controls. Added to for localization.
  12068. *
  12069. * @type {string}
  12070. * @private
  12071. */
  12072. BigPlayButton.prototype.controlText_ = 'Play Video';
  12073. Component$1.registerComponent('BigPlayButton', BigPlayButton);
  12074. /**
  12075. * The `CloseButton` is a `{@link Button}` that fires a `close` event when
  12076. * it gets clicked.
  12077. *
  12078. * @extends Button
  12079. */
  12080. var CloseButton = /*#__PURE__*/function (_Button) {
  12081. inheritsLoose(CloseButton, _Button);
  12082. /**
  12083. * Creates an instance of the this class.
  12084. *
  12085. * @param {Player} player
  12086. * The `Player` that this class should be attached to.
  12087. *
  12088. * @param {Object} [options]
  12089. * The key/value store of player options.
  12090. */
  12091. function CloseButton(player, options) {
  12092. var _this;
  12093. _this = _Button.call(this, player, options) || this;
  12094. _this.controlText(options && options.controlText || _this.localize('Close'));
  12095. return _this;
  12096. }
  12097. /**
  12098. * Builds the default DOM `className`.
  12099. *
  12100. * @return {string}
  12101. * The DOM `className` for this object.
  12102. */
  12103. var _proto = CloseButton.prototype;
  12104. _proto.buildCSSClass = function buildCSSClass() {
  12105. return "vjs-close-button " + _Button.prototype.buildCSSClass.call(this);
  12106. }
  12107. /**
  12108. * This gets called when a `CloseButton` gets clicked. See
  12109. * {@link ClickableComponent#handleClick} for more information on when
  12110. * this will be triggered
  12111. *
  12112. * @param {EventTarget~Event} event
  12113. * The `keydown`, `tap`, or `click` event that caused this function to be
  12114. * called.
  12115. *
  12116. * @listens tap
  12117. * @listens click
  12118. * @fires CloseButton#close
  12119. */
  12120. ;
  12121. _proto.handleClick = function handleClick(event) {
  12122. /**
  12123. * Triggered when the a `CloseButton` is clicked.
  12124. *
  12125. * @event CloseButton#close
  12126. * @type {EventTarget~Event}
  12127. *
  12128. * @property {boolean} [bubbles=false]
  12129. * set to false so that the close event does not
  12130. * bubble up to parents if there is no listener
  12131. */
  12132. this.trigger({
  12133. type: 'close',
  12134. bubbles: false
  12135. });
  12136. }
  12137. /**
  12138. * Event handler that is called when a `CloseButton` receives a
  12139. * `keydown` event.
  12140. *
  12141. * By default, if the key is Esc, it will trigger a `click` event.
  12142. *
  12143. * @param {EventTarget~Event} event
  12144. * The `keydown` event that caused this function to be called.
  12145. *
  12146. * @listens keydown
  12147. */
  12148. ;
  12149. _proto.handleKeyDown = function handleKeyDown(event) {
  12150. // Esc button will trigger `click` event
  12151. if (keycode.isEventKey(event, 'Esc')) {
  12152. event.preventDefault();
  12153. event.stopPropagation();
  12154. this.trigger('click');
  12155. } else {
  12156. // Pass keypress handling up for unsupported keys
  12157. _Button.prototype.handleKeyDown.call(this, event);
  12158. }
  12159. };
  12160. return CloseButton;
  12161. }(Button);
  12162. Component$1.registerComponent('CloseButton', CloseButton);
  12163. /**
  12164. * Button to toggle between play and pause.
  12165. *
  12166. * @extends Button
  12167. */
  12168. var PlayToggle = /*#__PURE__*/function (_Button) {
  12169. inheritsLoose(PlayToggle, _Button);
  12170. /**
  12171. * Creates an instance of this class.
  12172. *
  12173. * @param {Player} player
  12174. * The `Player` that this class should be attached to.
  12175. *
  12176. * @param {Object} [options={}]
  12177. * The key/value store of player options.
  12178. */
  12179. function PlayToggle(player, options) {
  12180. var _this;
  12181. if (options === void 0) {
  12182. options = {};
  12183. }
  12184. _this = _Button.call(this, player, options) || this; // show or hide replay icon
  12185. options.replay = options.replay === undefined || options.replay;
  12186. _this.on(player, 'play', function (e) {
  12187. return _this.handlePlay(e);
  12188. });
  12189. _this.on(player, 'pause', function (e) {
  12190. return _this.handlePause(e);
  12191. });
  12192. if (options.replay) {
  12193. _this.on(player, 'ended', function (e) {
  12194. return _this.handleEnded(e);
  12195. });
  12196. }
  12197. return _this;
  12198. }
  12199. /**
  12200. * Builds the default DOM `className`.
  12201. *
  12202. * @return {string}
  12203. * The DOM `className` for this object.
  12204. */
  12205. var _proto = PlayToggle.prototype;
  12206. _proto.buildCSSClass = function buildCSSClass() {
  12207. return "vjs-play-control " + _Button.prototype.buildCSSClass.call(this);
  12208. }
  12209. /**
  12210. * This gets called when an `PlayToggle` is "clicked". See
  12211. * {@link ClickableComponent} for more detailed information on what a click can be.
  12212. *
  12213. * @param {EventTarget~Event} [event]
  12214. * The `keydown`, `tap`, or `click` event that caused this function to be
  12215. * called.
  12216. *
  12217. * @listens tap
  12218. * @listens click
  12219. */
  12220. ;
  12221. _proto.handleClick = function handleClick(event) {
  12222. if (this.player_.paused()) {
  12223. silencePromise(this.player_.play());
  12224. } else {
  12225. this.player_.pause();
  12226. }
  12227. }
  12228. /**
  12229. * This gets called once after the video has ended and the user seeks so that
  12230. * we can change the replay button back to a play button.
  12231. *
  12232. * @param {EventTarget~Event} [event]
  12233. * The event that caused this function to run.
  12234. *
  12235. * @listens Player#seeked
  12236. */
  12237. ;
  12238. _proto.handleSeeked = function handleSeeked(event) {
  12239. this.removeClass('vjs-ended');
  12240. if (this.player_.paused()) {
  12241. this.handlePause(event);
  12242. } else {
  12243. this.handlePlay(event);
  12244. }
  12245. }
  12246. /**
  12247. * Add the vjs-playing class to the element so it can change appearance.
  12248. *
  12249. * @param {EventTarget~Event} [event]
  12250. * The event that caused this function to run.
  12251. *
  12252. * @listens Player#play
  12253. */
  12254. ;
  12255. _proto.handlePlay = function handlePlay(event) {
  12256. this.removeClass('vjs-ended');
  12257. this.removeClass('vjs-paused');
  12258. this.addClass('vjs-playing'); // change the button text to "Pause"
  12259. this.controlText('Pause');
  12260. }
  12261. /**
  12262. * Add the vjs-paused class to the element so it can change appearance.
  12263. *
  12264. * @param {EventTarget~Event} [event]
  12265. * The event that caused this function to run.
  12266. *
  12267. * @listens Player#pause
  12268. */
  12269. ;
  12270. _proto.handlePause = function handlePause(event) {
  12271. this.removeClass('vjs-playing');
  12272. this.addClass('vjs-paused'); // change the button text to "Play"
  12273. this.controlText('Play');
  12274. }
  12275. /**
  12276. * Add the vjs-ended class to the element so it can change appearance
  12277. *
  12278. * @param {EventTarget~Event} [event]
  12279. * The event that caused this function to run.
  12280. *
  12281. * @listens Player#ended
  12282. */
  12283. ;
  12284. _proto.handleEnded = function handleEnded(event) {
  12285. var _this2 = this;
  12286. this.removeClass('vjs-playing');
  12287. this.addClass('vjs-ended'); // change the button text to "Replay"
  12288. this.controlText('Replay'); // on the next seek remove the replay button
  12289. this.one(this.player_, 'seeked', function (e) {
  12290. return _this2.handleSeeked(e);
  12291. });
  12292. };
  12293. return PlayToggle;
  12294. }(Button);
  12295. /**
  12296. * The text that should display over the `PlayToggle`s controls. Added for localization.
  12297. *
  12298. * @type {string}
  12299. * @private
  12300. */
  12301. PlayToggle.prototype.controlText_ = 'Play';
  12302. Component$1.registerComponent('PlayToggle', PlayToggle);
  12303. /**
  12304. * @file format-time.js
  12305. * @module format-time
  12306. */
  12307. /**
  12308. * Format seconds as a time string, H:MM:SS or M:SS. Supplying a guide (in
  12309. * seconds) will force a number of leading zeros to cover the length of the
  12310. * guide.
  12311. *
  12312. * @private
  12313. * @param {number} seconds
  12314. * Number of seconds to be turned into a string
  12315. *
  12316. * @param {number} guide
  12317. * Number (in seconds) to model the string after
  12318. *
  12319. * @return {string}
  12320. * Time formatted as H:MM:SS or M:SS
  12321. */
  12322. var defaultImplementation = function defaultImplementation(seconds, guide) {
  12323. seconds = seconds < 0 ? 0 : seconds;
  12324. var s = Math.floor(seconds % 60);
  12325. var m = Math.floor(seconds / 60 % 60);
  12326. var h = Math.floor(seconds / 3600);
  12327. var gm = Math.floor(guide / 60 % 60);
  12328. var gh = Math.floor(guide / 3600); // handle invalid times
  12329. if (isNaN(seconds) || seconds === Infinity) {
  12330. // '-' is false for all relational operators (e.g. <, >=) so this setting
  12331. // will add the minimum number of fields specified by the guide
  12332. h = m = s = '-';
  12333. } // Check if we need to show hours
  12334. h = h > 0 || gh > 0 ? h + ':' : ''; // If hours are showing, we may need to add a leading zero.
  12335. // Always show at least one digit of minutes.
  12336. m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':'; // Check if leading zero is need for seconds
  12337. s = s < 10 ? '0' + s : s;
  12338. return h + m + s;
  12339. }; // Internal pointer to the current implementation.
  12340. var implementation = defaultImplementation;
  12341. /**
  12342. * Replaces the default formatTime implementation with a custom implementation.
  12343. *
  12344. * @param {Function} customImplementation
  12345. * A function which will be used in place of the default formatTime
  12346. * implementation. Will receive the current time in seconds and the
  12347. * guide (in seconds) as arguments.
  12348. */
  12349. function setFormatTime(customImplementation) {
  12350. implementation = customImplementation;
  12351. }
  12352. /**
  12353. * Resets formatTime to the default implementation.
  12354. */
  12355. function resetFormatTime() {
  12356. implementation = defaultImplementation;
  12357. }
  12358. /**
  12359. * Delegates to either the default time formatting function or a custom
  12360. * function supplied via `setFormatTime`.
  12361. *
  12362. * Formats seconds as a time string (H:MM:SS or M:SS). Supplying a
  12363. * guide (in seconds) will force a number of leading zeros to cover the
  12364. * length of the guide.
  12365. *
  12366. * @static
  12367. * @example formatTime(125, 600) === "02:05"
  12368. * @param {number} seconds
  12369. * Number of seconds to be turned into a string
  12370. *
  12371. * @param {number} guide
  12372. * Number (in seconds) to model the string after
  12373. *
  12374. * @return {string}
  12375. * Time formatted as H:MM:SS or M:SS
  12376. */
  12377. function formatTime(seconds, guide) {
  12378. if (guide === void 0) {
  12379. guide = seconds;
  12380. }
  12381. return implementation(seconds, guide);
  12382. }
  12383. /**
  12384. * Displays time information about the video
  12385. *
  12386. * @extends Component
  12387. */
  12388. var TimeDisplay = /*#__PURE__*/function (_Component) {
  12389. inheritsLoose(TimeDisplay, _Component);
  12390. /**
  12391. * Creates an instance of this class.
  12392. *
  12393. * @param {Player} player
  12394. * The `Player` that this class should be attached to.
  12395. *
  12396. * @param {Object} [options]
  12397. * The key/value store of player options.
  12398. */
  12399. function TimeDisplay(player, options) {
  12400. var _this;
  12401. _this = _Component.call(this, player, options) || this;
  12402. _this.on(player, ['timeupdate', 'ended'], function (e) {
  12403. return _this.updateContent(e);
  12404. });
  12405. _this.updateTextNode_();
  12406. return _this;
  12407. }
  12408. /**
  12409. * Create the `Component`'s DOM element
  12410. *
  12411. * @return {Element}
  12412. * The element that was created.
  12413. */
  12414. var _proto = TimeDisplay.prototype;
  12415. _proto.createEl = function createEl$1() {
  12416. var className = this.buildCSSClass();
  12417. var el = _Component.prototype.createEl.call(this, 'div', {
  12418. className: className + " vjs-time-control vjs-control"
  12419. });
  12420. var span = createEl('span', {
  12421. className: 'vjs-control-text',
  12422. textContent: this.localize(this.labelText_) + "\xA0"
  12423. }, {
  12424. role: 'presentation'
  12425. });
  12426. el.appendChild(span);
  12427. this.contentEl_ = createEl('span', {
  12428. className: className + "-display"
  12429. }, {
  12430. // tell screen readers not to automatically read the time as it changes
  12431. 'aria-live': 'off',
  12432. // span elements have no implicit role, but some screen readers (notably VoiceOver)
  12433. // treat them as a break between items in the DOM when using arrow keys
  12434. // (or left-to-right swipes on iOS) to read contents of a page. Using
  12435. // role='presentation' causes VoiceOver to NOT treat this span as a break.
  12436. 'role': 'presentation'
  12437. });
  12438. el.appendChild(this.contentEl_);
  12439. return el;
  12440. };
  12441. _proto.dispose = function dispose() {
  12442. this.contentEl_ = null;
  12443. this.textNode_ = null;
  12444. _Component.prototype.dispose.call(this);
  12445. }
  12446. /**
  12447. * Updates the time display text node with a new time
  12448. *
  12449. * @param {number} [time=0] the time to update to
  12450. *
  12451. * @private
  12452. */
  12453. ;
  12454. _proto.updateTextNode_ = function updateTextNode_(time) {
  12455. var _this2 = this;
  12456. if (time === void 0) {
  12457. time = 0;
  12458. }
  12459. time = formatTime(time);
  12460. if (this.formattedTime_ === time) {
  12461. return;
  12462. }
  12463. this.formattedTime_ = time;
  12464. this.requestNamedAnimationFrame('TimeDisplay#updateTextNode_', function () {
  12465. if (!_this2.contentEl_) {
  12466. return;
  12467. }
  12468. var oldNode = _this2.textNode_;
  12469. if (oldNode && _this2.contentEl_.firstChild !== oldNode) {
  12470. oldNode = null;
  12471. log$1.warn('TimeDisplay#updateTextnode_: Prevented replacement of text node element since it was no longer a child of this node. Appending a new node instead.');
  12472. }
  12473. _this2.textNode_ = document.createTextNode(_this2.formattedTime_);
  12474. if (!_this2.textNode_) {
  12475. return;
  12476. }
  12477. if (oldNode) {
  12478. _this2.contentEl_.replaceChild(_this2.textNode_, oldNode);
  12479. } else {
  12480. _this2.contentEl_.appendChild(_this2.textNode_);
  12481. }
  12482. });
  12483. }
  12484. /**
  12485. * To be filled out in the child class, should update the displayed time
  12486. * in accordance with the fact that the current time has changed.
  12487. *
  12488. * @param {EventTarget~Event} [event]
  12489. * The `timeupdate` event that caused this to run.
  12490. *
  12491. * @listens Player#timeupdate
  12492. */
  12493. ;
  12494. _proto.updateContent = function updateContent(event) {};
  12495. return TimeDisplay;
  12496. }(Component$1);
  12497. /**
  12498. * The text that is added to the `TimeDisplay` for screen reader users.
  12499. *
  12500. * @type {string}
  12501. * @private
  12502. */
  12503. TimeDisplay.prototype.labelText_ = 'Time';
  12504. /**
  12505. * The text that should display over the `TimeDisplay`s controls. Added to for localization.
  12506. *
  12507. * @type {string}
  12508. * @private
  12509. *
  12510. * @deprecated in v7; controlText_ is not used in non-active display Components
  12511. */
  12512. TimeDisplay.prototype.controlText_ = 'Time';
  12513. Component$1.registerComponent('TimeDisplay', TimeDisplay);
  12514. /**
  12515. * Displays the current time
  12516. *
  12517. * @extends Component
  12518. */
  12519. var CurrentTimeDisplay = /*#__PURE__*/function (_TimeDisplay) {
  12520. inheritsLoose(CurrentTimeDisplay, _TimeDisplay);
  12521. function CurrentTimeDisplay() {
  12522. return _TimeDisplay.apply(this, arguments) || this;
  12523. }
  12524. var _proto = CurrentTimeDisplay.prototype;
  12525. /**
  12526. * Builds the default DOM `className`.
  12527. *
  12528. * @return {string}
  12529. * The DOM `className` for this object.
  12530. */
  12531. _proto.buildCSSClass = function buildCSSClass() {
  12532. return 'vjs-current-time';
  12533. }
  12534. /**
  12535. * Update current time display
  12536. *
  12537. * @param {EventTarget~Event} [event]
  12538. * The `timeupdate` event that caused this function to run.
  12539. *
  12540. * @listens Player#timeupdate
  12541. */
  12542. ;
  12543. _proto.updateContent = function updateContent(event) {
  12544. // Allows for smooth scrubbing, when player can't keep up.
  12545. var time;
  12546. if (this.player_.ended()) {
  12547. time = this.player_.duration();
  12548. } else {
  12549. time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  12550. }
  12551. this.updateTextNode_(time);
  12552. };
  12553. return CurrentTimeDisplay;
  12554. }(TimeDisplay);
  12555. /**
  12556. * The text that is added to the `CurrentTimeDisplay` for screen reader users.
  12557. *
  12558. * @type {string}
  12559. * @private
  12560. */
  12561. CurrentTimeDisplay.prototype.labelText_ = 'Current Time';
  12562. /**
  12563. * The text that should display over the `CurrentTimeDisplay`s controls. Added to for localization.
  12564. *
  12565. * @type {string}
  12566. * @private
  12567. *
  12568. * @deprecated in v7; controlText_ is not used in non-active display Components
  12569. */
  12570. CurrentTimeDisplay.prototype.controlText_ = 'Current Time';
  12571. Component$1.registerComponent('CurrentTimeDisplay', CurrentTimeDisplay);
  12572. /**
  12573. * Displays the duration
  12574. *
  12575. * @extends Component
  12576. */
  12577. var DurationDisplay = /*#__PURE__*/function (_TimeDisplay) {
  12578. inheritsLoose(DurationDisplay, _TimeDisplay);
  12579. /**
  12580. * Creates an instance of this class.
  12581. *
  12582. * @param {Player} player
  12583. * The `Player` that this class should be attached to.
  12584. *
  12585. * @param {Object} [options]
  12586. * The key/value store of player options.
  12587. */
  12588. function DurationDisplay(player, options) {
  12589. var _this;
  12590. _this = _TimeDisplay.call(this, player, options) || this;
  12591. var updateContent = function updateContent(e) {
  12592. return _this.updateContent(e);
  12593. }; // we do not want to/need to throttle duration changes,
  12594. // as they should always display the changed duration as
  12595. // it has changed
  12596. _this.on(player, 'durationchange', updateContent); // Listen to loadstart because the player duration is reset when a new media element is loaded,
  12597. // but the durationchange on the user agent will not fire.
  12598. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}
  12599. _this.on(player, 'loadstart', updateContent); // Also listen for timeupdate (in the parent) and loadedmetadata because removing those
  12600. // listeners could have broken dependent applications/libraries. These
  12601. // can likely be removed for 7.0.
  12602. _this.on(player, 'loadedmetadata', updateContent);
  12603. return _this;
  12604. }
  12605. /**
  12606. * Builds the default DOM `className`.
  12607. *
  12608. * @return {string}
  12609. * The DOM `className` for this object.
  12610. */
  12611. var _proto = DurationDisplay.prototype;
  12612. _proto.buildCSSClass = function buildCSSClass() {
  12613. return 'vjs-duration';
  12614. }
  12615. /**
  12616. * Update duration time display.
  12617. *
  12618. * @param {EventTarget~Event} [event]
  12619. * The `durationchange`, `timeupdate`, or `loadedmetadata` event that caused
  12620. * this function to be called.
  12621. *
  12622. * @listens Player#durationchange
  12623. * @listens Player#timeupdate
  12624. * @listens Player#loadedmetadata
  12625. */
  12626. ;
  12627. _proto.updateContent = function updateContent(event) {
  12628. var duration = this.player_.duration();
  12629. this.updateTextNode_(duration);
  12630. };
  12631. return DurationDisplay;
  12632. }(TimeDisplay);
  12633. /**
  12634. * The text that is added to the `DurationDisplay` for screen reader users.
  12635. *
  12636. * @type {string}
  12637. * @private
  12638. */
  12639. DurationDisplay.prototype.labelText_ = 'Duration';
  12640. /**
  12641. * The text that should display over the `DurationDisplay`s controls. Added to for localization.
  12642. *
  12643. * @type {string}
  12644. * @private
  12645. *
  12646. * @deprecated in v7; controlText_ is not used in non-active display Components
  12647. */
  12648. DurationDisplay.prototype.controlText_ = 'Duration';
  12649. Component$1.registerComponent('DurationDisplay', DurationDisplay);
  12650. /**
  12651. * The separator between the current time and duration.
  12652. * Can be hidden if it's not needed in the design.
  12653. *
  12654. * @extends Component
  12655. */
  12656. var TimeDivider = /*#__PURE__*/function (_Component) {
  12657. inheritsLoose(TimeDivider, _Component);
  12658. function TimeDivider() {
  12659. return _Component.apply(this, arguments) || this;
  12660. }
  12661. var _proto = TimeDivider.prototype;
  12662. /**
  12663. * Create the component's DOM element
  12664. *
  12665. * @return {Element}
  12666. * The element that was created.
  12667. */
  12668. _proto.createEl = function createEl() {
  12669. var el = _Component.prototype.createEl.call(this, 'div', {
  12670. className: 'vjs-time-control vjs-time-divider'
  12671. }, {
  12672. // this element and its contents can be hidden from assistive techs since
  12673. // it is made extraneous by the announcement of the control text
  12674. // for the current time and duration displays
  12675. 'aria-hidden': true
  12676. });
  12677. var div = _Component.prototype.createEl.call(this, 'div');
  12678. var span = _Component.prototype.createEl.call(this, 'span', {
  12679. textContent: '/'
  12680. });
  12681. div.appendChild(span);
  12682. el.appendChild(div);
  12683. return el;
  12684. };
  12685. return TimeDivider;
  12686. }(Component$1);
  12687. Component$1.registerComponent('TimeDivider', TimeDivider);
  12688. /**
  12689. * Displays the time left in the video
  12690. *
  12691. * @extends Component
  12692. */
  12693. var RemainingTimeDisplay = /*#__PURE__*/function (_TimeDisplay) {
  12694. inheritsLoose(RemainingTimeDisplay, _TimeDisplay);
  12695. /**
  12696. * Creates an instance of this class.
  12697. *
  12698. * @param {Player} player
  12699. * The `Player` that this class should be attached to.
  12700. *
  12701. * @param {Object} [options]
  12702. * The key/value store of player options.
  12703. */
  12704. function RemainingTimeDisplay(player, options) {
  12705. var _this;
  12706. _this = _TimeDisplay.call(this, player, options) || this;
  12707. _this.on(player, 'durationchange', function (e) {
  12708. return _this.updateContent(e);
  12709. });
  12710. return _this;
  12711. }
  12712. /**
  12713. * Builds the default DOM `className`.
  12714. *
  12715. * @return {string}
  12716. * The DOM `className` for this object.
  12717. */
  12718. var _proto = RemainingTimeDisplay.prototype;
  12719. _proto.buildCSSClass = function buildCSSClass() {
  12720. return 'vjs-remaining-time';
  12721. }
  12722. /**
  12723. * Create the `Component`'s DOM element with the "minus" characted prepend to the time
  12724. *
  12725. * @return {Element}
  12726. * The element that was created.
  12727. */
  12728. ;
  12729. _proto.createEl = function createEl$1() {
  12730. var el = _TimeDisplay.prototype.createEl.call(this);
  12731. if (this.options_.displayNegative !== false) {
  12732. el.insertBefore(createEl('span', {}, {
  12733. 'aria-hidden': true
  12734. }, '-'), this.contentEl_);
  12735. }
  12736. return el;
  12737. }
  12738. /**
  12739. * Update remaining time display.
  12740. *
  12741. * @param {EventTarget~Event} [event]
  12742. * The `timeupdate` or `durationchange` event that caused this to run.
  12743. *
  12744. * @listens Player#timeupdate
  12745. * @listens Player#durationchange
  12746. */
  12747. ;
  12748. _proto.updateContent = function updateContent(event) {
  12749. if (typeof this.player_.duration() !== 'number') {
  12750. return;
  12751. }
  12752. var time; // @deprecated We should only use remainingTimeDisplay
  12753. // as of video.js 7
  12754. if (this.player_.ended()) {
  12755. time = 0;
  12756. } else if (this.player_.remainingTimeDisplay) {
  12757. time = this.player_.remainingTimeDisplay();
  12758. } else {
  12759. time = this.player_.remainingTime();
  12760. }
  12761. this.updateTextNode_(time);
  12762. };
  12763. return RemainingTimeDisplay;
  12764. }(TimeDisplay);
  12765. /**
  12766. * The text that is added to the `RemainingTimeDisplay` for screen reader users.
  12767. *
  12768. * @type {string}
  12769. * @private
  12770. */
  12771. RemainingTimeDisplay.prototype.labelText_ = 'Remaining Time';
  12772. /**
  12773. * The text that should display over the `RemainingTimeDisplay`s controls. Added to for localization.
  12774. *
  12775. * @type {string}
  12776. * @private
  12777. *
  12778. * @deprecated in v7; controlText_ is not used in non-active display Components
  12779. */
  12780. RemainingTimeDisplay.prototype.controlText_ = 'Remaining Time';
  12781. Component$1.registerComponent('RemainingTimeDisplay', RemainingTimeDisplay);
  12782. /**
  12783. * Displays the live indicator when duration is Infinity.
  12784. *
  12785. * @extends Component
  12786. */
  12787. var LiveDisplay = /*#__PURE__*/function (_Component) {
  12788. inheritsLoose(LiveDisplay, _Component);
  12789. /**
  12790. * Creates an instance of this class.
  12791. *
  12792. * @param {Player} player
  12793. * The `Player` that this class should be attached to.
  12794. *
  12795. * @param {Object} [options]
  12796. * The key/value store of player options.
  12797. */
  12798. function LiveDisplay(player, options) {
  12799. var _this;
  12800. _this = _Component.call(this, player, options) || this;
  12801. _this.updateShowing();
  12802. _this.on(_this.player(), 'durationchange', function (e) {
  12803. return _this.updateShowing(e);
  12804. });
  12805. return _this;
  12806. }
  12807. /**
  12808. * Create the `Component`'s DOM element
  12809. *
  12810. * @return {Element}
  12811. * The element that was created.
  12812. */
  12813. var _proto = LiveDisplay.prototype;
  12814. _proto.createEl = function createEl$1() {
  12815. var el = _Component.prototype.createEl.call(this, 'div', {
  12816. className: 'vjs-live-control vjs-control'
  12817. });
  12818. this.contentEl_ = createEl('div', {
  12819. className: 'vjs-live-display'
  12820. }, {
  12821. 'aria-live': 'off'
  12822. });
  12823. this.contentEl_.appendChild(createEl('span', {
  12824. className: 'vjs-control-text',
  12825. textContent: this.localize('Stream Type') + "\xA0"
  12826. }));
  12827. this.contentEl_.appendChild(document.createTextNode(this.localize('LIVE')));
  12828. el.appendChild(this.contentEl_);
  12829. return el;
  12830. };
  12831. _proto.dispose = function dispose() {
  12832. this.contentEl_ = null;
  12833. _Component.prototype.dispose.call(this);
  12834. }
  12835. /**
  12836. * Check the duration to see if the LiveDisplay should be showing or not. Then show/hide
  12837. * it accordingly
  12838. *
  12839. * @param {EventTarget~Event} [event]
  12840. * The {@link Player#durationchange} event that caused this function to run.
  12841. *
  12842. * @listens Player#durationchange
  12843. */
  12844. ;
  12845. _proto.updateShowing = function updateShowing(event) {
  12846. if (this.player().duration() === Infinity) {
  12847. this.show();
  12848. } else {
  12849. this.hide();
  12850. }
  12851. };
  12852. return LiveDisplay;
  12853. }(Component$1);
  12854. Component$1.registerComponent('LiveDisplay', LiveDisplay);
  12855. /**
  12856. * Displays the live indicator when duration is Infinity.
  12857. *
  12858. * @extends Component
  12859. */
  12860. var SeekToLive = /*#__PURE__*/function (_Button) {
  12861. inheritsLoose(SeekToLive, _Button);
  12862. /**
  12863. * Creates an instance of this class.
  12864. *
  12865. * @param {Player} player
  12866. * The `Player` that this class should be attached to.
  12867. *
  12868. * @param {Object} [options]
  12869. * The key/value store of player options.
  12870. */
  12871. function SeekToLive(player, options) {
  12872. var _this;
  12873. _this = _Button.call(this, player, options) || this;
  12874. _this.updateLiveEdgeStatus();
  12875. if (_this.player_.liveTracker) {
  12876. _this.updateLiveEdgeStatusHandler_ = function (e) {
  12877. return _this.updateLiveEdgeStatus(e);
  12878. };
  12879. _this.on(_this.player_.liveTracker, 'liveedgechange', _this.updateLiveEdgeStatusHandler_);
  12880. }
  12881. return _this;
  12882. }
  12883. /**
  12884. * Create the `Component`'s DOM element
  12885. *
  12886. * @return {Element}
  12887. * The element that was created.
  12888. */
  12889. var _proto = SeekToLive.prototype;
  12890. _proto.createEl = function createEl$1() {
  12891. var el = _Button.prototype.createEl.call(this, 'button', {
  12892. className: 'vjs-seek-to-live-control vjs-control'
  12893. });
  12894. this.textEl_ = createEl('span', {
  12895. className: 'vjs-seek-to-live-text',
  12896. textContent: this.localize('LIVE')
  12897. }, {
  12898. 'aria-hidden': 'true'
  12899. });
  12900. el.appendChild(this.textEl_);
  12901. return el;
  12902. }
  12903. /**
  12904. * Update the state of this button if we are at the live edge
  12905. * or not
  12906. */
  12907. ;
  12908. _proto.updateLiveEdgeStatus = function updateLiveEdgeStatus() {
  12909. // default to live edge
  12910. if (!this.player_.liveTracker || this.player_.liveTracker.atLiveEdge()) {
  12911. this.setAttribute('aria-disabled', true);
  12912. this.addClass('vjs-at-live-edge');
  12913. this.controlText('Seek to live, currently playing live');
  12914. } else {
  12915. this.setAttribute('aria-disabled', false);
  12916. this.removeClass('vjs-at-live-edge');
  12917. this.controlText('Seek to live, currently behind live');
  12918. }
  12919. }
  12920. /**
  12921. * On click bring us as near to the live point as possible.
  12922. * This requires that we wait for the next `live-seekable-change`
  12923. * event which will happen every segment length seconds.
  12924. */
  12925. ;
  12926. _proto.handleClick = function handleClick() {
  12927. this.player_.liveTracker.seekToLiveEdge();
  12928. }
  12929. /**
  12930. * Dispose of the element and stop tracking
  12931. */
  12932. ;
  12933. _proto.dispose = function dispose() {
  12934. if (this.player_.liveTracker) {
  12935. this.off(this.player_.liveTracker, 'liveedgechange', this.updateLiveEdgeStatusHandler_);
  12936. }
  12937. this.textEl_ = null;
  12938. _Button.prototype.dispose.call(this);
  12939. };
  12940. return SeekToLive;
  12941. }(Button);
  12942. SeekToLive.prototype.controlText_ = 'Seek to live, currently playing live';
  12943. Component$1.registerComponent('SeekToLive', SeekToLive);
  12944. /**
  12945. * Keep a number between a min and a max value
  12946. *
  12947. * @param {number} number
  12948. * The number to clamp
  12949. *
  12950. * @param {number} min
  12951. * The minimum value
  12952. * @param {number} max
  12953. * The maximum value
  12954. *
  12955. * @return {number}
  12956. * the clamped number
  12957. */
  12958. var clamp = function clamp(number, min, max) {
  12959. number = Number(number);
  12960. return Math.min(max, Math.max(min, isNaN(number) ? min : number));
  12961. };
  12962. /**
  12963. * The base functionality for a slider. Can be vertical or horizontal.
  12964. * For instance the volume bar or the seek bar on a video is a slider.
  12965. *
  12966. * @extends Component
  12967. */
  12968. var Slider = /*#__PURE__*/function (_Component) {
  12969. inheritsLoose(Slider, _Component);
  12970. /**
  12971. * Create an instance of this class
  12972. *
  12973. * @param {Player} player
  12974. * The `Player` that this class should be attached to.
  12975. *
  12976. * @param {Object} [options]
  12977. * The key/value store of player options.
  12978. */
  12979. function Slider(player, options) {
  12980. var _this;
  12981. _this = _Component.call(this, player, options) || this;
  12982. _this.handleMouseDown_ = function (e) {
  12983. return _this.handleMouseDown(e);
  12984. };
  12985. _this.handleMouseUp_ = function (e) {
  12986. return _this.handleMouseUp(e);
  12987. };
  12988. _this.handleKeyDown_ = function (e) {
  12989. return _this.handleKeyDown(e);
  12990. };
  12991. _this.handleClick_ = function (e) {
  12992. return _this.handleClick(e);
  12993. };
  12994. _this.handleMouseMove_ = function (e) {
  12995. return _this.handleMouseMove(e);
  12996. };
  12997. _this.update_ = function (e) {
  12998. return _this.update(e);
  12999. }; // Set property names to bar to match with the child Slider class is looking for
  13000. _this.bar = _this.getChild(_this.options_.barName); // Set a horizontal or vertical class on the slider depending on the slider type
  13001. _this.vertical(!!_this.options_.vertical);
  13002. _this.enable();
  13003. return _this;
  13004. }
  13005. /**
  13006. * Are controls are currently enabled for this slider or not.
  13007. *
  13008. * @return {boolean}
  13009. * true if controls are enabled, false otherwise
  13010. */
  13011. var _proto = Slider.prototype;
  13012. _proto.enabled = function enabled() {
  13013. return this.enabled_;
  13014. }
  13015. /**
  13016. * Enable controls for this slider if they are disabled
  13017. */
  13018. ;
  13019. _proto.enable = function enable() {
  13020. if (this.enabled()) {
  13021. return;
  13022. }
  13023. this.on('mousedown', this.handleMouseDown_);
  13024. this.on('touchstart', this.handleMouseDown_);
  13025. this.on('keydown', this.handleKeyDown_);
  13026. this.on('click', this.handleClick_); // TODO: deprecated, controlsvisible does not seem to be fired
  13027. this.on(this.player_, 'controlsvisible', this.update);
  13028. if (this.playerEvent) {
  13029. this.on(this.player_, this.playerEvent, this.update);
  13030. }
  13031. this.removeClass('disabled');
  13032. this.setAttribute('tabindex', 0);
  13033. this.enabled_ = true;
  13034. }
  13035. /**
  13036. * Disable controls for this slider if they are enabled
  13037. */
  13038. ;
  13039. _proto.disable = function disable() {
  13040. if (!this.enabled()) {
  13041. return;
  13042. }
  13043. var doc = this.bar.el_.ownerDocument;
  13044. this.off('mousedown', this.handleMouseDown_);
  13045. this.off('touchstart', this.handleMouseDown_);
  13046. this.off('keydown', this.handleKeyDown_);
  13047. this.off('click', this.handleClick_);
  13048. this.off(this.player_, 'controlsvisible', this.update_);
  13049. this.off(doc, 'mousemove', this.handleMouseMove_);
  13050. this.off(doc, 'mouseup', this.handleMouseUp_);
  13051. this.off(doc, 'touchmove', this.handleMouseMove_);
  13052. this.off(doc, 'touchend', this.handleMouseUp_);
  13053. this.removeAttribute('tabindex');
  13054. this.addClass('disabled');
  13055. if (this.playerEvent) {
  13056. this.off(this.player_, this.playerEvent, this.update);
  13057. }
  13058. this.enabled_ = false;
  13059. }
  13060. /**
  13061. * Create the `Slider`s DOM element.
  13062. *
  13063. * @param {string} type
  13064. * Type of element to create.
  13065. *
  13066. * @param {Object} [props={}]
  13067. * List of properties in Object form.
  13068. *
  13069. * @param {Object} [attributes={}]
  13070. * list of attributes in Object form.
  13071. *
  13072. * @return {Element}
  13073. * The element that gets created.
  13074. */
  13075. ;
  13076. _proto.createEl = function createEl(type, props, attributes) {
  13077. if (props === void 0) {
  13078. props = {};
  13079. }
  13080. if (attributes === void 0) {
  13081. attributes = {};
  13082. }
  13083. // Add the slider element class to all sub classes
  13084. props.className = props.className + ' vjs-slider';
  13085. props = assign$1({
  13086. tabIndex: 0
  13087. }, props);
  13088. attributes = assign$1({
  13089. 'role': 'slider',
  13090. 'aria-valuenow': 0,
  13091. 'aria-valuemin': 0,
  13092. 'aria-valuemax': 100,
  13093. 'tabIndex': 0
  13094. }, attributes);
  13095. return _Component.prototype.createEl.call(this, type, props, attributes);
  13096. }
  13097. /**
  13098. * Handle `mousedown` or `touchstart` events on the `Slider`.
  13099. *
  13100. * @param {EventTarget~Event} event
  13101. * `mousedown` or `touchstart` event that triggered this function
  13102. *
  13103. * @listens mousedown
  13104. * @listens touchstart
  13105. * @fires Slider#slideractive
  13106. */
  13107. ;
  13108. _proto.handleMouseDown = function handleMouseDown(event) {
  13109. var doc = this.bar.el_.ownerDocument;
  13110. if (event.type === 'mousedown') {
  13111. event.preventDefault();
  13112. } // Do not call preventDefault() on touchstart in Chrome
  13113. // to avoid console warnings. Use a 'touch-action: none' style
  13114. // instead to prevent unintented scrolling.
  13115. // https://developers.google.com/web/updates/2017/01/scrolling-intervention
  13116. if (event.type === 'touchstart' && !IS_CHROME) {
  13117. event.preventDefault();
  13118. }
  13119. blockTextSelection();
  13120. this.addClass('vjs-sliding');
  13121. /**
  13122. * Triggered when the slider is in an active state
  13123. *
  13124. * @event Slider#slideractive
  13125. * @type {EventTarget~Event}
  13126. */
  13127. this.trigger('slideractive');
  13128. this.on(doc, 'mousemove', this.handleMouseMove_);
  13129. this.on(doc, 'mouseup', this.handleMouseUp_);
  13130. this.on(doc, 'touchmove', this.handleMouseMove_);
  13131. this.on(doc, 'touchend', this.handleMouseUp_);
  13132. this.handleMouseMove(event, true);
  13133. }
  13134. /**
  13135. * Handle the `mousemove`, `touchmove`, and `mousedown` events on this `Slider`.
  13136. * The `mousemove` and `touchmove` events will only only trigger this function during
  13137. * `mousedown` and `touchstart`. This is due to {@link Slider#handleMouseDown} and
  13138. * {@link Slider#handleMouseUp}.
  13139. *
  13140. * @param {EventTarget~Event} event
  13141. * `mousedown`, `mousemove`, `touchstart`, or `touchmove` event that triggered
  13142. * this function
  13143. * @param {boolean} mouseDown this is a flag that should be set to true if `handleMouseMove` is called directly. It allows us to skip things that should not happen if coming from mouse down but should happen on regular mouse move handler. Defaults to false.
  13144. *
  13145. * @listens mousemove
  13146. * @listens touchmove
  13147. */
  13148. ;
  13149. _proto.handleMouseMove = function handleMouseMove(event) {}
  13150. /**
  13151. * Handle `mouseup` or `touchend` events on the `Slider`.
  13152. *
  13153. * @param {EventTarget~Event} event
  13154. * `mouseup` or `touchend` event that triggered this function.
  13155. *
  13156. * @listens touchend
  13157. * @listens mouseup
  13158. * @fires Slider#sliderinactive
  13159. */
  13160. ;
  13161. _proto.handleMouseUp = function handleMouseUp() {
  13162. var doc = this.bar.el_.ownerDocument;
  13163. unblockTextSelection();
  13164. this.removeClass('vjs-sliding');
  13165. /**
  13166. * Triggered when the slider is no longer in an active state.
  13167. *
  13168. * @event Slider#sliderinactive
  13169. * @type {EventTarget~Event}
  13170. */
  13171. this.trigger('sliderinactive');
  13172. this.off(doc, 'mousemove', this.handleMouseMove_);
  13173. this.off(doc, 'mouseup', this.handleMouseUp_);
  13174. this.off(doc, 'touchmove', this.handleMouseMove_);
  13175. this.off(doc, 'touchend', this.handleMouseUp_);
  13176. this.update();
  13177. }
  13178. /**
  13179. * Update the progress bar of the `Slider`.
  13180. *
  13181. * @return {number}
  13182. * The percentage of progress the progress bar represents as a
  13183. * number from 0 to 1.
  13184. */
  13185. ;
  13186. _proto.update = function update() {
  13187. var _this2 = this;
  13188. // In VolumeBar init we have a setTimeout for update that pops and update
  13189. // to the end of the execution stack. The player is destroyed before then
  13190. // update will cause an error
  13191. // If there's no bar...
  13192. if (!this.el_ || !this.bar) {
  13193. return;
  13194. } // clamp progress between 0 and 1
  13195. // and only round to four decimal places, as we round to two below
  13196. var progress = this.getProgress();
  13197. if (progress === this.progress_) {
  13198. return progress;
  13199. }
  13200. this.progress_ = progress;
  13201. this.requestNamedAnimationFrame('Slider#update', function () {
  13202. // Set the new bar width or height
  13203. var sizeKey = _this2.vertical() ? 'height' : 'width'; // Convert to a percentage for css value
  13204. _this2.bar.el().style[sizeKey] = (progress * 100).toFixed(2) + '%';
  13205. });
  13206. return progress;
  13207. }
  13208. /**
  13209. * Get the percentage of the bar that should be filled
  13210. * but clamped and rounded.
  13211. *
  13212. * @return {number}
  13213. * percentage filled that the slider is
  13214. */
  13215. ;
  13216. _proto.getProgress = function getProgress() {
  13217. return Number(clamp(this.getPercent(), 0, 1).toFixed(4));
  13218. }
  13219. /**
  13220. * Calculate distance for slider
  13221. *
  13222. * @param {EventTarget~Event} event
  13223. * The event that caused this function to run.
  13224. *
  13225. * @return {number}
  13226. * The current position of the Slider.
  13227. * - position.x for vertical `Slider`s
  13228. * - position.y for horizontal `Slider`s
  13229. */
  13230. ;
  13231. _proto.calculateDistance = function calculateDistance(event) {
  13232. var position = getPointerPosition(this.el_, event);
  13233. if (this.vertical()) {
  13234. return position.y;
  13235. }
  13236. return position.x;
  13237. }
  13238. /**
  13239. * Handle a `keydown` event on the `Slider`. Watches for left, rigth, up, and down
  13240. * arrow keys. This function will only be called when the slider has focus. See
  13241. * {@link Slider#handleFocus} and {@link Slider#handleBlur}.
  13242. *
  13243. * @param {EventTarget~Event} event
  13244. * the `keydown` event that caused this function to run.
  13245. *
  13246. * @listens keydown
  13247. */
  13248. ;
  13249. _proto.handleKeyDown = function handleKeyDown(event) {
  13250. // Left and Down Arrows
  13251. if (keycode.isEventKey(event, 'Left') || keycode.isEventKey(event, 'Down')) {
  13252. event.preventDefault();
  13253. event.stopPropagation();
  13254. this.stepBack(); // Up and Right Arrows
  13255. } else if (keycode.isEventKey(event, 'Right') || keycode.isEventKey(event, 'Up')) {
  13256. event.preventDefault();
  13257. event.stopPropagation();
  13258. this.stepForward();
  13259. } else {
  13260. // Pass keydown handling up for unsupported keys
  13261. _Component.prototype.handleKeyDown.call(this, event);
  13262. }
  13263. }
  13264. /**
  13265. * Listener for click events on slider, used to prevent clicks
  13266. * from bubbling up to parent elements like button menus.
  13267. *
  13268. * @param {Object} event
  13269. * Event that caused this object to run
  13270. */
  13271. ;
  13272. _proto.handleClick = function handleClick(event) {
  13273. event.stopPropagation();
  13274. event.preventDefault();
  13275. }
  13276. /**
  13277. * Get/set if slider is horizontal for vertical
  13278. *
  13279. * @param {boolean} [bool]
  13280. * - true if slider is vertical,
  13281. * - false is horizontal
  13282. *
  13283. * @return {boolean}
  13284. * - true if slider is vertical, and getting
  13285. * - false if the slider is horizontal, and getting
  13286. */
  13287. ;
  13288. _proto.vertical = function vertical(bool) {
  13289. if (bool === undefined) {
  13290. return this.vertical_ || false;
  13291. }
  13292. this.vertical_ = !!bool;
  13293. if (this.vertical_) {
  13294. this.addClass('vjs-slider-vertical');
  13295. } else {
  13296. this.addClass('vjs-slider-horizontal');
  13297. }
  13298. };
  13299. return Slider;
  13300. }(Component$1);
  13301. Component$1.registerComponent('Slider', Slider);
  13302. var percentify = function percentify(time, end) {
  13303. return clamp(time / end * 100, 0, 100).toFixed(2) + '%';
  13304. };
  13305. /**
  13306. * Shows loading progress
  13307. *
  13308. * @extends Component
  13309. */
  13310. var LoadProgressBar = /*#__PURE__*/function (_Component) {
  13311. inheritsLoose(LoadProgressBar, _Component);
  13312. /**
  13313. * Creates an instance of this class.
  13314. *
  13315. * @param {Player} player
  13316. * The `Player` that this class should be attached to.
  13317. *
  13318. * @param {Object} [options]
  13319. * The key/value store of player options.
  13320. */
  13321. function LoadProgressBar(player, options) {
  13322. var _this;
  13323. _this = _Component.call(this, player, options) || this;
  13324. _this.partEls_ = [];
  13325. _this.on(player, 'progress', function (e) {
  13326. return _this.update(e);
  13327. });
  13328. return _this;
  13329. }
  13330. /**
  13331. * Create the `Component`'s DOM element
  13332. *
  13333. * @return {Element}
  13334. * The element that was created.
  13335. */
  13336. var _proto = LoadProgressBar.prototype;
  13337. _proto.createEl = function createEl$1() {
  13338. var el = _Component.prototype.createEl.call(this, 'div', {
  13339. className: 'vjs-load-progress'
  13340. });
  13341. var wrapper = createEl('span', {
  13342. className: 'vjs-control-text'
  13343. });
  13344. var loadedText = createEl('span', {
  13345. textContent: this.localize('Loaded')
  13346. });
  13347. var separator = document.createTextNode(': ');
  13348. this.percentageEl_ = createEl('span', {
  13349. className: 'vjs-control-text-loaded-percentage',
  13350. textContent: '0%'
  13351. });
  13352. el.appendChild(wrapper);
  13353. wrapper.appendChild(loadedText);
  13354. wrapper.appendChild(separator);
  13355. wrapper.appendChild(this.percentageEl_);
  13356. return el;
  13357. };
  13358. _proto.dispose = function dispose() {
  13359. this.partEls_ = null;
  13360. this.percentageEl_ = null;
  13361. _Component.prototype.dispose.call(this);
  13362. }
  13363. /**
  13364. * Update progress bar
  13365. *
  13366. * @param {EventTarget~Event} [event]
  13367. * The `progress` event that caused this function to run.
  13368. *
  13369. * @listens Player#progress
  13370. */
  13371. ;
  13372. _proto.update = function update(event) {
  13373. var _this2 = this;
  13374. this.requestNamedAnimationFrame('LoadProgressBar#update', function () {
  13375. var liveTracker = _this2.player_.liveTracker;
  13376. var buffered = _this2.player_.buffered();
  13377. var duration = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : _this2.player_.duration();
  13378. var bufferedEnd = _this2.player_.bufferedEnd();
  13379. var children = _this2.partEls_;
  13380. var percent = percentify(bufferedEnd, duration);
  13381. if (_this2.percent_ !== percent) {
  13382. // update the width of the progress bar
  13383. _this2.el_.style.width = percent; // update the control-text
  13384. textContent(_this2.percentageEl_, percent);
  13385. _this2.percent_ = percent;
  13386. } // add child elements to represent the individual buffered time ranges
  13387. for (var i = 0; i < buffered.length; i++) {
  13388. var start = buffered.start(i);
  13389. var end = buffered.end(i);
  13390. var part = children[i];
  13391. if (!part) {
  13392. part = _this2.el_.appendChild(createEl());
  13393. children[i] = part;
  13394. } // only update if changed
  13395. if (part.dataset.start === start && part.dataset.end === end) {
  13396. continue;
  13397. }
  13398. part.dataset.start = start;
  13399. part.dataset.end = end; // set the percent based on the width of the progress bar (bufferedEnd)
  13400. part.style.left = percentify(start, bufferedEnd);
  13401. part.style.width = percentify(end - start, bufferedEnd);
  13402. } // remove unused buffered range elements
  13403. for (var _i = children.length; _i > buffered.length; _i--) {
  13404. _this2.el_.removeChild(children[_i - 1]);
  13405. }
  13406. children.length = buffered.length;
  13407. });
  13408. };
  13409. return LoadProgressBar;
  13410. }(Component$1);
  13411. Component$1.registerComponent('LoadProgressBar', LoadProgressBar);
  13412. /**
  13413. * Time tooltips display a time above the progress bar.
  13414. *
  13415. * @extends Component
  13416. */
  13417. var TimeTooltip = /*#__PURE__*/function (_Component) {
  13418. inheritsLoose(TimeTooltip, _Component);
  13419. /**
  13420. * Creates an instance of this class.
  13421. *
  13422. * @param {Player} player
  13423. * The {@link Player} that this class should be attached to.
  13424. *
  13425. * @param {Object} [options]
  13426. * The key/value store of player options.
  13427. */
  13428. function TimeTooltip(player, options) {
  13429. var _this;
  13430. _this = _Component.call(this, player, options) || this;
  13431. _this.update = throttle(bind(assertThisInitialized(_this), _this.update), UPDATE_REFRESH_INTERVAL);
  13432. return _this;
  13433. }
  13434. /**
  13435. * Create the time tooltip DOM element
  13436. *
  13437. * @return {Element}
  13438. * The element that was created.
  13439. */
  13440. var _proto = TimeTooltip.prototype;
  13441. _proto.createEl = function createEl() {
  13442. return _Component.prototype.createEl.call(this, 'div', {
  13443. className: 'vjs-time-tooltip'
  13444. }, {
  13445. 'aria-hidden': 'true'
  13446. });
  13447. }
  13448. /**
  13449. * Updates the position of the time tooltip relative to the `SeekBar`.
  13450. *
  13451. * @param {Object} seekBarRect
  13452. * The `ClientRect` for the {@link SeekBar} element.
  13453. *
  13454. * @param {number} seekBarPoint
  13455. * A number from 0 to 1, representing a horizontal reference point
  13456. * from the left edge of the {@link SeekBar}
  13457. */
  13458. ;
  13459. _proto.update = function update(seekBarRect, seekBarPoint, content) {
  13460. var tooltipRect = findPosition(this.el_);
  13461. var playerRect = getBoundingClientRect(this.player_.el());
  13462. var seekBarPointPx = seekBarRect.width * seekBarPoint; // do nothing if either rect isn't available
  13463. // for example, if the player isn't in the DOM for testing
  13464. if (!playerRect || !tooltipRect) {
  13465. return;
  13466. } // This is the space left of the `seekBarPoint` available within the bounds
  13467. // of the player. We calculate any gap between the left edge of the player
  13468. // and the left edge of the `SeekBar` and add the number of pixels in the
  13469. // `SeekBar` before hitting the `seekBarPoint`
  13470. var spaceLeftOfPoint = seekBarRect.left - playerRect.left + seekBarPointPx; // This is the space right of the `seekBarPoint` available within the bounds
  13471. // of the player. We calculate the number of pixels from the `seekBarPoint`
  13472. // to the right edge of the `SeekBar` and add to that any gap between the
  13473. // right edge of the `SeekBar` and the player.
  13474. var spaceRightOfPoint = seekBarRect.width - seekBarPointPx + (playerRect.right - seekBarRect.right); // This is the number of pixels by which the tooltip will need to be pulled
  13475. // further to the right to center it over the `seekBarPoint`.
  13476. var pullTooltipBy = tooltipRect.width / 2; // Adjust the `pullTooltipBy` distance to the left or right depending on
  13477. // the results of the space calculations above.
  13478. if (spaceLeftOfPoint < pullTooltipBy) {
  13479. pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
  13480. } else if (spaceRightOfPoint < pullTooltipBy) {
  13481. pullTooltipBy = spaceRightOfPoint;
  13482. } // Due to the imprecision of decimal/ratio based calculations and varying
  13483. // rounding behaviors, there are cases where the spacing adjustment is off
  13484. // by a pixel or two. This adds insurance to these calculations.
  13485. if (pullTooltipBy < 0) {
  13486. pullTooltipBy = 0;
  13487. } else if (pullTooltipBy > tooltipRect.width) {
  13488. pullTooltipBy = tooltipRect.width;
  13489. } // prevent small width fluctuations within 0.4px from
  13490. // changing the value below.
  13491. // This really helps for live to prevent the play
  13492. // progress time tooltip from jittering
  13493. pullTooltipBy = Math.round(pullTooltipBy);
  13494. this.el_.style.right = "-" + pullTooltipBy + "px";
  13495. this.write(content);
  13496. }
  13497. /**
  13498. * Write the time to the tooltip DOM element.
  13499. *
  13500. * @param {string} content
  13501. * The formatted time for the tooltip.
  13502. */
  13503. ;
  13504. _proto.write = function write(content) {
  13505. textContent(this.el_, content);
  13506. }
  13507. /**
  13508. * Updates the position of the time tooltip relative to the `SeekBar`.
  13509. *
  13510. * @param {Object} seekBarRect
  13511. * The `ClientRect` for the {@link SeekBar} element.
  13512. *
  13513. * @param {number} seekBarPoint
  13514. * A number from 0 to 1, representing a horizontal reference point
  13515. * from the left edge of the {@link SeekBar}
  13516. *
  13517. * @param {number} time
  13518. * The time to update the tooltip to, not used during live playback
  13519. *
  13520. * @param {Function} cb
  13521. * A function that will be called during the request animation frame
  13522. * for tooltips that need to do additional animations from the default
  13523. */
  13524. ;
  13525. _proto.updateTime = function updateTime(seekBarRect, seekBarPoint, time, cb) {
  13526. var _this2 = this;
  13527. this.requestNamedAnimationFrame('TimeTooltip#updateTime', function () {
  13528. var content;
  13529. var duration = _this2.player_.duration();
  13530. if (_this2.player_.liveTracker && _this2.player_.liveTracker.isLive()) {
  13531. var liveWindow = _this2.player_.liveTracker.liveWindow();
  13532. var secondsBehind = liveWindow - seekBarPoint * liveWindow;
  13533. content = (secondsBehind < 1 ? '' : '-') + formatTime(secondsBehind, liveWindow);
  13534. } else {
  13535. content = formatTime(time, duration);
  13536. }
  13537. _this2.update(seekBarRect, seekBarPoint, content);
  13538. if (cb) {
  13539. cb();
  13540. }
  13541. });
  13542. };
  13543. return TimeTooltip;
  13544. }(Component$1);
  13545. Component$1.registerComponent('TimeTooltip', TimeTooltip);
  13546. /**
  13547. * Used by {@link SeekBar} to display media playback progress as part of the
  13548. * {@link ProgressControl}.
  13549. *
  13550. * @extends Component
  13551. */
  13552. var PlayProgressBar = /*#__PURE__*/function (_Component) {
  13553. inheritsLoose(PlayProgressBar, _Component);
  13554. /**
  13555. * Creates an instance of this class.
  13556. *
  13557. * @param {Player} player
  13558. * The {@link Player} that this class should be attached to.
  13559. *
  13560. * @param {Object} [options]
  13561. * The key/value store of player options.
  13562. */
  13563. function PlayProgressBar(player, options) {
  13564. var _this;
  13565. _this = _Component.call(this, player, options) || this;
  13566. _this.update = throttle(bind(assertThisInitialized(_this), _this.update), UPDATE_REFRESH_INTERVAL);
  13567. return _this;
  13568. }
  13569. /**
  13570. * Create the the DOM element for this class.
  13571. *
  13572. * @return {Element}
  13573. * The element that was created.
  13574. */
  13575. var _proto = PlayProgressBar.prototype;
  13576. _proto.createEl = function createEl() {
  13577. return _Component.prototype.createEl.call(this, 'div', {
  13578. className: 'vjs-play-progress vjs-slider-bar'
  13579. }, {
  13580. 'aria-hidden': 'true'
  13581. });
  13582. }
  13583. /**
  13584. * Enqueues updates to its own DOM as well as the DOM of its
  13585. * {@link TimeTooltip} child.
  13586. *
  13587. * @param {Object} seekBarRect
  13588. * The `ClientRect` for the {@link SeekBar} element.
  13589. *
  13590. * @param {number} seekBarPoint
  13591. * A number from 0 to 1, representing a horizontal reference point
  13592. * from the left edge of the {@link SeekBar}
  13593. */
  13594. ;
  13595. _proto.update = function update(seekBarRect, seekBarPoint) {
  13596. var timeTooltip = this.getChild('timeTooltip');
  13597. if (!timeTooltip) {
  13598. return;
  13599. }
  13600. var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  13601. timeTooltip.updateTime(seekBarRect, seekBarPoint, time);
  13602. };
  13603. return PlayProgressBar;
  13604. }(Component$1);
  13605. /**
  13606. * Default options for {@link PlayProgressBar}.
  13607. *
  13608. * @type {Object}
  13609. * @private
  13610. */
  13611. PlayProgressBar.prototype.options_ = {
  13612. children: []
  13613. }; // Time tooltips should not be added to a player on mobile devices
  13614. if (!IS_IOS && !IS_ANDROID) {
  13615. PlayProgressBar.prototype.options_.children.push('timeTooltip');
  13616. }
  13617. Component$1.registerComponent('PlayProgressBar', PlayProgressBar);
  13618. /**
  13619. * The {@link MouseTimeDisplay} component tracks mouse movement over the
  13620. * {@link ProgressControl}. It displays an indicator and a {@link TimeTooltip}
  13621. * indicating the time which is represented by a given point in the
  13622. * {@link ProgressControl}.
  13623. *
  13624. * @extends Component
  13625. */
  13626. var MouseTimeDisplay = /*#__PURE__*/function (_Component) {
  13627. inheritsLoose(MouseTimeDisplay, _Component);
  13628. /**
  13629. * Creates an instance of this class.
  13630. *
  13631. * @param {Player} player
  13632. * The {@link Player} that this class should be attached to.
  13633. *
  13634. * @param {Object} [options]
  13635. * The key/value store of player options.
  13636. */
  13637. function MouseTimeDisplay(player, options) {
  13638. var _this;
  13639. _this = _Component.call(this, player, options) || this;
  13640. _this.update = throttle(bind(assertThisInitialized(_this), _this.update), UPDATE_REFRESH_INTERVAL);
  13641. return _this;
  13642. }
  13643. /**
  13644. * Create the DOM element for this class.
  13645. *
  13646. * @return {Element}
  13647. * The element that was created.
  13648. */
  13649. var _proto = MouseTimeDisplay.prototype;
  13650. _proto.createEl = function createEl() {
  13651. return _Component.prototype.createEl.call(this, 'div', {
  13652. className: 'vjs-mouse-display'
  13653. });
  13654. }
  13655. /**
  13656. * Enqueues updates to its own DOM as well as the DOM of its
  13657. * {@link TimeTooltip} child.
  13658. *
  13659. * @param {Object} seekBarRect
  13660. * The `ClientRect` for the {@link SeekBar} element.
  13661. *
  13662. * @param {number} seekBarPoint
  13663. * A number from 0 to 1, representing a horizontal reference point
  13664. * from the left edge of the {@link SeekBar}
  13665. */
  13666. ;
  13667. _proto.update = function update(seekBarRect, seekBarPoint) {
  13668. var _this2 = this;
  13669. var time = seekBarPoint * this.player_.duration();
  13670. this.getChild('timeTooltip').updateTime(seekBarRect, seekBarPoint, time, function () {
  13671. _this2.el_.style.left = seekBarRect.width * seekBarPoint + "px";
  13672. });
  13673. };
  13674. return MouseTimeDisplay;
  13675. }(Component$1);
  13676. /**
  13677. * Default options for `MouseTimeDisplay`
  13678. *
  13679. * @type {Object}
  13680. * @private
  13681. */
  13682. MouseTimeDisplay.prototype.options_ = {
  13683. children: ['timeTooltip']
  13684. };
  13685. Component$1.registerComponent('MouseTimeDisplay', MouseTimeDisplay);
  13686. var STEP_SECONDS = 5; // The multiplier of STEP_SECONDS that PgUp/PgDown move the timeline.
  13687. var PAGE_KEY_MULTIPLIER = 12;
  13688. /**
  13689. * Seek bar and container for the progress bars. Uses {@link PlayProgressBar}
  13690. * as its `bar`.
  13691. *
  13692. * @extends Slider
  13693. */
  13694. var SeekBar = /*#__PURE__*/function (_Slider) {
  13695. inheritsLoose(SeekBar, _Slider);
  13696. /**
  13697. * Creates an instance of this class.
  13698. *
  13699. * @param {Player} player
  13700. * The `Player` that this class should be attached to.
  13701. *
  13702. * @param {Object} [options]
  13703. * The key/value store of player options.
  13704. */
  13705. function SeekBar(player, options) {
  13706. var _this;
  13707. _this = _Slider.call(this, player, options) || this;
  13708. _this.setEventHandlers_();
  13709. return _this;
  13710. }
  13711. /**
  13712. * Sets the event handlers
  13713. *
  13714. * @private
  13715. */
  13716. var _proto = SeekBar.prototype;
  13717. _proto.setEventHandlers_ = function setEventHandlers_() {
  13718. var _this2 = this;
  13719. this.update_ = bind(this, this.update);
  13720. this.update = throttle(this.update_, UPDATE_REFRESH_INTERVAL);
  13721. this.on(this.player_, ['ended', 'durationchange', 'timeupdate'], this.update);
  13722. if (this.player_.liveTracker) {
  13723. this.on(this.player_.liveTracker, 'liveedgechange', this.update);
  13724. } // when playing, let's ensure we smoothly update the play progress bar
  13725. // via an interval
  13726. this.updateInterval = null;
  13727. this.enableIntervalHandler_ = function (e) {
  13728. return _this2.enableInterval_(e);
  13729. };
  13730. this.disableIntervalHandler_ = function (e) {
  13731. return _this2.disableInterval_(e);
  13732. };
  13733. this.on(this.player_, ['playing'], this.enableIntervalHandler_);
  13734. this.on(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_); // we don't need to update the play progress if the document is hidden,
  13735. // also, this causes the CPU to spike and eventually crash the page on IE11.
  13736. if ('hidden' in document && 'visibilityState' in document) {
  13737. this.on(document, 'visibilitychange', this.toggleVisibility_);
  13738. }
  13739. };
  13740. _proto.toggleVisibility_ = function toggleVisibility_(e) {
  13741. if (document.visibilityState === 'hidden') {
  13742. this.cancelNamedAnimationFrame('SeekBar#update');
  13743. this.cancelNamedAnimationFrame('Slider#update');
  13744. this.disableInterval_(e);
  13745. } else {
  13746. if (!this.player_.ended() && !this.player_.paused()) {
  13747. this.enableInterval_();
  13748. } // we just switched back to the page and someone may be looking, so, update ASAP
  13749. this.update();
  13750. }
  13751. };
  13752. _proto.enableInterval_ = function enableInterval_() {
  13753. if (this.updateInterval) {
  13754. return;
  13755. }
  13756. this.updateInterval = this.setInterval(this.update, UPDATE_REFRESH_INTERVAL);
  13757. };
  13758. _proto.disableInterval_ = function disableInterval_(e) {
  13759. if (this.player_.liveTracker && this.player_.liveTracker.isLive() && e && e.type !== 'ended') {
  13760. return;
  13761. }
  13762. if (!this.updateInterval) {
  13763. return;
  13764. }
  13765. this.clearInterval(this.updateInterval);
  13766. this.updateInterval = null;
  13767. }
  13768. /**
  13769. * Create the `Component`'s DOM element
  13770. *
  13771. * @return {Element}
  13772. * The element that was created.
  13773. */
  13774. ;
  13775. _proto.createEl = function createEl() {
  13776. return _Slider.prototype.createEl.call(this, 'div', {
  13777. className: 'vjs-progress-holder'
  13778. }, {
  13779. 'aria-label': this.localize('Progress Bar')
  13780. });
  13781. }
  13782. /**
  13783. * This function updates the play progress bar and accessibility
  13784. * attributes to whatever is passed in.
  13785. *
  13786. * @param {EventTarget~Event} [event]
  13787. * The `timeupdate` or `ended` event that caused this to run.
  13788. *
  13789. * @listens Player#timeupdate
  13790. *
  13791. * @return {number}
  13792. * The current percent at a number from 0-1
  13793. */
  13794. ;
  13795. _proto.update = function update(event) {
  13796. var _this3 = this;
  13797. // ignore updates while the tab is hidden
  13798. if (document.visibilityState === 'hidden') {
  13799. return;
  13800. }
  13801. var percent = _Slider.prototype.update.call(this);
  13802. this.requestNamedAnimationFrame('SeekBar#update', function () {
  13803. var currentTime = _this3.player_.ended() ? _this3.player_.duration() : _this3.getCurrentTime_();
  13804. var liveTracker = _this3.player_.liveTracker;
  13805. var duration = _this3.player_.duration();
  13806. if (liveTracker && liveTracker.isLive()) {
  13807. duration = _this3.player_.liveTracker.liveCurrentTime();
  13808. }
  13809. if (_this3.percent_ !== percent) {
  13810. // machine readable value of progress bar (percentage complete)
  13811. _this3.el_.setAttribute('aria-valuenow', (percent * 100).toFixed(2));
  13812. _this3.percent_ = percent;
  13813. }
  13814. if (_this3.currentTime_ !== currentTime || _this3.duration_ !== duration) {
  13815. // human readable value of progress bar (time complete)
  13816. _this3.el_.setAttribute('aria-valuetext', _this3.localize('progress bar timing: currentTime={1} duration={2}', [formatTime(currentTime, duration), formatTime(duration, duration)], '{1} of {2}'));
  13817. _this3.currentTime_ = currentTime;
  13818. _this3.duration_ = duration;
  13819. } // update the progress bar time tooltip with the current time
  13820. if (_this3.bar) {
  13821. _this3.bar.update(getBoundingClientRect(_this3.el()), _this3.getProgress());
  13822. }
  13823. });
  13824. return percent;
  13825. }
  13826. /**
  13827. * Prevent liveThreshold from causing seeks to seem like they
  13828. * are not happening from a user perspective.
  13829. *
  13830. * @param {number} ct
  13831. * current time to seek to
  13832. */
  13833. ;
  13834. _proto.userSeek_ = function userSeek_(ct) {
  13835. if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {
  13836. this.player_.liveTracker.nextSeekedFromUser();
  13837. }
  13838. this.player_.currentTime(ct);
  13839. }
  13840. /**
  13841. * Get the value of current time but allows for smooth scrubbing,
  13842. * when player can't keep up.
  13843. *
  13844. * @return {number}
  13845. * The current time value to display
  13846. *
  13847. * @private
  13848. */
  13849. ;
  13850. _proto.getCurrentTime_ = function getCurrentTime_() {
  13851. return this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  13852. }
  13853. /**
  13854. * Get the percentage of media played so far.
  13855. *
  13856. * @return {number}
  13857. * The percentage of media played so far (0 to 1).
  13858. */
  13859. ;
  13860. _proto.getPercent = function getPercent() {
  13861. var currentTime = this.getCurrentTime_();
  13862. var percent;
  13863. var liveTracker = this.player_.liveTracker;
  13864. if (liveTracker && liveTracker.isLive()) {
  13865. percent = (currentTime - liveTracker.seekableStart()) / liveTracker.liveWindow(); // prevent the percent from changing at the live edge
  13866. if (liveTracker.atLiveEdge()) {
  13867. percent = 1;
  13868. }
  13869. } else {
  13870. percent = currentTime / this.player_.duration();
  13871. }
  13872. return percent;
  13873. }
  13874. /**
  13875. * Handle mouse down on seek bar
  13876. *
  13877. * @param {EventTarget~Event} event
  13878. * The `mousedown` event that caused this to run.
  13879. *
  13880. * @listens mousedown
  13881. */
  13882. ;
  13883. _proto.handleMouseDown = function handleMouseDown(event) {
  13884. if (!isSingleLeftClick(event)) {
  13885. return;
  13886. } // Stop event propagation to prevent double fire in progress-control.js
  13887. event.stopPropagation();
  13888. this.videoWasPlaying = !this.player_.paused();
  13889. this.player_.pause();
  13890. _Slider.prototype.handleMouseDown.call(this, event);
  13891. }
  13892. /**
  13893. * Handle mouse move on seek bar
  13894. *
  13895. * @param {EventTarget~Event} event
  13896. * The `mousemove` event that caused this to run.
  13897. * @param {boolean} mouseDown this is a flag that should be set to true if `handleMouseMove` is called directly. It allows us to skip things that should not happen if coming from mouse down but should happen on regular mouse move handler. Defaults to false
  13898. *
  13899. * @listens mousemove
  13900. */
  13901. ;
  13902. _proto.handleMouseMove = function handleMouseMove(event, mouseDown) {
  13903. if (mouseDown === void 0) {
  13904. mouseDown = false;
  13905. }
  13906. if (!isSingleLeftClick(event)) {
  13907. return;
  13908. }
  13909. if (!mouseDown && !this.player_.scrubbing()) {
  13910. this.player_.scrubbing(true);
  13911. }
  13912. var newTime;
  13913. var distance = this.calculateDistance(event);
  13914. var liveTracker = this.player_.liveTracker;
  13915. if (!liveTracker || !liveTracker.isLive()) {
  13916. newTime = distance * this.player_.duration(); // Don't let video end while scrubbing.
  13917. if (newTime === this.player_.duration()) {
  13918. newTime = newTime - 0.1;
  13919. }
  13920. } else {
  13921. if (distance >= 0.99) {
  13922. liveTracker.seekToLiveEdge();
  13923. return;
  13924. }
  13925. var seekableStart = liveTracker.seekableStart();
  13926. var seekableEnd = liveTracker.liveCurrentTime();
  13927. newTime = seekableStart + distance * liveTracker.liveWindow(); // Don't let video end while scrubbing.
  13928. if (newTime >= seekableEnd) {
  13929. newTime = seekableEnd;
  13930. } // Compensate for precision differences so that currentTime is not less
  13931. // than seekable start
  13932. if (newTime <= seekableStart) {
  13933. newTime = seekableStart + 0.1;
  13934. } // On android seekableEnd can be Infinity sometimes,
  13935. // this will cause newTime to be Infinity, which is
  13936. // not a valid currentTime.
  13937. if (newTime === Infinity) {
  13938. return;
  13939. }
  13940. } // Set new time (tell player to seek to new time)
  13941. this.userSeek_(newTime);
  13942. };
  13943. _proto.enable = function enable() {
  13944. _Slider.prototype.enable.call(this);
  13945. var mouseTimeDisplay = this.getChild('mouseTimeDisplay');
  13946. if (!mouseTimeDisplay) {
  13947. return;
  13948. }
  13949. mouseTimeDisplay.show();
  13950. };
  13951. _proto.disable = function disable() {
  13952. _Slider.prototype.disable.call(this);
  13953. var mouseTimeDisplay = this.getChild('mouseTimeDisplay');
  13954. if (!mouseTimeDisplay) {
  13955. return;
  13956. }
  13957. mouseTimeDisplay.hide();
  13958. }
  13959. /**
  13960. * Handle mouse up on seek bar
  13961. *
  13962. * @param {EventTarget~Event} event
  13963. * The `mouseup` event that caused this to run.
  13964. *
  13965. * @listens mouseup
  13966. */
  13967. ;
  13968. _proto.handleMouseUp = function handleMouseUp(event) {
  13969. _Slider.prototype.handleMouseUp.call(this, event); // Stop event propagation to prevent double fire in progress-control.js
  13970. if (event) {
  13971. event.stopPropagation();
  13972. }
  13973. this.player_.scrubbing(false);
  13974. /**
  13975. * Trigger timeupdate because we're done seeking and the time has changed.
  13976. * This is particularly useful for if the player is paused to time the time displays.
  13977. *
  13978. * @event Tech#timeupdate
  13979. * @type {EventTarget~Event}
  13980. */
  13981. this.player_.trigger({
  13982. type: 'timeupdate',
  13983. target: this,
  13984. manuallyTriggered: true
  13985. });
  13986. if (this.videoWasPlaying) {
  13987. silencePromise(this.player_.play());
  13988. } else {
  13989. // We're done seeking and the time has changed.
  13990. // If the player is paused, make sure we display the correct time on the seek bar.
  13991. this.update_();
  13992. }
  13993. }
  13994. /**
  13995. * Move more quickly fast forward for keyboard-only users
  13996. */
  13997. ;
  13998. _proto.stepForward = function stepForward() {
  13999. this.userSeek_(this.player_.currentTime() + STEP_SECONDS);
  14000. }
  14001. /**
  14002. * Move more quickly rewind for keyboard-only users
  14003. */
  14004. ;
  14005. _proto.stepBack = function stepBack() {
  14006. this.userSeek_(this.player_.currentTime() - STEP_SECONDS);
  14007. }
  14008. /**
  14009. * Toggles the playback state of the player
  14010. * This gets called when enter or space is used on the seekbar
  14011. *
  14012. * @param {EventTarget~Event} event
  14013. * The `keydown` event that caused this function to be called
  14014. *
  14015. */
  14016. ;
  14017. _proto.handleAction = function handleAction(event) {
  14018. if (this.player_.paused()) {
  14019. this.player_.play();
  14020. } else {
  14021. this.player_.pause();
  14022. }
  14023. }
  14024. /**
  14025. * Called when this SeekBar has focus and a key gets pressed down.
  14026. * Supports the following keys:
  14027. *
  14028. * Space or Enter key fire a click event
  14029. * Home key moves to start of the timeline
  14030. * End key moves to end of the timeline
  14031. * Digit "0" through "9" keys move to 0%, 10% ... 80%, 90% of the timeline
  14032. * PageDown key moves back a larger step than ArrowDown
  14033. * PageUp key moves forward a large step
  14034. *
  14035. * @param {EventTarget~Event} event
  14036. * The `keydown` event that caused this function to be called.
  14037. *
  14038. * @listens keydown
  14039. */
  14040. ;
  14041. _proto.handleKeyDown = function handleKeyDown(event) {
  14042. var liveTracker = this.player_.liveTracker;
  14043. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) {
  14044. event.preventDefault();
  14045. event.stopPropagation();
  14046. this.handleAction(event);
  14047. } else if (keycode.isEventKey(event, 'Home')) {
  14048. event.preventDefault();
  14049. event.stopPropagation();
  14050. this.userSeek_(0);
  14051. } else if (keycode.isEventKey(event, 'End')) {
  14052. event.preventDefault();
  14053. event.stopPropagation();
  14054. if (liveTracker && liveTracker.isLive()) {
  14055. this.userSeek_(liveTracker.liveCurrentTime());
  14056. } else {
  14057. this.userSeek_(this.player_.duration());
  14058. }
  14059. } else if (/^[0-9]$/.test(keycode(event))) {
  14060. event.preventDefault();
  14061. event.stopPropagation();
  14062. var gotoFraction = (keycode.codes[keycode(event)] - keycode.codes['0']) * 10.0 / 100.0;
  14063. if (liveTracker && liveTracker.isLive()) {
  14064. this.userSeek_(liveTracker.seekableStart() + liveTracker.liveWindow() * gotoFraction);
  14065. } else {
  14066. this.userSeek_(this.player_.duration() * gotoFraction);
  14067. }
  14068. } else if (keycode.isEventKey(event, 'PgDn')) {
  14069. event.preventDefault();
  14070. event.stopPropagation();
  14071. this.userSeek_(this.player_.currentTime() - STEP_SECONDS * PAGE_KEY_MULTIPLIER);
  14072. } else if (keycode.isEventKey(event, 'PgUp')) {
  14073. event.preventDefault();
  14074. event.stopPropagation();
  14075. this.userSeek_(this.player_.currentTime() + STEP_SECONDS * PAGE_KEY_MULTIPLIER);
  14076. } else {
  14077. // Pass keydown handling up for unsupported keys
  14078. _Slider.prototype.handleKeyDown.call(this, event);
  14079. }
  14080. };
  14081. _proto.dispose = function dispose() {
  14082. this.disableInterval_();
  14083. this.off(this.player_, ['ended', 'durationchange', 'timeupdate'], this.update);
  14084. if (this.player_.liveTracker) {
  14085. this.off(this.player_.liveTracker, 'liveedgechange', this.update);
  14086. }
  14087. this.off(this.player_, ['playing'], this.enableIntervalHandler_);
  14088. this.off(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_); // we don't need to update the play progress if the document is hidden,
  14089. // also, this causes the CPU to spike and eventually crash the page on IE11.
  14090. if ('hidden' in document && 'visibilityState' in document) {
  14091. this.off(document, 'visibilitychange', this.toggleVisibility_);
  14092. }
  14093. _Slider.prototype.dispose.call(this);
  14094. };
  14095. return SeekBar;
  14096. }(Slider);
  14097. /**
  14098. * Default options for the `SeekBar`
  14099. *
  14100. * @type {Object}
  14101. * @private
  14102. */
  14103. SeekBar.prototype.options_ = {
  14104. children: ['loadProgressBar', 'playProgressBar'],
  14105. barName: 'playProgressBar'
  14106. }; // MouseTimeDisplay tooltips should not be added to a player on mobile devices
  14107. if (!IS_IOS && !IS_ANDROID) {
  14108. SeekBar.prototype.options_.children.splice(1, 0, 'mouseTimeDisplay');
  14109. }
  14110. Component$1.registerComponent('SeekBar', SeekBar);
  14111. /**
  14112. * The Progress Control component contains the seek bar, load progress,
  14113. * and play progress.
  14114. *
  14115. * @extends Component
  14116. */
  14117. var ProgressControl = /*#__PURE__*/function (_Component) {
  14118. inheritsLoose(ProgressControl, _Component);
  14119. /**
  14120. * Creates an instance of this class.
  14121. *
  14122. * @param {Player} player
  14123. * The `Player` that this class should be attached to.
  14124. *
  14125. * @param {Object} [options]
  14126. * The key/value store of player options.
  14127. */
  14128. function ProgressControl(player, options) {
  14129. var _this;
  14130. _this = _Component.call(this, player, options) || this;
  14131. _this.handleMouseMove = throttle(bind(assertThisInitialized(_this), _this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
  14132. _this.throttledHandleMouseSeek = throttle(bind(assertThisInitialized(_this), _this.handleMouseSeek), UPDATE_REFRESH_INTERVAL);
  14133. _this.handleMouseUpHandler_ = function (e) {
  14134. return _this.handleMouseUp(e);
  14135. };
  14136. _this.handleMouseDownHandler_ = function (e) {
  14137. return _this.handleMouseDown(e);
  14138. };
  14139. _this.enable();
  14140. return _this;
  14141. }
  14142. /**
  14143. * Create the `Component`'s DOM element
  14144. *
  14145. * @return {Element}
  14146. * The element that was created.
  14147. */
  14148. var _proto = ProgressControl.prototype;
  14149. _proto.createEl = function createEl() {
  14150. return _Component.prototype.createEl.call(this, 'div', {
  14151. className: 'vjs-progress-control vjs-control'
  14152. });
  14153. }
  14154. /**
  14155. * When the mouse moves over the `ProgressControl`, the pointer position
  14156. * gets passed down to the `MouseTimeDisplay` component.
  14157. *
  14158. * @param {EventTarget~Event} event
  14159. * The `mousemove` event that caused this function to run.
  14160. *
  14161. * @listen mousemove
  14162. */
  14163. ;
  14164. _proto.handleMouseMove = function handleMouseMove(event) {
  14165. var seekBar = this.getChild('seekBar');
  14166. if (!seekBar) {
  14167. return;
  14168. }
  14169. var playProgressBar = seekBar.getChild('playProgressBar');
  14170. var mouseTimeDisplay = seekBar.getChild('mouseTimeDisplay');
  14171. if (!playProgressBar && !mouseTimeDisplay) {
  14172. return;
  14173. }
  14174. var seekBarEl = seekBar.el();
  14175. var seekBarRect = findPosition(seekBarEl);
  14176. var seekBarPoint = getPointerPosition(seekBarEl, event).x; // The default skin has a gap on either side of the `SeekBar`. This means
  14177. // that it's possible to trigger this behavior outside the boundaries of
  14178. // the `SeekBar`. This ensures we stay within it at all times.
  14179. seekBarPoint = clamp(seekBarPoint, 0, 1);
  14180. if (mouseTimeDisplay) {
  14181. mouseTimeDisplay.update(seekBarRect, seekBarPoint);
  14182. }
  14183. if (playProgressBar) {
  14184. playProgressBar.update(seekBarRect, seekBar.getProgress());
  14185. }
  14186. }
  14187. /**
  14188. * A throttled version of the {@link ProgressControl#handleMouseSeek} listener.
  14189. *
  14190. * @method ProgressControl#throttledHandleMouseSeek
  14191. * @param {EventTarget~Event} event
  14192. * The `mousemove` event that caused this function to run.
  14193. *
  14194. * @listen mousemove
  14195. * @listen touchmove
  14196. */
  14197. /**
  14198. * Handle `mousemove` or `touchmove` events on the `ProgressControl`.
  14199. *
  14200. * @param {EventTarget~Event} event
  14201. * `mousedown` or `touchstart` event that triggered this function
  14202. *
  14203. * @listens mousemove
  14204. * @listens touchmove
  14205. */
  14206. ;
  14207. _proto.handleMouseSeek = function handleMouseSeek(event) {
  14208. var seekBar = this.getChild('seekBar');
  14209. if (seekBar) {
  14210. seekBar.handleMouseMove(event);
  14211. }
  14212. }
  14213. /**
  14214. * Are controls are currently enabled for this progress control.
  14215. *
  14216. * @return {boolean}
  14217. * true if controls are enabled, false otherwise
  14218. */
  14219. ;
  14220. _proto.enabled = function enabled() {
  14221. return this.enabled_;
  14222. }
  14223. /**
  14224. * Disable all controls on the progress control and its children
  14225. */
  14226. ;
  14227. _proto.disable = function disable() {
  14228. this.children().forEach(function (child) {
  14229. return child.disable && child.disable();
  14230. });
  14231. if (!this.enabled()) {
  14232. return;
  14233. }
  14234. this.off(['mousedown', 'touchstart'], this.handleMouseDownHandler_);
  14235. this.off(this.el_, 'mousemove', this.handleMouseMove);
  14236. this.removeListenersAddedOnMousedownAndTouchstart();
  14237. this.addClass('disabled');
  14238. this.enabled_ = false; // Restore normal playback state if controls are disabled while scrubbing
  14239. if (this.player_.scrubbing()) {
  14240. var seekBar = this.getChild('seekBar');
  14241. this.player_.scrubbing(false);
  14242. if (seekBar.videoWasPlaying) {
  14243. silencePromise(this.player_.play());
  14244. }
  14245. }
  14246. }
  14247. /**
  14248. * Enable all controls on the progress control and its children
  14249. */
  14250. ;
  14251. _proto.enable = function enable() {
  14252. this.children().forEach(function (child) {
  14253. return child.enable && child.enable();
  14254. });
  14255. if (this.enabled()) {
  14256. return;
  14257. }
  14258. this.on(['mousedown', 'touchstart'], this.handleMouseDownHandler_);
  14259. this.on(this.el_, 'mousemove', this.handleMouseMove);
  14260. this.removeClass('disabled');
  14261. this.enabled_ = true;
  14262. }
  14263. /**
  14264. * Cleanup listeners after the user finishes interacting with the progress controls
  14265. */
  14266. ;
  14267. _proto.removeListenersAddedOnMousedownAndTouchstart = function removeListenersAddedOnMousedownAndTouchstart() {
  14268. var doc = this.el_.ownerDocument;
  14269. this.off(doc, 'mousemove', this.throttledHandleMouseSeek);
  14270. this.off(doc, 'touchmove', this.throttledHandleMouseSeek);
  14271. this.off(doc, 'mouseup', this.handleMouseUpHandler_);
  14272. this.off(doc, 'touchend', this.handleMouseUpHandler_);
  14273. }
  14274. /**
  14275. * Handle `mousedown` or `touchstart` events on the `ProgressControl`.
  14276. *
  14277. * @param {EventTarget~Event} event
  14278. * `mousedown` or `touchstart` event that triggered this function
  14279. *
  14280. * @listens mousedown
  14281. * @listens touchstart
  14282. */
  14283. ;
  14284. _proto.handleMouseDown = function handleMouseDown(event) {
  14285. var doc = this.el_.ownerDocument;
  14286. var seekBar = this.getChild('seekBar');
  14287. if (seekBar) {
  14288. seekBar.handleMouseDown(event);
  14289. }
  14290. this.on(doc, 'mousemove', this.throttledHandleMouseSeek);
  14291. this.on(doc, 'touchmove', this.throttledHandleMouseSeek);
  14292. this.on(doc, 'mouseup', this.handleMouseUpHandler_);
  14293. this.on(doc, 'touchend', this.handleMouseUpHandler_);
  14294. }
  14295. /**
  14296. * Handle `mouseup` or `touchend` events on the `ProgressControl`.
  14297. *
  14298. * @param {EventTarget~Event} event
  14299. * `mouseup` or `touchend` event that triggered this function.
  14300. *
  14301. * @listens touchend
  14302. * @listens mouseup
  14303. */
  14304. ;
  14305. _proto.handleMouseUp = function handleMouseUp(event) {
  14306. var seekBar = this.getChild('seekBar');
  14307. if (seekBar) {
  14308. seekBar.handleMouseUp(event);
  14309. }
  14310. this.removeListenersAddedOnMousedownAndTouchstart();
  14311. };
  14312. return ProgressControl;
  14313. }(Component$1);
  14314. /**
  14315. * Default options for `ProgressControl`
  14316. *
  14317. * @type {Object}
  14318. * @private
  14319. */
  14320. ProgressControl.prototype.options_ = {
  14321. children: ['seekBar']
  14322. };
  14323. Component$1.registerComponent('ProgressControl', ProgressControl);
  14324. /**
  14325. * Toggle Picture-in-Picture mode
  14326. *
  14327. * @extends Button
  14328. */
  14329. var PictureInPictureToggle = /*#__PURE__*/function (_Button) {
  14330. inheritsLoose(PictureInPictureToggle, _Button);
  14331. /**
  14332. * Creates an instance of this class.
  14333. *
  14334. * @param {Player} player
  14335. * The `Player` that this class should be attached to.
  14336. *
  14337. * @param {Object} [options]
  14338. * The key/value store of player options.
  14339. *
  14340. * @listens Player#enterpictureinpicture
  14341. * @listens Player#leavepictureinpicture
  14342. */
  14343. function PictureInPictureToggle(player, options) {
  14344. var _this;
  14345. _this = _Button.call(this, player, options) || this;
  14346. _this.on(player, ['enterpictureinpicture', 'leavepictureinpicture'], function (e) {
  14347. return _this.handlePictureInPictureChange(e);
  14348. });
  14349. _this.on(player, ['disablepictureinpicturechanged', 'loadedmetadata'], function (e) {
  14350. return _this.handlePictureInPictureEnabledChange(e);
  14351. });
  14352. _this.on(player, ['loadedmetadata', 'audioonlymodechange', 'audiopostermodechange'], function () {
  14353. // This audio detection will not detect HLS or DASH audio-only streams because there was no reliable way to detect them at the time
  14354. var isSourceAudio = player.currentType().substring(0, 5) === 'audio';
  14355. if (isSourceAudio || player.audioPosterMode() || player.audioOnlyMode()) {
  14356. if (player.isInPictureInPicture()) {
  14357. player.exitPictureInPicture();
  14358. }
  14359. _this.hide();
  14360. } else {
  14361. _this.show();
  14362. }
  14363. }); // TODO: Deactivate button on player emptied event.
  14364. _this.disable();
  14365. return _this;
  14366. }
  14367. /**
  14368. * Builds the default DOM `className`.
  14369. *
  14370. * @return {string}
  14371. * The DOM `className` for this object.
  14372. */
  14373. var _proto = PictureInPictureToggle.prototype;
  14374. _proto.buildCSSClass = function buildCSSClass() {
  14375. return "vjs-picture-in-picture-control " + _Button.prototype.buildCSSClass.call(this);
  14376. }
  14377. /**
  14378. * Enables or disables button based on document.pictureInPictureEnabled property value
  14379. * or on value returned by player.disablePictureInPicture() method.
  14380. */
  14381. ;
  14382. _proto.handlePictureInPictureEnabledChange = function handlePictureInPictureEnabledChange() {
  14383. if (document.pictureInPictureEnabled && this.player_.disablePictureInPicture() === false) {
  14384. this.enable();
  14385. } else {
  14386. this.disable();
  14387. }
  14388. }
  14389. /**
  14390. * Handles enterpictureinpicture and leavepictureinpicture on the player and change control text accordingly.
  14391. *
  14392. * @param {EventTarget~Event} [event]
  14393. * The {@link Player#enterpictureinpicture} or {@link Player#leavepictureinpicture} event that caused this function to be
  14394. * called.
  14395. *
  14396. * @listens Player#enterpictureinpicture
  14397. * @listens Player#leavepictureinpicture
  14398. */
  14399. ;
  14400. _proto.handlePictureInPictureChange = function handlePictureInPictureChange(event) {
  14401. if (this.player_.isInPictureInPicture()) {
  14402. this.controlText('Exit Picture-in-Picture');
  14403. } else {
  14404. this.controlText('Picture-in-Picture');
  14405. }
  14406. this.handlePictureInPictureEnabledChange();
  14407. }
  14408. /**
  14409. * This gets called when an `PictureInPictureToggle` is "clicked". See
  14410. * {@link ClickableComponent} for more detailed information on what a click can be.
  14411. *
  14412. * @param {EventTarget~Event} [event]
  14413. * The `keydown`, `tap`, or `click` event that caused this function to be
  14414. * called.
  14415. *
  14416. * @listens tap
  14417. * @listens click
  14418. */
  14419. ;
  14420. _proto.handleClick = function handleClick(event) {
  14421. if (!this.player_.isInPictureInPicture()) {
  14422. this.player_.requestPictureInPicture();
  14423. } else {
  14424. this.player_.exitPictureInPicture();
  14425. }
  14426. };
  14427. return PictureInPictureToggle;
  14428. }(Button);
  14429. /**
  14430. * The text that should display over the `PictureInPictureToggle`s controls. Added for localization.
  14431. *
  14432. * @type {string}
  14433. * @private
  14434. */
  14435. PictureInPictureToggle.prototype.controlText_ = 'Picture-in-Picture';
  14436. Component$1.registerComponent('PictureInPictureToggle', PictureInPictureToggle);
  14437. /**
  14438. * Toggle fullscreen video
  14439. *
  14440. * @extends Button
  14441. */
  14442. var FullscreenToggle = /*#__PURE__*/function (_Button) {
  14443. inheritsLoose(FullscreenToggle, _Button);
  14444. /**
  14445. * Creates an instance of this class.
  14446. *
  14447. * @param {Player} player
  14448. * The `Player` that this class should be attached to.
  14449. *
  14450. * @param {Object} [options]
  14451. * The key/value store of player options.
  14452. */
  14453. function FullscreenToggle(player, options) {
  14454. var _this;
  14455. _this = _Button.call(this, player, options) || this;
  14456. _this.on(player, 'fullscreenchange', function (e) {
  14457. return _this.handleFullscreenChange(e);
  14458. });
  14459. if (document[player.fsApi_.fullscreenEnabled] === false) {
  14460. _this.disable();
  14461. }
  14462. return _this;
  14463. }
  14464. /**
  14465. * Builds the default DOM `className`.
  14466. *
  14467. * @return {string}
  14468. * The DOM `className` for this object.
  14469. */
  14470. var _proto = FullscreenToggle.prototype;
  14471. _proto.buildCSSClass = function buildCSSClass() {
  14472. return "vjs-fullscreen-control " + _Button.prototype.buildCSSClass.call(this);
  14473. }
  14474. /**
  14475. * Handles fullscreenchange on the player and change control text accordingly.
  14476. *
  14477. * @param {EventTarget~Event} [event]
  14478. * The {@link Player#fullscreenchange} event that caused this function to be
  14479. * called.
  14480. *
  14481. * @listens Player#fullscreenchange
  14482. */
  14483. ;
  14484. _proto.handleFullscreenChange = function handleFullscreenChange(event) {
  14485. if (this.player_.isFullscreen()) {
  14486. this.controlText('Non-Fullscreen');
  14487. } else {
  14488. this.controlText('Fullscreen');
  14489. }
  14490. }
  14491. /**
  14492. * This gets called when an `FullscreenToggle` is "clicked". See
  14493. * {@link ClickableComponent} for more detailed information on what a click can be.
  14494. *
  14495. * @param {EventTarget~Event} [event]
  14496. * The `keydown`, `tap`, or `click` event that caused this function to be
  14497. * called.
  14498. *
  14499. * @listens tap
  14500. * @listens click
  14501. */
  14502. ;
  14503. _proto.handleClick = function handleClick(event) {
  14504. if (!this.player_.isFullscreen()) {
  14505. this.player_.requestFullscreen();
  14506. } else {
  14507. this.player_.exitFullscreen();
  14508. }
  14509. };
  14510. return FullscreenToggle;
  14511. }(Button);
  14512. /**
  14513. * The text that should display over the `FullscreenToggle`s controls. Added for localization.
  14514. *
  14515. * @type {string}
  14516. * @private
  14517. */
  14518. FullscreenToggle.prototype.controlText_ = 'Fullscreen';
  14519. Component$1.registerComponent('FullscreenToggle', FullscreenToggle);
  14520. /**
  14521. * Check if volume control is supported and if it isn't hide the
  14522. * `Component` that was passed using the `vjs-hidden` class.
  14523. *
  14524. * @param {Component} self
  14525. * The component that should be hidden if volume is unsupported
  14526. *
  14527. * @param {Player} player
  14528. * A reference to the player
  14529. *
  14530. * @private
  14531. */
  14532. var checkVolumeSupport = function checkVolumeSupport(self, player) {
  14533. // hide volume controls when they're not supported by the current tech
  14534. if (player.tech_ && !player.tech_.featuresVolumeControl) {
  14535. self.addClass('vjs-hidden');
  14536. }
  14537. self.on(player, 'loadstart', function () {
  14538. if (!player.tech_.featuresVolumeControl) {
  14539. self.addClass('vjs-hidden');
  14540. } else {
  14541. self.removeClass('vjs-hidden');
  14542. }
  14543. });
  14544. };
  14545. /**
  14546. * Shows volume level
  14547. *
  14548. * @extends Component
  14549. */
  14550. var VolumeLevel = /*#__PURE__*/function (_Component) {
  14551. inheritsLoose(VolumeLevel, _Component);
  14552. function VolumeLevel() {
  14553. return _Component.apply(this, arguments) || this;
  14554. }
  14555. var _proto = VolumeLevel.prototype;
  14556. /**
  14557. * Create the `Component`'s DOM element
  14558. *
  14559. * @return {Element}
  14560. * The element that was created.
  14561. */
  14562. _proto.createEl = function createEl() {
  14563. var el = _Component.prototype.createEl.call(this, 'div', {
  14564. className: 'vjs-volume-level'
  14565. });
  14566. el.appendChild(_Component.prototype.createEl.call(this, 'span', {
  14567. className: 'vjs-control-text'
  14568. }));
  14569. return el;
  14570. };
  14571. return VolumeLevel;
  14572. }(Component$1);
  14573. Component$1.registerComponent('VolumeLevel', VolumeLevel);
  14574. /**
  14575. * Volume level tooltips display a volume above or side by side the volume bar.
  14576. *
  14577. * @extends Component
  14578. */
  14579. var VolumeLevelTooltip = /*#__PURE__*/function (_Component) {
  14580. inheritsLoose(VolumeLevelTooltip, _Component);
  14581. /**
  14582. * Creates an instance of this class.
  14583. *
  14584. * @param {Player} player
  14585. * The {@link Player} that this class should be attached to.
  14586. *
  14587. * @param {Object} [options]
  14588. * The key/value store of player options.
  14589. */
  14590. function VolumeLevelTooltip(player, options) {
  14591. var _this;
  14592. _this = _Component.call(this, player, options) || this;
  14593. _this.update = throttle(bind(assertThisInitialized(_this), _this.update), UPDATE_REFRESH_INTERVAL);
  14594. return _this;
  14595. }
  14596. /**
  14597. * Create the volume tooltip DOM element
  14598. *
  14599. * @return {Element}
  14600. * The element that was created.
  14601. */
  14602. var _proto = VolumeLevelTooltip.prototype;
  14603. _proto.createEl = function createEl() {
  14604. return _Component.prototype.createEl.call(this, 'div', {
  14605. className: 'vjs-volume-tooltip'
  14606. }, {
  14607. 'aria-hidden': 'true'
  14608. });
  14609. }
  14610. /**
  14611. * Updates the position of the tooltip relative to the `VolumeBar` and
  14612. * its content text.
  14613. *
  14614. * @param {Object} rangeBarRect
  14615. * The `ClientRect` for the {@link VolumeBar} element.
  14616. *
  14617. * @param {number} rangeBarPoint
  14618. * A number from 0 to 1, representing a horizontal/vertical reference point
  14619. * from the left edge of the {@link VolumeBar}
  14620. *
  14621. * @param {boolean} vertical
  14622. * Referees to the Volume control position
  14623. * in the control bar{@link VolumeControl}
  14624. *
  14625. */
  14626. ;
  14627. _proto.update = function update(rangeBarRect, rangeBarPoint, vertical, content) {
  14628. if (!vertical) {
  14629. var tooltipRect = getBoundingClientRect(this.el_);
  14630. var playerRect = getBoundingClientRect(this.player_.el());
  14631. var volumeBarPointPx = rangeBarRect.width * rangeBarPoint;
  14632. if (!playerRect || !tooltipRect) {
  14633. return;
  14634. }
  14635. var spaceLeftOfPoint = rangeBarRect.left - playerRect.left + volumeBarPointPx;
  14636. var spaceRightOfPoint = rangeBarRect.width - volumeBarPointPx + (playerRect.right - rangeBarRect.right);
  14637. var pullTooltipBy = tooltipRect.width / 2;
  14638. if (spaceLeftOfPoint < pullTooltipBy) {
  14639. pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
  14640. } else if (spaceRightOfPoint < pullTooltipBy) {
  14641. pullTooltipBy = spaceRightOfPoint;
  14642. }
  14643. if (pullTooltipBy < 0) {
  14644. pullTooltipBy = 0;
  14645. } else if (pullTooltipBy > tooltipRect.width) {
  14646. pullTooltipBy = tooltipRect.width;
  14647. }
  14648. this.el_.style.right = "-" + pullTooltipBy + "px";
  14649. }
  14650. this.write(content + "%");
  14651. }
  14652. /**
  14653. * Write the volume to the tooltip DOM element.
  14654. *
  14655. * @param {string} content
  14656. * The formatted volume for the tooltip.
  14657. */
  14658. ;
  14659. _proto.write = function write(content) {
  14660. textContent(this.el_, content);
  14661. }
  14662. /**
  14663. * Updates the position of the volume tooltip relative to the `VolumeBar`.
  14664. *
  14665. * @param {Object} rangeBarRect
  14666. * The `ClientRect` for the {@link VolumeBar} element.
  14667. *
  14668. * @param {number} rangeBarPoint
  14669. * A number from 0 to 1, representing a horizontal/vertical reference point
  14670. * from the left edge of the {@link VolumeBar}
  14671. *
  14672. * @param {boolean} vertical
  14673. * Referees to the Volume control position
  14674. * in the control bar{@link VolumeControl}
  14675. *
  14676. * @param {number} volume
  14677. * The volume level to update the tooltip to
  14678. *
  14679. * @param {Function} cb
  14680. * A function that will be called during the request animation frame
  14681. * for tooltips that need to do additional animations from the default
  14682. */
  14683. ;
  14684. _proto.updateVolume = function updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, cb) {
  14685. var _this2 = this;
  14686. this.requestNamedAnimationFrame('VolumeLevelTooltip#updateVolume', function () {
  14687. _this2.update(rangeBarRect, rangeBarPoint, vertical, volume.toFixed(0));
  14688. if (cb) {
  14689. cb();
  14690. }
  14691. });
  14692. };
  14693. return VolumeLevelTooltip;
  14694. }(Component$1);
  14695. Component$1.registerComponent('VolumeLevelTooltip', VolumeLevelTooltip);
  14696. /**
  14697. * The {@link MouseVolumeLevelDisplay} component tracks mouse movement over the
  14698. * {@link VolumeControl}. It displays an indicator and a {@link VolumeLevelTooltip}
  14699. * indicating the volume level which is represented by a given point in the
  14700. * {@link VolumeBar}.
  14701. *
  14702. * @extends Component
  14703. */
  14704. var MouseVolumeLevelDisplay = /*#__PURE__*/function (_Component) {
  14705. inheritsLoose(MouseVolumeLevelDisplay, _Component);
  14706. /**
  14707. * Creates an instance of this class.
  14708. *
  14709. * @param {Player} player
  14710. * The {@link Player} that this class should be attached to.
  14711. *
  14712. * @param {Object} [options]
  14713. * The key/value store of player options.
  14714. */
  14715. function MouseVolumeLevelDisplay(player, options) {
  14716. var _this;
  14717. _this = _Component.call(this, player, options) || this;
  14718. _this.update = throttle(bind(assertThisInitialized(_this), _this.update), UPDATE_REFRESH_INTERVAL);
  14719. return _this;
  14720. }
  14721. /**
  14722. * Create the DOM element for this class.
  14723. *
  14724. * @return {Element}
  14725. * The element that was created.
  14726. */
  14727. var _proto = MouseVolumeLevelDisplay.prototype;
  14728. _proto.createEl = function createEl() {
  14729. return _Component.prototype.createEl.call(this, 'div', {
  14730. className: 'vjs-mouse-display'
  14731. });
  14732. }
  14733. /**
  14734. * Enquires updates to its own DOM as well as the DOM of its
  14735. * {@link VolumeLevelTooltip} child.
  14736. *
  14737. * @param {Object} rangeBarRect
  14738. * The `ClientRect` for the {@link VolumeBar} element.
  14739. *
  14740. * @param {number} rangeBarPoint
  14741. * A number from 0 to 1, representing a horizontal/vertical reference point
  14742. * from the left edge of the {@link VolumeBar}
  14743. *
  14744. * @param {boolean} vertical
  14745. * Referees to the Volume control position
  14746. * in the control bar{@link VolumeControl}
  14747. *
  14748. */
  14749. ;
  14750. _proto.update = function update(rangeBarRect, rangeBarPoint, vertical) {
  14751. var _this2 = this;
  14752. var volume = 100 * rangeBarPoint;
  14753. this.getChild('volumeLevelTooltip').updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, function () {
  14754. if (vertical) {
  14755. _this2.el_.style.bottom = rangeBarRect.height * rangeBarPoint + "px";
  14756. } else {
  14757. _this2.el_.style.left = rangeBarRect.width * rangeBarPoint + "px";
  14758. }
  14759. });
  14760. };
  14761. return MouseVolumeLevelDisplay;
  14762. }(Component$1);
  14763. /**
  14764. * Default options for `MouseVolumeLevelDisplay`
  14765. *
  14766. * @type {Object}
  14767. * @private
  14768. */
  14769. MouseVolumeLevelDisplay.prototype.options_ = {
  14770. children: ['volumeLevelTooltip']
  14771. };
  14772. Component$1.registerComponent('MouseVolumeLevelDisplay', MouseVolumeLevelDisplay);
  14773. /**
  14774. * The bar that contains the volume level and can be clicked on to adjust the level
  14775. *
  14776. * @extends Slider
  14777. */
  14778. var VolumeBar = /*#__PURE__*/function (_Slider) {
  14779. inheritsLoose(VolumeBar, _Slider);
  14780. /**
  14781. * Creates an instance of this class.
  14782. *
  14783. * @param {Player} player
  14784. * The `Player` that this class should be attached to.
  14785. *
  14786. * @param {Object} [options]
  14787. * The key/value store of player options.
  14788. */
  14789. function VolumeBar(player, options) {
  14790. var _this;
  14791. _this = _Slider.call(this, player, options) || this;
  14792. _this.on('slideractive', function (e) {
  14793. return _this.updateLastVolume_(e);
  14794. });
  14795. _this.on(player, 'volumechange', function (e) {
  14796. return _this.updateARIAAttributes(e);
  14797. });
  14798. player.ready(function () {
  14799. return _this.updateARIAAttributes();
  14800. });
  14801. return _this;
  14802. }
  14803. /**
  14804. * Create the `Component`'s DOM element
  14805. *
  14806. * @return {Element}
  14807. * The element that was created.
  14808. */
  14809. var _proto = VolumeBar.prototype;
  14810. _proto.createEl = function createEl() {
  14811. return _Slider.prototype.createEl.call(this, 'div', {
  14812. className: 'vjs-volume-bar vjs-slider-bar'
  14813. }, {
  14814. 'aria-label': this.localize('Volume Level'),
  14815. 'aria-live': 'polite'
  14816. });
  14817. }
  14818. /**
  14819. * Handle mouse down on volume bar
  14820. *
  14821. * @param {EventTarget~Event} event
  14822. * The `mousedown` event that caused this to run.
  14823. *
  14824. * @listens mousedown
  14825. */
  14826. ;
  14827. _proto.handleMouseDown = function handleMouseDown(event) {
  14828. if (!isSingleLeftClick(event)) {
  14829. return;
  14830. }
  14831. _Slider.prototype.handleMouseDown.call(this, event);
  14832. }
  14833. /**
  14834. * Handle movement events on the {@link VolumeMenuButton}.
  14835. *
  14836. * @param {EventTarget~Event} event
  14837. * The event that caused this function to run.
  14838. *
  14839. * @listens mousemove
  14840. */
  14841. ;
  14842. _proto.handleMouseMove = function handleMouseMove(event) {
  14843. var mouseVolumeLevelDisplay = this.getChild('mouseVolumeLevelDisplay');
  14844. if (mouseVolumeLevelDisplay) {
  14845. var volumeBarEl = this.el();
  14846. var volumeBarRect = getBoundingClientRect(volumeBarEl);
  14847. var vertical = this.vertical();
  14848. var volumeBarPoint = getPointerPosition(volumeBarEl, event);
  14849. volumeBarPoint = vertical ? volumeBarPoint.y : volumeBarPoint.x; // The default skin has a gap on either side of the `VolumeBar`. This means
  14850. // that it's possible to trigger this behavior outside the boundaries of
  14851. // the `VolumeBar`. This ensures we stay within it at all times.
  14852. volumeBarPoint = clamp(volumeBarPoint, 0, 1);
  14853. mouseVolumeLevelDisplay.update(volumeBarRect, volumeBarPoint, vertical);
  14854. }
  14855. if (!isSingleLeftClick(event)) {
  14856. return;
  14857. }
  14858. this.checkMuted();
  14859. this.player_.volume(this.calculateDistance(event));
  14860. }
  14861. /**
  14862. * If the player is muted unmute it.
  14863. */
  14864. ;
  14865. _proto.checkMuted = function checkMuted() {
  14866. if (this.player_.muted()) {
  14867. this.player_.muted(false);
  14868. }
  14869. }
  14870. /**
  14871. * Get percent of volume level
  14872. *
  14873. * @return {number}
  14874. * Volume level percent as a decimal number.
  14875. */
  14876. ;
  14877. _proto.getPercent = function getPercent() {
  14878. if (this.player_.muted()) {
  14879. return 0;
  14880. }
  14881. return this.player_.volume();
  14882. }
  14883. /**
  14884. * Increase volume level for keyboard users
  14885. */
  14886. ;
  14887. _proto.stepForward = function stepForward() {
  14888. this.checkMuted();
  14889. this.player_.volume(this.player_.volume() + 0.1);
  14890. }
  14891. /**
  14892. * Decrease volume level for keyboard users
  14893. */
  14894. ;
  14895. _proto.stepBack = function stepBack() {
  14896. this.checkMuted();
  14897. this.player_.volume(this.player_.volume() - 0.1);
  14898. }
  14899. /**
  14900. * Update ARIA accessibility attributes
  14901. *
  14902. * @param {EventTarget~Event} [event]
  14903. * The `volumechange` event that caused this function to run.
  14904. *
  14905. * @listens Player#volumechange
  14906. */
  14907. ;
  14908. _proto.updateARIAAttributes = function updateARIAAttributes(event) {
  14909. var ariaValue = this.player_.muted() ? 0 : this.volumeAsPercentage_();
  14910. this.el_.setAttribute('aria-valuenow', ariaValue);
  14911. this.el_.setAttribute('aria-valuetext', ariaValue + '%');
  14912. }
  14913. /**
  14914. * Returns the current value of the player volume as a percentage
  14915. *
  14916. * @private
  14917. */
  14918. ;
  14919. _proto.volumeAsPercentage_ = function volumeAsPercentage_() {
  14920. return Math.round(this.player_.volume() * 100);
  14921. }
  14922. /**
  14923. * When user starts dragging the VolumeBar, store the volume and listen for
  14924. * the end of the drag. When the drag ends, if the volume was set to zero,
  14925. * set lastVolume to the stored volume.
  14926. *
  14927. * @listens slideractive
  14928. * @private
  14929. */
  14930. ;
  14931. _proto.updateLastVolume_ = function updateLastVolume_() {
  14932. var _this2 = this;
  14933. var volumeBeforeDrag = this.player_.volume();
  14934. this.one('sliderinactive', function () {
  14935. if (_this2.player_.volume() === 0) {
  14936. _this2.player_.lastVolume_(volumeBeforeDrag);
  14937. }
  14938. });
  14939. };
  14940. return VolumeBar;
  14941. }(Slider);
  14942. /**
  14943. * Default options for the `VolumeBar`
  14944. *
  14945. * @type {Object}
  14946. * @private
  14947. */
  14948. VolumeBar.prototype.options_ = {
  14949. children: ['volumeLevel'],
  14950. barName: 'volumeLevel'
  14951. }; // MouseVolumeLevelDisplay tooltip should not be added to a player on mobile devices
  14952. if (!IS_IOS && !IS_ANDROID) {
  14953. VolumeBar.prototype.options_.children.splice(0, 0, 'mouseVolumeLevelDisplay');
  14954. }
  14955. /**
  14956. * Call the update event for this Slider when this event happens on the player.
  14957. *
  14958. * @type {string}
  14959. */
  14960. VolumeBar.prototype.playerEvent = 'volumechange';
  14961. Component$1.registerComponent('VolumeBar', VolumeBar);
  14962. /**
  14963. * The component for controlling the volume level
  14964. *
  14965. * @extends Component
  14966. */
  14967. var VolumeControl = /*#__PURE__*/function (_Component) {
  14968. inheritsLoose(VolumeControl, _Component);
  14969. /**
  14970. * Creates an instance of this class.
  14971. *
  14972. * @param {Player} player
  14973. * The `Player` that this class should be attached to.
  14974. *
  14975. * @param {Object} [options={}]
  14976. * The key/value store of player options.
  14977. */
  14978. function VolumeControl(player, options) {
  14979. var _this;
  14980. if (options === void 0) {
  14981. options = {};
  14982. }
  14983. options.vertical = options.vertical || false; // Pass the vertical option down to the VolumeBar if
  14984. // the VolumeBar is turned on.
  14985. if (typeof options.volumeBar === 'undefined' || isPlain(options.volumeBar)) {
  14986. options.volumeBar = options.volumeBar || {};
  14987. options.volumeBar.vertical = options.vertical;
  14988. }
  14989. _this = _Component.call(this, player, options) || this; // hide this control if volume support is missing
  14990. checkVolumeSupport(assertThisInitialized(_this), player);
  14991. _this.throttledHandleMouseMove = throttle(bind(assertThisInitialized(_this), _this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
  14992. _this.handleMouseUpHandler_ = function (e) {
  14993. return _this.handleMouseUp(e);
  14994. };
  14995. _this.on('mousedown', function (e) {
  14996. return _this.handleMouseDown(e);
  14997. });
  14998. _this.on('touchstart', function (e) {
  14999. return _this.handleMouseDown(e);
  15000. });
  15001. _this.on('mousemove', function (e) {
  15002. return _this.handleMouseMove(e);
  15003. }); // while the slider is active (the mouse has been pressed down and
  15004. // is dragging) or in focus we do not want to hide the VolumeBar
  15005. _this.on(_this.volumeBar, ['focus', 'slideractive'], function () {
  15006. _this.volumeBar.addClass('vjs-slider-active');
  15007. _this.addClass('vjs-slider-active');
  15008. _this.trigger('slideractive');
  15009. });
  15010. _this.on(_this.volumeBar, ['blur', 'sliderinactive'], function () {
  15011. _this.volumeBar.removeClass('vjs-slider-active');
  15012. _this.removeClass('vjs-slider-active');
  15013. _this.trigger('sliderinactive');
  15014. });
  15015. return _this;
  15016. }
  15017. /**
  15018. * Create the `Component`'s DOM element
  15019. *
  15020. * @return {Element}
  15021. * The element that was created.
  15022. */
  15023. var _proto = VolumeControl.prototype;
  15024. _proto.createEl = function createEl() {
  15025. var orientationClass = 'vjs-volume-horizontal';
  15026. if (this.options_.vertical) {
  15027. orientationClass = 'vjs-volume-vertical';
  15028. }
  15029. return _Component.prototype.createEl.call(this, 'div', {
  15030. className: "vjs-volume-control vjs-control " + orientationClass
  15031. });
  15032. }
  15033. /**
  15034. * Handle `mousedown` or `touchstart` events on the `VolumeControl`.
  15035. *
  15036. * @param {EventTarget~Event} event
  15037. * `mousedown` or `touchstart` event that triggered this function
  15038. *
  15039. * @listens mousedown
  15040. * @listens touchstart
  15041. */
  15042. ;
  15043. _proto.handleMouseDown = function handleMouseDown(event) {
  15044. var doc = this.el_.ownerDocument;
  15045. this.on(doc, 'mousemove', this.throttledHandleMouseMove);
  15046. this.on(doc, 'touchmove', this.throttledHandleMouseMove);
  15047. this.on(doc, 'mouseup', this.handleMouseUpHandler_);
  15048. this.on(doc, 'touchend', this.handleMouseUpHandler_);
  15049. }
  15050. /**
  15051. * Handle `mouseup` or `touchend` events on the `VolumeControl`.
  15052. *
  15053. * @param {EventTarget~Event} event
  15054. * `mouseup` or `touchend` event that triggered this function.
  15055. *
  15056. * @listens touchend
  15057. * @listens mouseup
  15058. */
  15059. ;
  15060. _proto.handleMouseUp = function handleMouseUp(event) {
  15061. var doc = this.el_.ownerDocument;
  15062. this.off(doc, 'mousemove', this.throttledHandleMouseMove);
  15063. this.off(doc, 'touchmove', this.throttledHandleMouseMove);
  15064. this.off(doc, 'mouseup', this.handleMouseUpHandler_);
  15065. this.off(doc, 'touchend', this.handleMouseUpHandler_);
  15066. }
  15067. /**
  15068. * Handle `mousedown` or `touchstart` events on the `VolumeControl`.
  15069. *
  15070. * @param {EventTarget~Event} event
  15071. * `mousedown` or `touchstart` event that triggered this function
  15072. *
  15073. * @listens mousedown
  15074. * @listens touchstart
  15075. */
  15076. ;
  15077. _proto.handleMouseMove = function handleMouseMove(event) {
  15078. this.volumeBar.handleMouseMove(event);
  15079. };
  15080. return VolumeControl;
  15081. }(Component$1);
  15082. /**
  15083. * Default options for the `VolumeControl`
  15084. *
  15085. * @type {Object}
  15086. * @private
  15087. */
  15088. VolumeControl.prototype.options_ = {
  15089. children: ['volumeBar']
  15090. };
  15091. Component$1.registerComponent('VolumeControl', VolumeControl);
  15092. /**
  15093. * Check if muting volume is supported and if it isn't hide the mute toggle
  15094. * button.
  15095. *
  15096. * @param {Component} self
  15097. * A reference to the mute toggle button
  15098. *
  15099. * @param {Player} player
  15100. * A reference to the player
  15101. *
  15102. * @private
  15103. */
  15104. var checkMuteSupport = function checkMuteSupport(self, player) {
  15105. // hide mute toggle button if it's not supported by the current tech
  15106. if (player.tech_ && !player.tech_.featuresMuteControl) {
  15107. self.addClass('vjs-hidden');
  15108. }
  15109. self.on(player, 'loadstart', function () {
  15110. if (!player.tech_.featuresMuteControl) {
  15111. self.addClass('vjs-hidden');
  15112. } else {
  15113. self.removeClass('vjs-hidden');
  15114. }
  15115. });
  15116. };
  15117. /**
  15118. * A button component for muting the audio.
  15119. *
  15120. * @extends Button
  15121. */
  15122. var MuteToggle = /*#__PURE__*/function (_Button) {
  15123. inheritsLoose(MuteToggle, _Button);
  15124. /**
  15125. * Creates an instance of this class.
  15126. *
  15127. * @param {Player} player
  15128. * The `Player` that this class should be attached to.
  15129. *
  15130. * @param {Object} [options]
  15131. * The key/value store of player options.
  15132. */
  15133. function MuteToggle(player, options) {
  15134. var _this;
  15135. _this = _Button.call(this, player, options) || this; // hide this control if volume support is missing
  15136. checkMuteSupport(assertThisInitialized(_this), player);
  15137. _this.on(player, ['loadstart', 'volumechange'], function (e) {
  15138. return _this.update(e);
  15139. });
  15140. return _this;
  15141. }
  15142. /**
  15143. * Builds the default DOM `className`.
  15144. *
  15145. * @return {string}
  15146. * The DOM `className` for this object.
  15147. */
  15148. var _proto = MuteToggle.prototype;
  15149. _proto.buildCSSClass = function buildCSSClass() {
  15150. return "vjs-mute-control " + _Button.prototype.buildCSSClass.call(this);
  15151. }
  15152. /**
  15153. * This gets called when an `MuteToggle` is "clicked". See
  15154. * {@link ClickableComponent} for more detailed information on what a click can be.
  15155. *
  15156. * @param {EventTarget~Event} [event]
  15157. * The `keydown`, `tap`, or `click` event that caused this function to be
  15158. * called.
  15159. *
  15160. * @listens tap
  15161. * @listens click
  15162. */
  15163. ;
  15164. _proto.handleClick = function handleClick(event) {
  15165. var vol = this.player_.volume();
  15166. var lastVolume = this.player_.lastVolume_();
  15167. if (vol === 0) {
  15168. var volumeToSet = lastVolume < 0.1 ? 0.1 : lastVolume;
  15169. this.player_.volume(volumeToSet);
  15170. this.player_.muted(false);
  15171. } else {
  15172. this.player_.muted(this.player_.muted() ? false : true);
  15173. }
  15174. }
  15175. /**
  15176. * Update the `MuteToggle` button based on the state of `volume` and `muted`
  15177. * on the player.
  15178. *
  15179. * @param {EventTarget~Event} [event]
  15180. * The {@link Player#loadstart} event if this function was called
  15181. * through an event.
  15182. *
  15183. * @listens Player#loadstart
  15184. * @listens Player#volumechange
  15185. */
  15186. ;
  15187. _proto.update = function update(event) {
  15188. this.updateIcon_();
  15189. this.updateControlText_();
  15190. }
  15191. /**
  15192. * Update the appearance of the `MuteToggle` icon.
  15193. *
  15194. * Possible states (given `level` variable below):
  15195. * - 0: crossed out
  15196. * - 1: zero bars of volume
  15197. * - 2: one bar of volume
  15198. * - 3: two bars of volume
  15199. *
  15200. * @private
  15201. */
  15202. ;
  15203. _proto.updateIcon_ = function updateIcon_() {
  15204. var vol = this.player_.volume();
  15205. var level = 3; // in iOS when a player is loaded with muted attribute
  15206. // and volume is changed with a native mute button
  15207. // we want to make sure muted state is updated
  15208. if (IS_IOS && this.player_.tech_ && this.player_.tech_.el_) {
  15209. this.player_.muted(this.player_.tech_.el_.muted);
  15210. }
  15211. if (vol === 0 || this.player_.muted()) {
  15212. level = 0;
  15213. } else if (vol < 0.33) {
  15214. level = 1;
  15215. } else if (vol < 0.67) {
  15216. level = 2;
  15217. } // TODO improve muted icon classes
  15218. for (var i = 0; i < 4; i++) {
  15219. removeClass(this.el_, "vjs-vol-" + i);
  15220. }
  15221. addClass(this.el_, "vjs-vol-" + level);
  15222. }
  15223. /**
  15224. * If `muted` has changed on the player, update the control text
  15225. * (`title` attribute on `vjs-mute-control` element and content of
  15226. * `vjs-control-text` element).
  15227. *
  15228. * @private
  15229. */
  15230. ;
  15231. _proto.updateControlText_ = function updateControlText_() {
  15232. var soundOff = this.player_.muted() || this.player_.volume() === 0;
  15233. var text = soundOff ? 'Unmute' : 'Mute';
  15234. if (this.controlText() !== text) {
  15235. this.controlText(text);
  15236. }
  15237. };
  15238. return MuteToggle;
  15239. }(Button);
  15240. /**
  15241. * The text that should display over the `MuteToggle`s controls. Added for localization.
  15242. *
  15243. * @type {string}
  15244. * @private
  15245. */
  15246. MuteToggle.prototype.controlText_ = 'Mute';
  15247. Component$1.registerComponent('MuteToggle', MuteToggle);
  15248. /**
  15249. * A Component to contain the MuteToggle and VolumeControl so that
  15250. * they can work together.
  15251. *
  15252. * @extends Component
  15253. */
  15254. var VolumePanel = /*#__PURE__*/function (_Component) {
  15255. inheritsLoose(VolumePanel, _Component);
  15256. /**
  15257. * Creates an instance of this class.
  15258. *
  15259. * @param {Player} player
  15260. * The `Player` that this class should be attached to.
  15261. *
  15262. * @param {Object} [options={}]
  15263. * The key/value store of player options.
  15264. */
  15265. function VolumePanel(player, options) {
  15266. var _this;
  15267. if (options === void 0) {
  15268. options = {};
  15269. }
  15270. if (typeof options.inline !== 'undefined') {
  15271. options.inline = options.inline;
  15272. } else {
  15273. options.inline = true;
  15274. } // pass the inline option down to the VolumeControl as vertical if
  15275. // the VolumeControl is on.
  15276. if (typeof options.volumeControl === 'undefined' || isPlain(options.volumeControl)) {
  15277. options.volumeControl = options.volumeControl || {};
  15278. options.volumeControl.vertical = !options.inline;
  15279. }
  15280. _this = _Component.call(this, player, options) || this; // this handler is used by mouse handler methods below
  15281. _this.handleKeyPressHandler_ = function (e) {
  15282. return _this.handleKeyPress(e);
  15283. };
  15284. _this.on(player, ['loadstart'], function (e) {
  15285. return _this.volumePanelState_(e);
  15286. });
  15287. _this.on(_this.muteToggle, 'keyup', function (e) {
  15288. return _this.handleKeyPress(e);
  15289. });
  15290. _this.on(_this.volumeControl, 'keyup', function (e) {
  15291. return _this.handleVolumeControlKeyUp(e);
  15292. });
  15293. _this.on('keydown', function (e) {
  15294. return _this.handleKeyPress(e);
  15295. });
  15296. _this.on('mouseover', function (e) {
  15297. return _this.handleMouseOver(e);
  15298. });
  15299. _this.on('mouseout', function (e) {
  15300. return _this.handleMouseOut(e);
  15301. }); // while the slider is active (the mouse has been pressed down and
  15302. // is dragging) we do not want to hide the VolumeBar
  15303. _this.on(_this.volumeControl, ['slideractive'], _this.sliderActive_);
  15304. _this.on(_this.volumeControl, ['sliderinactive'], _this.sliderInactive_);
  15305. return _this;
  15306. }
  15307. /**
  15308. * Add vjs-slider-active class to the VolumePanel
  15309. *
  15310. * @listens VolumeControl#slideractive
  15311. * @private
  15312. */
  15313. var _proto = VolumePanel.prototype;
  15314. _proto.sliderActive_ = function sliderActive_() {
  15315. this.addClass('vjs-slider-active');
  15316. }
  15317. /**
  15318. * Removes vjs-slider-active class to the VolumePanel
  15319. *
  15320. * @listens VolumeControl#sliderinactive
  15321. * @private
  15322. */
  15323. ;
  15324. _proto.sliderInactive_ = function sliderInactive_() {
  15325. this.removeClass('vjs-slider-active');
  15326. }
  15327. /**
  15328. * Adds vjs-hidden or vjs-mute-toggle-only to the VolumePanel
  15329. * depending on MuteToggle and VolumeControl state
  15330. *
  15331. * @listens Player#loadstart
  15332. * @private
  15333. */
  15334. ;
  15335. _proto.volumePanelState_ = function volumePanelState_() {
  15336. // hide volume panel if neither volume control or mute toggle
  15337. // are displayed
  15338. if (this.volumeControl.hasClass('vjs-hidden') && this.muteToggle.hasClass('vjs-hidden')) {
  15339. this.addClass('vjs-hidden');
  15340. } // if only mute toggle is visible we don't want
  15341. // volume panel expanding when hovered or active
  15342. if (this.volumeControl.hasClass('vjs-hidden') && !this.muteToggle.hasClass('vjs-hidden')) {
  15343. this.addClass('vjs-mute-toggle-only');
  15344. }
  15345. }
  15346. /**
  15347. * Create the `Component`'s DOM element
  15348. *
  15349. * @return {Element}
  15350. * The element that was created.
  15351. */
  15352. ;
  15353. _proto.createEl = function createEl() {
  15354. var orientationClass = 'vjs-volume-panel-horizontal';
  15355. if (!this.options_.inline) {
  15356. orientationClass = 'vjs-volume-panel-vertical';
  15357. }
  15358. return _Component.prototype.createEl.call(this, 'div', {
  15359. className: "vjs-volume-panel vjs-control " + orientationClass
  15360. });
  15361. }
  15362. /**
  15363. * Dispose of the `volume-panel` and all child components.
  15364. */
  15365. ;
  15366. _proto.dispose = function dispose() {
  15367. this.handleMouseOut();
  15368. _Component.prototype.dispose.call(this);
  15369. }
  15370. /**
  15371. * Handles `keyup` events on the `VolumeControl`, looking for ESC, which closes
  15372. * the volume panel and sets focus on `MuteToggle`.
  15373. *
  15374. * @param {EventTarget~Event} event
  15375. * The `keyup` event that caused this function to be called.
  15376. *
  15377. * @listens keyup
  15378. */
  15379. ;
  15380. _proto.handleVolumeControlKeyUp = function handleVolumeControlKeyUp(event) {
  15381. if (keycode.isEventKey(event, 'Esc')) {
  15382. this.muteToggle.focus();
  15383. }
  15384. }
  15385. /**
  15386. * This gets called when a `VolumePanel` gains hover via a `mouseover` event.
  15387. * Turns on listening for `mouseover` event. When they happen it
  15388. * calls `this.handleMouseOver`.
  15389. *
  15390. * @param {EventTarget~Event} event
  15391. * The `mouseover` event that caused this function to be called.
  15392. *
  15393. * @listens mouseover
  15394. */
  15395. ;
  15396. _proto.handleMouseOver = function handleMouseOver(event) {
  15397. this.addClass('vjs-hover');
  15398. on(document, 'keyup', this.handleKeyPressHandler_);
  15399. }
  15400. /**
  15401. * This gets called when a `VolumePanel` gains hover via a `mouseout` event.
  15402. * Turns on listening for `mouseout` event. When they happen it
  15403. * calls `this.handleMouseOut`.
  15404. *
  15405. * @param {EventTarget~Event} event
  15406. * The `mouseout` event that caused this function to be called.
  15407. *
  15408. * @listens mouseout
  15409. */
  15410. ;
  15411. _proto.handleMouseOut = function handleMouseOut(event) {
  15412. this.removeClass('vjs-hover');
  15413. off(document, 'keyup', this.handleKeyPressHandler_);
  15414. }
  15415. /**
  15416. * Handles `keyup` event on the document or `keydown` event on the `VolumePanel`,
  15417. * looking for ESC, which hides the `VolumeControl`.
  15418. *
  15419. * @param {EventTarget~Event} event
  15420. * The keypress that triggered this event.
  15421. *
  15422. * @listens keydown | keyup
  15423. */
  15424. ;
  15425. _proto.handleKeyPress = function handleKeyPress(event) {
  15426. if (keycode.isEventKey(event, 'Esc')) {
  15427. this.handleMouseOut();
  15428. }
  15429. };
  15430. return VolumePanel;
  15431. }(Component$1);
  15432. /**
  15433. * Default options for the `VolumeControl`
  15434. *
  15435. * @type {Object}
  15436. * @private
  15437. */
  15438. VolumePanel.prototype.options_ = {
  15439. children: ['muteToggle', 'volumeControl']
  15440. };
  15441. Component$1.registerComponent('VolumePanel', VolumePanel);
  15442. /**
  15443. * The Menu component is used to build popup menus, including subtitle and
  15444. * captions selection menus.
  15445. *
  15446. * @extends Component
  15447. */
  15448. var Menu = /*#__PURE__*/function (_Component) {
  15449. inheritsLoose(Menu, _Component);
  15450. /**
  15451. * Create an instance of this class.
  15452. *
  15453. * @param {Player} player
  15454. * the player that this component should attach to
  15455. *
  15456. * @param {Object} [options]
  15457. * Object of option names and values
  15458. *
  15459. */
  15460. function Menu(player, options) {
  15461. var _this;
  15462. _this = _Component.call(this, player, options) || this;
  15463. if (options) {
  15464. _this.menuButton_ = options.menuButton;
  15465. }
  15466. _this.focusedChild_ = -1;
  15467. _this.on('keydown', function (e) {
  15468. return _this.handleKeyDown(e);
  15469. }); // All the menu item instances share the same blur handler provided by the menu container.
  15470. _this.boundHandleBlur_ = function (e) {
  15471. return _this.handleBlur(e);
  15472. };
  15473. _this.boundHandleTapClick_ = function (e) {
  15474. return _this.handleTapClick(e);
  15475. };
  15476. return _this;
  15477. }
  15478. /**
  15479. * Add event listeners to the {@link MenuItem}.
  15480. *
  15481. * @param {Object} component
  15482. * The instance of the `MenuItem` to add listeners to.
  15483. *
  15484. */
  15485. var _proto = Menu.prototype;
  15486. _proto.addEventListenerForItem = function addEventListenerForItem(component) {
  15487. if (!(component instanceof Component$1)) {
  15488. return;
  15489. }
  15490. this.on(component, 'blur', this.boundHandleBlur_);
  15491. this.on(component, ['tap', 'click'], this.boundHandleTapClick_);
  15492. }
  15493. /**
  15494. * Remove event listeners from the {@link MenuItem}.
  15495. *
  15496. * @param {Object} component
  15497. * The instance of the `MenuItem` to remove listeners.
  15498. *
  15499. */
  15500. ;
  15501. _proto.removeEventListenerForItem = function removeEventListenerForItem(component) {
  15502. if (!(component instanceof Component$1)) {
  15503. return;
  15504. }
  15505. this.off(component, 'blur', this.boundHandleBlur_);
  15506. this.off(component, ['tap', 'click'], this.boundHandleTapClick_);
  15507. }
  15508. /**
  15509. * This method will be called indirectly when the component has been added
  15510. * before the component adds to the new menu instance by `addItem`.
  15511. * In this case, the original menu instance will remove the component
  15512. * by calling `removeChild`.
  15513. *
  15514. * @param {Object} component
  15515. * The instance of the `MenuItem`
  15516. */
  15517. ;
  15518. _proto.removeChild = function removeChild(component) {
  15519. if (typeof component === 'string') {
  15520. component = this.getChild(component);
  15521. }
  15522. this.removeEventListenerForItem(component);
  15523. _Component.prototype.removeChild.call(this, component);
  15524. }
  15525. /**
  15526. * Add a {@link MenuItem} to the menu.
  15527. *
  15528. * @param {Object|string} component
  15529. * The name or instance of the `MenuItem` to add.
  15530. *
  15531. */
  15532. ;
  15533. _proto.addItem = function addItem(component) {
  15534. var childComponent = this.addChild(component);
  15535. if (childComponent) {
  15536. this.addEventListenerForItem(childComponent);
  15537. }
  15538. }
  15539. /**
  15540. * Create the `Menu`s DOM element.
  15541. *
  15542. * @return {Element}
  15543. * the element that was created
  15544. */
  15545. ;
  15546. _proto.createEl = function createEl$1() {
  15547. var contentElType = this.options_.contentElType || 'ul';
  15548. this.contentEl_ = createEl(contentElType, {
  15549. className: 'vjs-menu-content'
  15550. });
  15551. this.contentEl_.setAttribute('role', 'menu');
  15552. var el = _Component.prototype.createEl.call(this, 'div', {
  15553. append: this.contentEl_,
  15554. className: 'vjs-menu'
  15555. });
  15556. el.appendChild(this.contentEl_); // Prevent clicks from bubbling up. Needed for Menu Buttons,
  15557. // where a click on the parent is significant
  15558. on(el, 'click', function (event) {
  15559. event.preventDefault();
  15560. event.stopImmediatePropagation();
  15561. });
  15562. return el;
  15563. };
  15564. _proto.dispose = function dispose() {
  15565. this.contentEl_ = null;
  15566. this.boundHandleBlur_ = null;
  15567. this.boundHandleTapClick_ = null;
  15568. _Component.prototype.dispose.call(this);
  15569. }
  15570. /**
  15571. * Called when a `MenuItem` loses focus.
  15572. *
  15573. * @param {EventTarget~Event} event
  15574. * The `blur` event that caused this function to be called.
  15575. *
  15576. * @listens blur
  15577. */
  15578. ;
  15579. _proto.handleBlur = function handleBlur(event) {
  15580. var relatedTarget = event.relatedTarget || document.activeElement; // Close menu popup when a user clicks outside the menu
  15581. if (!this.children().some(function (element) {
  15582. return element.el() === relatedTarget;
  15583. })) {
  15584. var btn = this.menuButton_;
  15585. if (btn && btn.buttonPressed_ && relatedTarget !== btn.el().firstChild) {
  15586. btn.unpressButton();
  15587. }
  15588. }
  15589. }
  15590. /**
  15591. * Called when a `MenuItem` gets clicked or tapped.
  15592. *
  15593. * @param {EventTarget~Event} event
  15594. * The `click` or `tap` event that caused this function to be called.
  15595. *
  15596. * @listens click,tap
  15597. */
  15598. ;
  15599. _proto.handleTapClick = function handleTapClick(event) {
  15600. // Unpress the associated MenuButton, and move focus back to it
  15601. if (this.menuButton_) {
  15602. this.menuButton_.unpressButton();
  15603. var childComponents = this.children();
  15604. if (!Array.isArray(childComponents)) {
  15605. return;
  15606. }
  15607. var foundComponent = childComponents.filter(function (component) {
  15608. return component.el() === event.target;
  15609. })[0];
  15610. if (!foundComponent) {
  15611. return;
  15612. } // don't focus menu button if item is a caption settings item
  15613. // because focus will move elsewhere
  15614. if (foundComponent.name() !== 'CaptionSettingsMenuItem') {
  15615. this.menuButton_.focus();
  15616. }
  15617. }
  15618. }
  15619. /**
  15620. * Handle a `keydown` event on this menu. This listener is added in the constructor.
  15621. *
  15622. * @param {EventTarget~Event} event
  15623. * A `keydown` event that happened on the menu.
  15624. *
  15625. * @listens keydown
  15626. */
  15627. ;
  15628. _proto.handleKeyDown = function handleKeyDown(event) {
  15629. // Left and Down Arrows
  15630. if (keycode.isEventKey(event, 'Left') || keycode.isEventKey(event, 'Down')) {
  15631. event.preventDefault();
  15632. event.stopPropagation();
  15633. this.stepForward(); // Up and Right Arrows
  15634. } else if (keycode.isEventKey(event, 'Right') || keycode.isEventKey(event, 'Up')) {
  15635. event.preventDefault();
  15636. event.stopPropagation();
  15637. this.stepBack();
  15638. }
  15639. }
  15640. /**
  15641. * Move to next (lower) menu item for keyboard users.
  15642. */
  15643. ;
  15644. _proto.stepForward = function stepForward() {
  15645. var stepChild = 0;
  15646. if (this.focusedChild_ !== undefined) {
  15647. stepChild = this.focusedChild_ + 1;
  15648. }
  15649. this.focus(stepChild);
  15650. }
  15651. /**
  15652. * Move to previous (higher) menu item for keyboard users.
  15653. */
  15654. ;
  15655. _proto.stepBack = function stepBack() {
  15656. var stepChild = 0;
  15657. if (this.focusedChild_ !== undefined) {
  15658. stepChild = this.focusedChild_ - 1;
  15659. }
  15660. this.focus(stepChild);
  15661. }
  15662. /**
  15663. * Set focus on a {@link MenuItem} in the `Menu`.
  15664. *
  15665. * @param {Object|string} [item=0]
  15666. * Index of child item set focus on.
  15667. */
  15668. ;
  15669. _proto.focus = function focus(item) {
  15670. if (item === void 0) {
  15671. item = 0;
  15672. }
  15673. var children = this.children().slice();
  15674. var haveTitle = children.length && children[0].hasClass('vjs-menu-title');
  15675. if (haveTitle) {
  15676. children.shift();
  15677. }
  15678. if (children.length > 0) {
  15679. if (item < 0) {
  15680. item = 0;
  15681. } else if (item >= children.length) {
  15682. item = children.length - 1;
  15683. }
  15684. this.focusedChild_ = item;
  15685. children[item].el_.focus();
  15686. }
  15687. };
  15688. return Menu;
  15689. }(Component$1);
  15690. Component$1.registerComponent('Menu', Menu);
  15691. /**
  15692. * A `MenuButton` class for any popup {@link Menu}.
  15693. *
  15694. * @extends Component
  15695. */
  15696. var MenuButton = /*#__PURE__*/function (_Component) {
  15697. inheritsLoose(MenuButton, _Component);
  15698. /**
  15699. * Creates an instance of this class.
  15700. *
  15701. * @param {Player} player
  15702. * The `Player` that this class should be attached to.
  15703. *
  15704. * @param {Object} [options={}]
  15705. * The key/value store of player options.
  15706. */
  15707. function MenuButton(player, options) {
  15708. var _this;
  15709. if (options === void 0) {
  15710. options = {};
  15711. }
  15712. _this = _Component.call(this, player, options) || this;
  15713. _this.menuButton_ = new Button(player, options);
  15714. _this.menuButton_.controlText(_this.controlText_);
  15715. _this.menuButton_.el_.setAttribute('aria-haspopup', 'true'); // Add buildCSSClass values to the button, not the wrapper
  15716. var buttonClass = Button.prototype.buildCSSClass();
  15717. _this.menuButton_.el_.className = _this.buildCSSClass() + ' ' + buttonClass;
  15718. _this.menuButton_.removeClass('vjs-control');
  15719. _this.addChild(_this.menuButton_);
  15720. _this.update();
  15721. _this.enabled_ = true;
  15722. var handleClick = function handleClick(e) {
  15723. return _this.handleClick(e);
  15724. };
  15725. _this.handleMenuKeyUp_ = function (e) {
  15726. return _this.handleMenuKeyUp(e);
  15727. };
  15728. _this.on(_this.menuButton_, 'tap', handleClick);
  15729. _this.on(_this.menuButton_, 'click', handleClick);
  15730. _this.on(_this.menuButton_, 'keydown', function (e) {
  15731. return _this.handleKeyDown(e);
  15732. });
  15733. _this.on(_this.menuButton_, 'mouseenter', function () {
  15734. _this.addClass('vjs-hover');
  15735. _this.menu.show();
  15736. on(document, 'keyup', _this.handleMenuKeyUp_);
  15737. });
  15738. _this.on('mouseleave', function (e) {
  15739. return _this.handleMouseLeave(e);
  15740. });
  15741. _this.on('keydown', function (e) {
  15742. return _this.handleSubmenuKeyDown(e);
  15743. });
  15744. return _this;
  15745. }
  15746. /**
  15747. * Update the menu based on the current state of its items.
  15748. */
  15749. var _proto = MenuButton.prototype;
  15750. _proto.update = function update() {
  15751. var menu = this.createMenu();
  15752. if (this.menu) {
  15753. this.menu.dispose();
  15754. this.removeChild(this.menu);
  15755. }
  15756. this.menu = menu;
  15757. this.addChild(menu);
  15758. /**
  15759. * Track the state of the menu button
  15760. *
  15761. * @type {Boolean}
  15762. * @private
  15763. */
  15764. this.buttonPressed_ = false;
  15765. this.menuButton_.el_.setAttribute('aria-expanded', 'false');
  15766. if (this.items && this.items.length <= this.hideThreshold_) {
  15767. this.hide();
  15768. this.menu.contentEl_.removeAttribute('role');
  15769. } else {
  15770. this.show();
  15771. this.menu.contentEl_.setAttribute('role', 'menu');
  15772. }
  15773. }
  15774. /**
  15775. * Create the menu and add all items to it.
  15776. *
  15777. * @return {Menu}
  15778. * The constructed menu
  15779. */
  15780. ;
  15781. _proto.createMenu = function createMenu() {
  15782. var menu = new Menu(this.player_, {
  15783. menuButton: this
  15784. });
  15785. /**
  15786. * Hide the menu if the number of items is less than or equal to this threshold. This defaults
  15787. * to 0 and whenever we add items which can be hidden to the menu we'll increment it. We list
  15788. * it here because every time we run `createMenu` we need to reset the value.
  15789. *
  15790. * @protected
  15791. * @type {Number}
  15792. */
  15793. this.hideThreshold_ = 0; // Add a title list item to the top
  15794. if (this.options_.title) {
  15795. var titleEl = createEl('li', {
  15796. className: 'vjs-menu-title',
  15797. textContent: toTitleCase$1(this.options_.title),
  15798. tabIndex: -1
  15799. });
  15800. var titleComponent = new Component$1(this.player_, {
  15801. el: titleEl
  15802. });
  15803. menu.addItem(titleComponent);
  15804. }
  15805. this.items = this.createItems();
  15806. if (this.items) {
  15807. // Add menu items to the menu
  15808. for (var i = 0; i < this.items.length; i++) {
  15809. menu.addItem(this.items[i]);
  15810. }
  15811. }
  15812. return menu;
  15813. }
  15814. /**
  15815. * Create the list of menu items. Specific to each subclass.
  15816. *
  15817. * @abstract
  15818. */
  15819. ;
  15820. _proto.createItems = function createItems() {}
  15821. /**
  15822. * Create the `MenuButtons`s DOM element.
  15823. *
  15824. * @return {Element}
  15825. * The element that gets created.
  15826. */
  15827. ;
  15828. _proto.createEl = function createEl() {
  15829. return _Component.prototype.createEl.call(this, 'div', {
  15830. className: this.buildWrapperCSSClass()
  15831. }, {});
  15832. }
  15833. /**
  15834. * Allow sub components to stack CSS class names for the wrapper element
  15835. *
  15836. * @return {string}
  15837. * The constructed wrapper DOM `className`
  15838. */
  15839. ;
  15840. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  15841. var menuButtonClass = 'vjs-menu-button'; // If the inline option is passed, we want to use different styles altogether.
  15842. if (this.options_.inline === true) {
  15843. menuButtonClass += '-inline';
  15844. } else {
  15845. menuButtonClass += '-popup';
  15846. } // TODO: Fix the CSS so that this isn't necessary
  15847. var buttonClass = Button.prototype.buildCSSClass();
  15848. return "vjs-menu-button " + menuButtonClass + " " + buttonClass + " " + _Component.prototype.buildCSSClass.call(this);
  15849. }
  15850. /**
  15851. * Builds the default DOM `className`.
  15852. *
  15853. * @return {string}
  15854. * The DOM `className` for this object.
  15855. */
  15856. ;
  15857. _proto.buildCSSClass = function buildCSSClass() {
  15858. var menuButtonClass = 'vjs-menu-button'; // If the inline option is passed, we want to use different styles altogether.
  15859. if (this.options_.inline === true) {
  15860. menuButtonClass += '-inline';
  15861. } else {
  15862. menuButtonClass += '-popup';
  15863. }
  15864. return "vjs-menu-button " + menuButtonClass + " " + _Component.prototype.buildCSSClass.call(this);
  15865. }
  15866. /**
  15867. * Get or set the localized control text that will be used for accessibility.
  15868. *
  15869. * > NOTE: This will come from the internal `menuButton_` element.
  15870. *
  15871. * @param {string} [text]
  15872. * Control text for element.
  15873. *
  15874. * @param {Element} [el=this.menuButton_.el()]
  15875. * Element to set the title on.
  15876. *
  15877. * @return {string}
  15878. * - The control text when getting
  15879. */
  15880. ;
  15881. _proto.controlText = function controlText(text, el) {
  15882. if (el === void 0) {
  15883. el = this.menuButton_.el();
  15884. }
  15885. return this.menuButton_.controlText(text, el);
  15886. }
  15887. /**
  15888. * Dispose of the `menu-button` and all child components.
  15889. */
  15890. ;
  15891. _proto.dispose = function dispose() {
  15892. this.handleMouseLeave();
  15893. _Component.prototype.dispose.call(this);
  15894. }
  15895. /**
  15896. * Handle a click on a `MenuButton`.
  15897. * See {@link ClickableComponent#handleClick} for instances where this is called.
  15898. *
  15899. * @param {EventTarget~Event} event
  15900. * The `keydown`, `tap`, or `click` event that caused this function to be
  15901. * called.
  15902. *
  15903. * @listens tap
  15904. * @listens click
  15905. */
  15906. ;
  15907. _proto.handleClick = function handleClick(event) {
  15908. if (this.buttonPressed_) {
  15909. this.unpressButton();
  15910. } else {
  15911. this.pressButton();
  15912. }
  15913. }
  15914. /**
  15915. * Handle `mouseleave` for `MenuButton`.
  15916. *
  15917. * @param {EventTarget~Event} event
  15918. * The `mouseleave` event that caused this function to be called.
  15919. *
  15920. * @listens mouseleave
  15921. */
  15922. ;
  15923. _proto.handleMouseLeave = function handleMouseLeave(event) {
  15924. this.removeClass('vjs-hover');
  15925. off(document, 'keyup', this.handleMenuKeyUp_);
  15926. }
  15927. /**
  15928. * Set the focus to the actual button, not to this element
  15929. */
  15930. ;
  15931. _proto.focus = function focus() {
  15932. this.menuButton_.focus();
  15933. }
  15934. /**
  15935. * Remove the focus from the actual button, not this element
  15936. */
  15937. ;
  15938. _proto.blur = function blur() {
  15939. this.menuButton_.blur();
  15940. }
  15941. /**
  15942. * Handle tab, escape, down arrow, and up arrow keys for `MenuButton`. See
  15943. * {@link ClickableComponent#handleKeyDown} for instances where this is called.
  15944. *
  15945. * @param {EventTarget~Event} event
  15946. * The `keydown` event that caused this function to be called.
  15947. *
  15948. * @listens keydown
  15949. */
  15950. ;
  15951. _proto.handleKeyDown = function handleKeyDown(event) {
  15952. // Escape or Tab unpress the 'button'
  15953. if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) {
  15954. if (this.buttonPressed_) {
  15955. this.unpressButton();
  15956. } // Don't preventDefault for Tab key - we still want to lose focus
  15957. if (!keycode.isEventKey(event, 'Tab')) {
  15958. event.preventDefault(); // Set focus back to the menu button's button
  15959. this.menuButton_.focus();
  15960. } // Up Arrow or Down Arrow also 'press' the button to open the menu
  15961. } else if (keycode.isEventKey(event, 'Up') || keycode.isEventKey(event, 'Down')) {
  15962. if (!this.buttonPressed_) {
  15963. event.preventDefault();
  15964. this.pressButton();
  15965. }
  15966. }
  15967. }
  15968. /**
  15969. * Handle a `keyup` event on a `MenuButton`. The listener for this is added in
  15970. * the constructor.
  15971. *
  15972. * @param {EventTarget~Event} event
  15973. * Key press event
  15974. *
  15975. * @listens keyup
  15976. */
  15977. ;
  15978. _proto.handleMenuKeyUp = function handleMenuKeyUp(event) {
  15979. // Escape hides popup menu
  15980. if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) {
  15981. this.removeClass('vjs-hover');
  15982. }
  15983. }
  15984. /**
  15985. * This method name now delegates to `handleSubmenuKeyDown`. This means
  15986. * anyone calling `handleSubmenuKeyPress` will not see their method calls
  15987. * stop working.
  15988. *
  15989. * @param {EventTarget~Event} event
  15990. * The event that caused this function to be called.
  15991. */
  15992. ;
  15993. _proto.handleSubmenuKeyPress = function handleSubmenuKeyPress(event) {
  15994. this.handleSubmenuKeyDown(event);
  15995. }
  15996. /**
  15997. * Handle a `keydown` event on a sub-menu. The listener for this is added in
  15998. * the constructor.
  15999. *
  16000. * @param {EventTarget~Event} event
  16001. * Key press event
  16002. *
  16003. * @listens keydown
  16004. */
  16005. ;
  16006. _proto.handleSubmenuKeyDown = function handleSubmenuKeyDown(event) {
  16007. // Escape or Tab unpress the 'button'
  16008. if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) {
  16009. if (this.buttonPressed_) {
  16010. this.unpressButton();
  16011. } // Don't preventDefault for Tab key - we still want to lose focus
  16012. if (!keycode.isEventKey(event, 'Tab')) {
  16013. event.preventDefault(); // Set focus back to the menu button's button
  16014. this.menuButton_.focus();
  16015. }
  16016. }
  16017. }
  16018. /**
  16019. * Put the current `MenuButton` into a pressed state.
  16020. */
  16021. ;
  16022. _proto.pressButton = function pressButton() {
  16023. if (this.enabled_) {
  16024. this.buttonPressed_ = true;
  16025. this.menu.show();
  16026. this.menu.lockShowing();
  16027. this.menuButton_.el_.setAttribute('aria-expanded', 'true'); // set the focus into the submenu, except on iOS where it is resulting in
  16028. // undesired scrolling behavior when the player is in an iframe
  16029. if (IS_IOS && isInFrame()) {
  16030. // Return early so that the menu isn't focused
  16031. return;
  16032. }
  16033. this.menu.focus();
  16034. }
  16035. }
  16036. /**
  16037. * Take the current `MenuButton` out of a pressed state.
  16038. */
  16039. ;
  16040. _proto.unpressButton = function unpressButton() {
  16041. if (this.enabled_) {
  16042. this.buttonPressed_ = false;
  16043. this.menu.unlockShowing();
  16044. this.menu.hide();
  16045. this.menuButton_.el_.setAttribute('aria-expanded', 'false');
  16046. }
  16047. }
  16048. /**
  16049. * Disable the `MenuButton`. Don't allow it to be clicked.
  16050. */
  16051. ;
  16052. _proto.disable = function disable() {
  16053. this.unpressButton();
  16054. this.enabled_ = false;
  16055. this.addClass('vjs-disabled');
  16056. this.menuButton_.disable();
  16057. }
  16058. /**
  16059. * Enable the `MenuButton`. Allow it to be clicked.
  16060. */
  16061. ;
  16062. _proto.enable = function enable() {
  16063. this.enabled_ = true;
  16064. this.removeClass('vjs-disabled');
  16065. this.menuButton_.enable();
  16066. };
  16067. return MenuButton;
  16068. }(Component$1);
  16069. Component$1.registerComponent('MenuButton', MenuButton);
  16070. /**
  16071. * The base class for buttons that toggle specific track types (e.g. subtitles).
  16072. *
  16073. * @extends MenuButton
  16074. */
  16075. var TrackButton = /*#__PURE__*/function (_MenuButton) {
  16076. inheritsLoose(TrackButton, _MenuButton);
  16077. /**
  16078. * Creates an instance of this class.
  16079. *
  16080. * @param {Player} player
  16081. * The `Player` that this class should be attached to.
  16082. *
  16083. * @param {Object} [options]
  16084. * The key/value store of player options.
  16085. */
  16086. function TrackButton(player, options) {
  16087. var _this;
  16088. var tracks = options.tracks;
  16089. _this = _MenuButton.call(this, player, options) || this;
  16090. if (_this.items.length <= 1) {
  16091. _this.hide();
  16092. }
  16093. if (!tracks) {
  16094. return assertThisInitialized(_this);
  16095. }
  16096. var updateHandler = bind(assertThisInitialized(_this), _this.update);
  16097. tracks.addEventListener('removetrack', updateHandler);
  16098. tracks.addEventListener('addtrack', updateHandler);
  16099. tracks.addEventListener('labelchange', updateHandler);
  16100. _this.player_.on('ready', updateHandler);
  16101. _this.player_.on('dispose', function () {
  16102. tracks.removeEventListener('removetrack', updateHandler);
  16103. tracks.removeEventListener('addtrack', updateHandler);
  16104. tracks.removeEventListener('labelchange', updateHandler);
  16105. });
  16106. return _this;
  16107. }
  16108. return TrackButton;
  16109. }(MenuButton);
  16110. Component$1.registerComponent('TrackButton', TrackButton);
  16111. /**
  16112. * @file menu-keys.js
  16113. */
  16114. /**
  16115. * All keys used for operation of a menu (`MenuButton`, `Menu`, and `MenuItem`)
  16116. * Note that 'Enter' and 'Space' are not included here (otherwise they would
  16117. * prevent the `MenuButton` and `MenuItem` from being keyboard-clickable)
  16118. * @typedef MenuKeys
  16119. * @array
  16120. */
  16121. var MenuKeys = ['Tab', 'Esc', 'Up', 'Down', 'Right', 'Left'];
  16122. /**
  16123. * The component for a menu item. `<li>`
  16124. *
  16125. * @extends ClickableComponent
  16126. */
  16127. var MenuItem = /*#__PURE__*/function (_ClickableComponent) {
  16128. inheritsLoose(MenuItem, _ClickableComponent);
  16129. /**
  16130. * Creates an instance of the this class.
  16131. *
  16132. * @param {Player} player
  16133. * The `Player` that this class should be attached to.
  16134. *
  16135. * @param {Object} [options={}]
  16136. * The key/value store of player options.
  16137. *
  16138. */
  16139. function MenuItem(player, options) {
  16140. var _this;
  16141. _this = _ClickableComponent.call(this, player, options) || this;
  16142. _this.selectable = options.selectable;
  16143. _this.isSelected_ = options.selected || false;
  16144. _this.multiSelectable = options.multiSelectable;
  16145. _this.selected(_this.isSelected_);
  16146. if (_this.selectable) {
  16147. if (_this.multiSelectable) {
  16148. _this.el_.setAttribute('role', 'menuitemcheckbox');
  16149. } else {
  16150. _this.el_.setAttribute('role', 'menuitemradio');
  16151. }
  16152. } else {
  16153. _this.el_.setAttribute('role', 'menuitem');
  16154. }
  16155. return _this;
  16156. }
  16157. /**
  16158. * Create the `MenuItem's DOM element
  16159. *
  16160. * @param {string} [type=li]
  16161. * Element's node type, not actually used, always set to `li`.
  16162. *
  16163. * @param {Object} [props={}]
  16164. * An object of properties that should be set on the element
  16165. *
  16166. * @param {Object} [attrs={}]
  16167. * An object of attributes that should be set on the element
  16168. *
  16169. * @return {Element}
  16170. * The element that gets created.
  16171. */
  16172. var _proto = MenuItem.prototype;
  16173. _proto.createEl = function createEl$1(type, props, attrs) {
  16174. // The control is textual, not just an icon
  16175. this.nonIconControl = true;
  16176. var el = _ClickableComponent.prototype.createEl.call(this, 'li', assign$1({
  16177. className: 'vjs-menu-item',
  16178. tabIndex: -1
  16179. }, props), attrs); // swap icon with menu item text.
  16180. el.replaceChild(createEl('span', {
  16181. className: 'vjs-menu-item-text',
  16182. textContent: this.localize(this.options_.label)
  16183. }), el.querySelector('.vjs-icon-placeholder'));
  16184. return el;
  16185. }
  16186. /**
  16187. * Ignore keys which are used by the menu, but pass any other ones up. See
  16188. * {@link ClickableComponent#handleKeyDown} for instances where this is called.
  16189. *
  16190. * @param {EventTarget~Event} event
  16191. * The `keydown` event that caused this function to be called.
  16192. *
  16193. * @listens keydown
  16194. */
  16195. ;
  16196. _proto.handleKeyDown = function handleKeyDown(event) {
  16197. if (!MenuKeys.some(function (key) {
  16198. return keycode.isEventKey(event, key);
  16199. })) {
  16200. // Pass keydown handling up for unused keys
  16201. _ClickableComponent.prototype.handleKeyDown.call(this, event);
  16202. }
  16203. }
  16204. /**
  16205. * Any click on a `MenuItem` puts it into the selected state.
  16206. * See {@link ClickableComponent#handleClick} for instances where this is called.
  16207. *
  16208. * @param {EventTarget~Event} event
  16209. * The `keydown`, `tap`, or `click` event that caused this function to be
  16210. * called.
  16211. *
  16212. * @listens tap
  16213. * @listens click
  16214. */
  16215. ;
  16216. _proto.handleClick = function handleClick(event) {
  16217. this.selected(true);
  16218. }
  16219. /**
  16220. * Set the state for this menu item as selected or not.
  16221. *
  16222. * @param {boolean} selected
  16223. * if the menu item is selected or not
  16224. */
  16225. ;
  16226. _proto.selected = function selected(_selected) {
  16227. if (this.selectable) {
  16228. if (_selected) {
  16229. this.addClass('vjs-selected');
  16230. this.el_.setAttribute('aria-checked', 'true'); // aria-checked isn't fully supported by browsers/screen readers,
  16231. // so indicate selected state to screen reader in the control text.
  16232. this.controlText(', selected');
  16233. this.isSelected_ = true;
  16234. } else {
  16235. this.removeClass('vjs-selected');
  16236. this.el_.setAttribute('aria-checked', 'false'); // Indicate un-selected state to screen reader
  16237. this.controlText('');
  16238. this.isSelected_ = false;
  16239. }
  16240. }
  16241. };
  16242. return MenuItem;
  16243. }(ClickableComponent);
  16244. Component$1.registerComponent('MenuItem', MenuItem);
  16245. /**
  16246. * The specific menu item type for selecting a language within a text track kind
  16247. *
  16248. * @extends MenuItem
  16249. */
  16250. var TextTrackMenuItem = /*#__PURE__*/function (_MenuItem) {
  16251. inheritsLoose(TextTrackMenuItem, _MenuItem);
  16252. /**
  16253. * Creates an instance of this class.
  16254. *
  16255. * @param {Player} player
  16256. * The `Player` that this class should be attached to.
  16257. *
  16258. * @param {Object} [options]
  16259. * The key/value store of player options.
  16260. */
  16261. function TextTrackMenuItem(player, options) {
  16262. var _this;
  16263. var track = options.track;
  16264. var tracks = player.textTracks(); // Modify options for parent MenuItem class's init.
  16265. options.label = track.label || track.language || 'Unknown';
  16266. options.selected = track.mode === 'showing';
  16267. _this = _MenuItem.call(this, player, options) || this;
  16268. _this.track = track; // Determine the relevant kind(s) of tracks for this component and filter
  16269. // out empty kinds.
  16270. _this.kinds = (options.kinds || [options.kind || _this.track.kind]).filter(Boolean);
  16271. var changeHandler = function changeHandler() {
  16272. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  16273. args[_key] = arguments[_key];
  16274. }
  16275. _this.handleTracksChange.apply(assertThisInitialized(_this), args);
  16276. };
  16277. var selectedLanguageChangeHandler = function selectedLanguageChangeHandler() {
  16278. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  16279. args[_key2] = arguments[_key2];
  16280. }
  16281. _this.handleSelectedLanguageChange.apply(assertThisInitialized(_this), args);
  16282. };
  16283. player.on(['loadstart', 'texttrackchange'], changeHandler);
  16284. tracks.addEventListener('change', changeHandler);
  16285. tracks.addEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
  16286. _this.on('dispose', function () {
  16287. player.off(['loadstart', 'texttrackchange'], changeHandler);
  16288. tracks.removeEventListener('change', changeHandler);
  16289. tracks.removeEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
  16290. }); // iOS7 doesn't dispatch change events to TextTrackLists when an
  16291. // associated track's mode changes. Without something like
  16292. // Object.observe() (also not present on iOS7), it's not
  16293. // possible to detect changes to the mode attribute and polyfill
  16294. // the change event. As a poor substitute, we manually dispatch
  16295. // change events whenever the controls modify the mode.
  16296. if (tracks.onchange === undefined) {
  16297. var event;
  16298. _this.on(['tap', 'click'], function () {
  16299. if (typeof window.Event !== 'object') {
  16300. // Android 2.3 throws an Illegal Constructor error for window.Event
  16301. try {
  16302. event = new window.Event('change');
  16303. } catch (err) {// continue regardless of error
  16304. }
  16305. }
  16306. if (!event) {
  16307. event = document.createEvent('Event');
  16308. event.initEvent('change', true, true);
  16309. }
  16310. tracks.dispatchEvent(event);
  16311. });
  16312. } // set the default state based on current tracks
  16313. _this.handleTracksChange();
  16314. return _this;
  16315. }
  16316. /**
  16317. * This gets called when an `TextTrackMenuItem` is "clicked". See
  16318. * {@link ClickableComponent} for more detailed information on what a click can be.
  16319. *
  16320. * @param {EventTarget~Event} event
  16321. * The `keydown`, `tap`, or `click` event that caused this function to be
  16322. * called.
  16323. *
  16324. * @listens tap
  16325. * @listens click
  16326. */
  16327. var _proto = TextTrackMenuItem.prototype;
  16328. _proto.handleClick = function handleClick(event) {
  16329. var referenceTrack = this.track;
  16330. var tracks = this.player_.textTracks();
  16331. _MenuItem.prototype.handleClick.call(this, event);
  16332. if (!tracks) {
  16333. return;
  16334. }
  16335. for (var i = 0; i < tracks.length; i++) {
  16336. var track = tracks[i]; // If the track from the text tracks list is not of the right kind,
  16337. // skip it. We do not want to affect tracks of incompatible kind(s).
  16338. if (this.kinds.indexOf(track.kind) === -1) {
  16339. continue;
  16340. } // If this text track is the component's track and it is not showing,
  16341. // set it to showing.
  16342. if (track === referenceTrack) {
  16343. if (track.mode !== 'showing') {
  16344. track.mode = 'showing';
  16345. } // If this text track is not the component's track and it is not
  16346. // disabled, set it to disabled.
  16347. } else if (track.mode !== 'disabled') {
  16348. track.mode = 'disabled';
  16349. }
  16350. }
  16351. }
  16352. /**
  16353. * Handle text track list change
  16354. *
  16355. * @param {EventTarget~Event} event
  16356. * The `change` event that caused this function to be called.
  16357. *
  16358. * @listens TextTrackList#change
  16359. */
  16360. ;
  16361. _proto.handleTracksChange = function handleTracksChange(event) {
  16362. var shouldBeSelected = this.track.mode === 'showing'; // Prevent redundant selected() calls because they may cause
  16363. // screen readers to read the appended control text unnecessarily
  16364. if (shouldBeSelected !== this.isSelected_) {
  16365. this.selected(shouldBeSelected);
  16366. }
  16367. };
  16368. _proto.handleSelectedLanguageChange = function handleSelectedLanguageChange(event) {
  16369. if (this.track.mode === 'showing') {
  16370. var selectedLanguage = this.player_.cache_.selectedLanguage; // Don't replace the kind of track across the same language
  16371. if (selectedLanguage && selectedLanguage.enabled && selectedLanguage.language === this.track.language && selectedLanguage.kind !== this.track.kind) {
  16372. return;
  16373. }
  16374. this.player_.cache_.selectedLanguage = {
  16375. enabled: true,
  16376. language: this.track.language,
  16377. kind: this.track.kind
  16378. };
  16379. }
  16380. };
  16381. _proto.dispose = function dispose() {
  16382. // remove reference to track object on dispose
  16383. this.track = null;
  16384. _MenuItem.prototype.dispose.call(this);
  16385. };
  16386. return TextTrackMenuItem;
  16387. }(MenuItem);
  16388. Component$1.registerComponent('TextTrackMenuItem', TextTrackMenuItem);
  16389. /**
  16390. * A special menu item for turning of a specific type of text track
  16391. *
  16392. * @extends TextTrackMenuItem
  16393. */
  16394. var OffTextTrackMenuItem = /*#__PURE__*/function (_TextTrackMenuItem) {
  16395. inheritsLoose(OffTextTrackMenuItem, _TextTrackMenuItem);
  16396. /**
  16397. * Creates an instance of this class.
  16398. *
  16399. * @param {Player} player
  16400. * The `Player` that this class should be attached to.
  16401. *
  16402. * @param {Object} [options]
  16403. * The key/value store of player options.
  16404. */
  16405. function OffTextTrackMenuItem(player, options) {
  16406. // Create pseudo track info
  16407. // Requires options['kind']
  16408. options.track = {
  16409. player: player,
  16410. // it is no longer necessary to store `kind` or `kinds` on the track itself
  16411. // since they are now stored in the `kinds` property of all instances of
  16412. // TextTrackMenuItem, but this will remain for backwards compatibility
  16413. kind: options.kind,
  16414. kinds: options.kinds,
  16415. "default": false,
  16416. mode: 'disabled'
  16417. };
  16418. if (!options.kinds) {
  16419. options.kinds = [options.kind];
  16420. }
  16421. if (options.label) {
  16422. options.track.label = options.label;
  16423. } else {
  16424. options.track.label = options.kinds.join(' and ') + ' off';
  16425. } // MenuItem is selectable
  16426. options.selectable = true; // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  16427. options.multiSelectable = false;
  16428. return _TextTrackMenuItem.call(this, player, options) || this;
  16429. }
  16430. /**
  16431. * Handle text track change
  16432. *
  16433. * @param {EventTarget~Event} event
  16434. * The event that caused this function to run
  16435. */
  16436. var _proto = OffTextTrackMenuItem.prototype;
  16437. _proto.handleTracksChange = function handleTracksChange(event) {
  16438. var tracks = this.player().textTracks();
  16439. var shouldBeSelected = true;
  16440. for (var i = 0, l = tracks.length; i < l; i++) {
  16441. var track = tracks[i];
  16442. if (this.options_.kinds.indexOf(track.kind) > -1 && track.mode === 'showing') {
  16443. shouldBeSelected = false;
  16444. break;
  16445. }
  16446. } // Prevent redundant selected() calls because they may cause
  16447. // screen readers to read the appended control text unnecessarily
  16448. if (shouldBeSelected !== this.isSelected_) {
  16449. this.selected(shouldBeSelected);
  16450. }
  16451. };
  16452. _proto.handleSelectedLanguageChange = function handleSelectedLanguageChange(event) {
  16453. var tracks = this.player().textTracks();
  16454. var allHidden = true;
  16455. for (var i = 0, l = tracks.length; i < l; i++) {
  16456. var track = tracks[i];
  16457. if (['captions', 'descriptions', 'subtitles'].indexOf(track.kind) > -1 && track.mode === 'showing') {
  16458. allHidden = false;
  16459. break;
  16460. }
  16461. }
  16462. if (allHidden) {
  16463. this.player_.cache_.selectedLanguage = {
  16464. enabled: false
  16465. };
  16466. }
  16467. };
  16468. return OffTextTrackMenuItem;
  16469. }(TextTrackMenuItem);
  16470. Component$1.registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem);
  16471. /**
  16472. * The base class for buttons that toggle specific text track types (e.g. subtitles)
  16473. *
  16474. * @extends MenuButton
  16475. */
  16476. var TextTrackButton = /*#__PURE__*/function (_TrackButton) {
  16477. inheritsLoose(TextTrackButton, _TrackButton);
  16478. /**
  16479. * Creates an instance of this class.
  16480. *
  16481. * @param {Player} player
  16482. * The `Player` that this class should be attached to.
  16483. *
  16484. * @param {Object} [options={}]
  16485. * The key/value store of player options.
  16486. */
  16487. function TextTrackButton(player, options) {
  16488. if (options === void 0) {
  16489. options = {};
  16490. }
  16491. options.tracks = player.textTracks();
  16492. return _TrackButton.call(this, player, options) || this;
  16493. }
  16494. /**
  16495. * Create a menu item for each text track
  16496. *
  16497. * @param {TextTrackMenuItem[]} [items=[]]
  16498. * Existing array of items to use during creation
  16499. *
  16500. * @return {TextTrackMenuItem[]}
  16501. * Array of menu items that were created
  16502. */
  16503. var _proto = TextTrackButton.prototype;
  16504. _proto.createItems = function createItems(items, TrackMenuItem) {
  16505. if (items === void 0) {
  16506. items = [];
  16507. }
  16508. if (TrackMenuItem === void 0) {
  16509. TrackMenuItem = TextTrackMenuItem;
  16510. }
  16511. // Label is an override for the [track] off label
  16512. // USed to localise captions/subtitles
  16513. var label;
  16514. if (this.label_) {
  16515. label = this.label_ + " off";
  16516. } // Add an OFF menu item to turn all tracks off
  16517. items.push(new OffTextTrackMenuItem(this.player_, {
  16518. kinds: this.kinds_,
  16519. kind: this.kind_,
  16520. label: label
  16521. }));
  16522. this.hideThreshold_ += 1;
  16523. var tracks = this.player_.textTracks();
  16524. if (!Array.isArray(this.kinds_)) {
  16525. this.kinds_ = [this.kind_];
  16526. }
  16527. for (var i = 0; i < tracks.length; i++) {
  16528. var track = tracks[i]; // only add tracks that are of an appropriate kind and have a label
  16529. if (this.kinds_.indexOf(track.kind) > -1) {
  16530. var item = new TrackMenuItem(this.player_, {
  16531. track: track,
  16532. kinds: this.kinds_,
  16533. kind: this.kind_,
  16534. // MenuItem is selectable
  16535. selectable: true,
  16536. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  16537. multiSelectable: false
  16538. });
  16539. item.addClass("vjs-" + track.kind + "-menu-item");
  16540. items.push(item);
  16541. }
  16542. }
  16543. return items;
  16544. };
  16545. return TextTrackButton;
  16546. }(TrackButton);
  16547. Component$1.registerComponent('TextTrackButton', TextTrackButton);
  16548. /**
  16549. * The chapter track menu item
  16550. *
  16551. * @extends MenuItem
  16552. */
  16553. var ChaptersTrackMenuItem = /*#__PURE__*/function (_MenuItem) {
  16554. inheritsLoose(ChaptersTrackMenuItem, _MenuItem);
  16555. /**
  16556. * Creates an instance of this class.
  16557. *
  16558. * @param {Player} player
  16559. * The `Player` that this class should be attached to.
  16560. *
  16561. * @param {Object} [options]
  16562. * The key/value store of player options.
  16563. */
  16564. function ChaptersTrackMenuItem(player, options) {
  16565. var _this;
  16566. var track = options.track;
  16567. var cue = options.cue;
  16568. var currentTime = player.currentTime(); // Modify options for parent MenuItem class's init.
  16569. options.selectable = true;
  16570. options.multiSelectable = false;
  16571. options.label = cue.text;
  16572. options.selected = cue.startTime <= currentTime && currentTime < cue.endTime;
  16573. _this = _MenuItem.call(this, player, options) || this;
  16574. _this.track = track;
  16575. _this.cue = cue;
  16576. return _this;
  16577. }
  16578. /**
  16579. * This gets called when an `ChaptersTrackMenuItem` is "clicked". See
  16580. * {@link ClickableComponent} for more detailed information on what a click can be.
  16581. *
  16582. * @param {EventTarget~Event} [event]
  16583. * The `keydown`, `tap`, or `click` event that caused this function to be
  16584. * called.
  16585. *
  16586. * @listens tap
  16587. * @listens click
  16588. */
  16589. var _proto = ChaptersTrackMenuItem.prototype;
  16590. _proto.handleClick = function handleClick(event) {
  16591. _MenuItem.prototype.handleClick.call(this);
  16592. this.player_.currentTime(this.cue.startTime);
  16593. };
  16594. return ChaptersTrackMenuItem;
  16595. }(MenuItem);
  16596. Component$1.registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem);
  16597. /**
  16598. * The button component for toggling and selecting chapters
  16599. * Chapters act much differently than other text tracks
  16600. * Cues are navigation vs. other tracks of alternative languages
  16601. *
  16602. * @extends TextTrackButton
  16603. */
  16604. var ChaptersButton = /*#__PURE__*/function (_TextTrackButton) {
  16605. inheritsLoose(ChaptersButton, _TextTrackButton);
  16606. /**
  16607. * Creates an instance of this class.
  16608. *
  16609. * @param {Player} player
  16610. * The `Player` that this class should be attached to.
  16611. *
  16612. * @param {Object} [options]
  16613. * The key/value store of player options.
  16614. *
  16615. * @param {Component~ReadyCallback} [ready]
  16616. * The function to call when this function is ready.
  16617. */
  16618. function ChaptersButton(player, options, ready) {
  16619. var _this;
  16620. _this = _TextTrackButton.call(this, player, options, ready) || this;
  16621. _this.selectCurrentItem_ = function () {
  16622. _this.items.forEach(function (item) {
  16623. item.selected(_this.track_.activeCues[0] === item.cue);
  16624. });
  16625. };
  16626. return _this;
  16627. }
  16628. /**
  16629. * Builds the default DOM `className`.
  16630. *
  16631. * @return {string}
  16632. * The DOM `className` for this object.
  16633. */
  16634. var _proto = ChaptersButton.prototype;
  16635. _proto.buildCSSClass = function buildCSSClass() {
  16636. return "vjs-chapters-button " + _TextTrackButton.prototype.buildCSSClass.call(this);
  16637. };
  16638. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  16639. return "vjs-chapters-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
  16640. }
  16641. /**
  16642. * Update the menu based on the current state of its items.
  16643. *
  16644. * @param {EventTarget~Event} [event]
  16645. * An event that triggered this function to run.
  16646. *
  16647. * @listens TextTrackList#addtrack
  16648. * @listens TextTrackList#removetrack
  16649. * @listens TextTrackList#change
  16650. */
  16651. ;
  16652. _proto.update = function update(event) {
  16653. if (event && event.track && event.track.kind !== 'chapters') {
  16654. return;
  16655. }
  16656. var track = this.findChaptersTrack();
  16657. if (track !== this.track_) {
  16658. this.setTrack(track);
  16659. _TextTrackButton.prototype.update.call(this);
  16660. } else if (!this.items || track && track.cues && track.cues.length !== this.items.length) {
  16661. // Update the menu initially or if the number of cues has changed since set
  16662. _TextTrackButton.prototype.update.call(this);
  16663. }
  16664. }
  16665. /**
  16666. * Set the currently selected track for the chapters button.
  16667. *
  16668. * @param {TextTrack} track
  16669. * The new track to select. Nothing will change if this is the currently selected
  16670. * track.
  16671. */
  16672. ;
  16673. _proto.setTrack = function setTrack(track) {
  16674. if (this.track_ === track) {
  16675. return;
  16676. }
  16677. if (!this.updateHandler_) {
  16678. this.updateHandler_ = this.update.bind(this);
  16679. } // here this.track_ refers to the old track instance
  16680. if (this.track_) {
  16681. var remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
  16682. if (remoteTextTrackEl) {
  16683. remoteTextTrackEl.removeEventListener('load', this.updateHandler_);
  16684. }
  16685. this.track_.removeEventListener('cuechange', this.selectCurrentItem_);
  16686. this.track_ = null;
  16687. }
  16688. this.track_ = track; // here this.track_ refers to the new track instance
  16689. if (this.track_) {
  16690. this.track_.mode = 'hidden';
  16691. var _remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
  16692. if (_remoteTextTrackEl) {
  16693. _remoteTextTrackEl.addEventListener('load', this.updateHandler_);
  16694. }
  16695. this.track_.addEventListener('cuechange', this.selectCurrentItem_);
  16696. }
  16697. }
  16698. /**
  16699. * Find the track object that is currently in use by this ChaptersButton
  16700. *
  16701. * @return {TextTrack|undefined}
  16702. * The current track or undefined if none was found.
  16703. */
  16704. ;
  16705. _proto.findChaptersTrack = function findChaptersTrack() {
  16706. var tracks = this.player_.textTracks() || [];
  16707. for (var i = tracks.length - 1; i >= 0; i--) {
  16708. // We will always choose the last track as our chaptersTrack
  16709. var track = tracks[i];
  16710. if (track.kind === this.kind_) {
  16711. return track;
  16712. }
  16713. }
  16714. }
  16715. /**
  16716. * Get the caption for the ChaptersButton based on the track label. This will also
  16717. * use the current tracks localized kind as a fallback if a label does not exist.
  16718. *
  16719. * @return {string}
  16720. * The tracks current label or the localized track kind.
  16721. */
  16722. ;
  16723. _proto.getMenuCaption = function getMenuCaption() {
  16724. if (this.track_ && this.track_.label) {
  16725. return this.track_.label;
  16726. }
  16727. return this.localize(toTitleCase$1(this.kind_));
  16728. }
  16729. /**
  16730. * Create menu from chapter track
  16731. *
  16732. * @return {Menu}
  16733. * New menu for the chapter buttons
  16734. */
  16735. ;
  16736. _proto.createMenu = function createMenu() {
  16737. this.options_.title = this.getMenuCaption();
  16738. return _TextTrackButton.prototype.createMenu.call(this);
  16739. }
  16740. /**
  16741. * Create a menu item for each text track
  16742. *
  16743. * @return {TextTrackMenuItem[]}
  16744. * Array of menu items
  16745. */
  16746. ;
  16747. _proto.createItems = function createItems() {
  16748. var items = [];
  16749. if (!this.track_) {
  16750. return items;
  16751. }
  16752. var cues = this.track_.cues;
  16753. if (!cues) {
  16754. return items;
  16755. }
  16756. for (var i = 0, l = cues.length; i < l; i++) {
  16757. var cue = cues[i];
  16758. var mi = new ChaptersTrackMenuItem(this.player_, {
  16759. track: this.track_,
  16760. cue: cue
  16761. });
  16762. items.push(mi);
  16763. }
  16764. return items;
  16765. };
  16766. return ChaptersButton;
  16767. }(TextTrackButton);
  16768. /**
  16769. * `kind` of TextTrack to look for to associate it with this menu.
  16770. *
  16771. * @type {string}
  16772. * @private
  16773. */
  16774. ChaptersButton.prototype.kind_ = 'chapters';
  16775. /**
  16776. * The text that should display over the `ChaptersButton`s controls. Added for localization.
  16777. *
  16778. * @type {string}
  16779. * @private
  16780. */
  16781. ChaptersButton.prototype.controlText_ = 'Chapters';
  16782. Component$1.registerComponent('ChaptersButton', ChaptersButton);
  16783. /**
  16784. * The button component for toggling and selecting descriptions
  16785. *
  16786. * @extends TextTrackButton
  16787. */
  16788. var DescriptionsButton = /*#__PURE__*/function (_TextTrackButton) {
  16789. inheritsLoose(DescriptionsButton, _TextTrackButton);
  16790. /**
  16791. * Creates an instance of this class.
  16792. *
  16793. * @param {Player} player
  16794. * The `Player` that this class should be attached to.
  16795. *
  16796. * @param {Object} [options]
  16797. * The key/value store of player options.
  16798. *
  16799. * @param {Component~ReadyCallback} [ready]
  16800. * The function to call when this component is ready.
  16801. */
  16802. function DescriptionsButton(player, options, ready) {
  16803. var _this;
  16804. _this = _TextTrackButton.call(this, player, options, ready) || this;
  16805. var tracks = player.textTracks();
  16806. var changeHandler = bind(assertThisInitialized(_this), _this.handleTracksChange);
  16807. tracks.addEventListener('change', changeHandler);
  16808. _this.on('dispose', function () {
  16809. tracks.removeEventListener('change', changeHandler);
  16810. });
  16811. return _this;
  16812. }
  16813. /**
  16814. * Handle text track change
  16815. *
  16816. * @param {EventTarget~Event} event
  16817. * The event that caused this function to run
  16818. *
  16819. * @listens TextTrackList#change
  16820. */
  16821. var _proto = DescriptionsButton.prototype;
  16822. _proto.handleTracksChange = function handleTracksChange(event) {
  16823. var tracks = this.player().textTracks();
  16824. var disabled = false; // Check whether a track of a different kind is showing
  16825. for (var i = 0, l = tracks.length; i < l; i++) {
  16826. var track = tracks[i];
  16827. if (track.kind !== this.kind_ && track.mode === 'showing') {
  16828. disabled = true;
  16829. break;
  16830. }
  16831. } // If another track is showing, disable this menu button
  16832. if (disabled) {
  16833. this.disable();
  16834. } else {
  16835. this.enable();
  16836. }
  16837. }
  16838. /**
  16839. * Builds the default DOM `className`.
  16840. *
  16841. * @return {string}
  16842. * The DOM `className` for this object.
  16843. */
  16844. ;
  16845. _proto.buildCSSClass = function buildCSSClass() {
  16846. return "vjs-descriptions-button " + _TextTrackButton.prototype.buildCSSClass.call(this);
  16847. };
  16848. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  16849. return "vjs-descriptions-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
  16850. };
  16851. return DescriptionsButton;
  16852. }(TextTrackButton);
  16853. /**
  16854. * `kind` of TextTrack to look for to associate it with this menu.
  16855. *
  16856. * @type {string}
  16857. * @private
  16858. */
  16859. DescriptionsButton.prototype.kind_ = 'descriptions';
  16860. /**
  16861. * The text that should display over the `DescriptionsButton`s controls. Added for localization.
  16862. *
  16863. * @type {string}
  16864. * @private
  16865. */
  16866. DescriptionsButton.prototype.controlText_ = 'Descriptions';
  16867. Component$1.registerComponent('DescriptionsButton', DescriptionsButton);
  16868. /**
  16869. * The button component for toggling and selecting subtitles
  16870. *
  16871. * @extends TextTrackButton
  16872. */
  16873. var SubtitlesButton = /*#__PURE__*/function (_TextTrackButton) {
  16874. inheritsLoose(SubtitlesButton, _TextTrackButton);
  16875. /**
  16876. * Creates an instance of this class.
  16877. *
  16878. * @param {Player} player
  16879. * The `Player` that this class should be attached to.
  16880. *
  16881. * @param {Object} [options]
  16882. * The key/value store of player options.
  16883. *
  16884. * @param {Component~ReadyCallback} [ready]
  16885. * The function to call when this component is ready.
  16886. */
  16887. function SubtitlesButton(player, options, ready) {
  16888. return _TextTrackButton.call(this, player, options, ready) || this;
  16889. }
  16890. /**
  16891. * Builds the default DOM `className`.
  16892. *
  16893. * @return {string}
  16894. * The DOM `className` for this object.
  16895. */
  16896. var _proto = SubtitlesButton.prototype;
  16897. _proto.buildCSSClass = function buildCSSClass() {
  16898. return "vjs-subtitles-button " + _TextTrackButton.prototype.buildCSSClass.call(this);
  16899. };
  16900. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  16901. return "vjs-subtitles-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
  16902. };
  16903. return SubtitlesButton;
  16904. }(TextTrackButton);
  16905. /**
  16906. * `kind` of TextTrack to look for to associate it with this menu.
  16907. *
  16908. * @type {string}
  16909. * @private
  16910. */
  16911. SubtitlesButton.prototype.kind_ = 'subtitles';
  16912. /**
  16913. * The text that should display over the `SubtitlesButton`s controls. Added for localization.
  16914. *
  16915. * @type {string}
  16916. * @private
  16917. */
  16918. SubtitlesButton.prototype.controlText_ = 'Subtitles';
  16919. Component$1.registerComponent('SubtitlesButton', SubtitlesButton);
  16920. /**
  16921. * The menu item for caption track settings menu
  16922. *
  16923. * @extends TextTrackMenuItem
  16924. */
  16925. var CaptionSettingsMenuItem = /*#__PURE__*/function (_TextTrackMenuItem) {
  16926. inheritsLoose(CaptionSettingsMenuItem, _TextTrackMenuItem);
  16927. /**
  16928. * Creates an instance of this class.
  16929. *
  16930. * @param {Player} player
  16931. * The `Player` that this class should be attached to.
  16932. *
  16933. * @param {Object} [options]
  16934. * The key/value store of player options.
  16935. */
  16936. function CaptionSettingsMenuItem(player, options) {
  16937. var _this;
  16938. options.track = {
  16939. player: player,
  16940. kind: options.kind,
  16941. label: options.kind + ' settings',
  16942. selectable: false,
  16943. "default": false,
  16944. mode: 'disabled'
  16945. }; // CaptionSettingsMenuItem has no concept of 'selected'
  16946. options.selectable = false;
  16947. options.name = 'CaptionSettingsMenuItem';
  16948. _this = _TextTrackMenuItem.call(this, player, options) || this;
  16949. _this.addClass('vjs-texttrack-settings');
  16950. _this.controlText(', opens ' + options.kind + ' settings dialog');
  16951. return _this;
  16952. }
  16953. /**
  16954. * This gets called when an `CaptionSettingsMenuItem` is "clicked". See
  16955. * {@link ClickableComponent} for more detailed information on what a click can be.
  16956. *
  16957. * @param {EventTarget~Event} [event]
  16958. * The `keydown`, `tap`, or `click` event that caused this function to be
  16959. * called.
  16960. *
  16961. * @listens tap
  16962. * @listens click
  16963. */
  16964. var _proto = CaptionSettingsMenuItem.prototype;
  16965. _proto.handleClick = function handleClick(event) {
  16966. this.player().getChild('textTrackSettings').open();
  16967. };
  16968. return CaptionSettingsMenuItem;
  16969. }(TextTrackMenuItem);
  16970. Component$1.registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem);
  16971. /**
  16972. * The button component for toggling and selecting captions
  16973. *
  16974. * @extends TextTrackButton
  16975. */
  16976. var CaptionsButton = /*#__PURE__*/function (_TextTrackButton) {
  16977. inheritsLoose(CaptionsButton, _TextTrackButton);
  16978. /**
  16979. * Creates an instance of this class.
  16980. *
  16981. * @param {Player} player
  16982. * The `Player` that this class should be attached to.
  16983. *
  16984. * @param {Object} [options]
  16985. * The key/value store of player options.
  16986. *
  16987. * @param {Component~ReadyCallback} [ready]
  16988. * The function to call when this component is ready.
  16989. */
  16990. function CaptionsButton(player, options, ready) {
  16991. return _TextTrackButton.call(this, player, options, ready) || this;
  16992. }
  16993. /**
  16994. * Builds the default DOM `className`.
  16995. *
  16996. * @return {string}
  16997. * The DOM `className` for this object.
  16998. */
  16999. var _proto = CaptionsButton.prototype;
  17000. _proto.buildCSSClass = function buildCSSClass() {
  17001. return "vjs-captions-button " + _TextTrackButton.prototype.buildCSSClass.call(this);
  17002. };
  17003. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  17004. return "vjs-captions-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
  17005. }
  17006. /**
  17007. * Create caption menu items
  17008. *
  17009. * @return {CaptionSettingsMenuItem[]}
  17010. * The array of current menu items.
  17011. */
  17012. ;
  17013. _proto.createItems = function createItems() {
  17014. var items = [];
  17015. if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
  17016. items.push(new CaptionSettingsMenuItem(this.player_, {
  17017. kind: this.kind_
  17018. }));
  17019. this.hideThreshold_ += 1;
  17020. }
  17021. return _TextTrackButton.prototype.createItems.call(this, items);
  17022. };
  17023. return CaptionsButton;
  17024. }(TextTrackButton);
  17025. /**
  17026. * `kind` of TextTrack to look for to associate it with this menu.
  17027. *
  17028. * @type {string}
  17029. * @private
  17030. */
  17031. CaptionsButton.prototype.kind_ = 'captions';
  17032. /**
  17033. * The text that should display over the `CaptionsButton`s controls. Added for localization.
  17034. *
  17035. * @type {string}
  17036. * @private
  17037. */
  17038. CaptionsButton.prototype.controlText_ = 'Captions';
  17039. Component$1.registerComponent('CaptionsButton', CaptionsButton);
  17040. /**
  17041. * SubsCapsMenuItem has an [cc] icon to distinguish captions from subtitles
  17042. * in the SubsCapsMenu.
  17043. *
  17044. * @extends TextTrackMenuItem
  17045. */
  17046. var SubsCapsMenuItem = /*#__PURE__*/function (_TextTrackMenuItem) {
  17047. inheritsLoose(SubsCapsMenuItem, _TextTrackMenuItem);
  17048. function SubsCapsMenuItem() {
  17049. return _TextTrackMenuItem.apply(this, arguments) || this;
  17050. }
  17051. var _proto = SubsCapsMenuItem.prototype;
  17052. _proto.createEl = function createEl$1(type, props, attrs) {
  17053. var el = _TextTrackMenuItem.prototype.createEl.call(this, type, props, attrs);
  17054. var parentSpan = el.querySelector('.vjs-menu-item-text');
  17055. if (this.options_.track.kind === 'captions') {
  17056. parentSpan.appendChild(createEl('span', {
  17057. className: 'vjs-icon-placeholder'
  17058. }, {
  17059. 'aria-hidden': true
  17060. }));
  17061. parentSpan.appendChild(createEl('span', {
  17062. className: 'vjs-control-text',
  17063. // space added as the text will visually flow with the
  17064. // label
  17065. textContent: " " + this.localize('Captions')
  17066. }));
  17067. }
  17068. return el;
  17069. };
  17070. return SubsCapsMenuItem;
  17071. }(TextTrackMenuItem);
  17072. Component$1.registerComponent('SubsCapsMenuItem', SubsCapsMenuItem);
  17073. /**
  17074. * The button component for toggling and selecting captions and/or subtitles
  17075. *
  17076. * @extends TextTrackButton
  17077. */
  17078. var SubsCapsButton = /*#__PURE__*/function (_TextTrackButton) {
  17079. inheritsLoose(SubsCapsButton, _TextTrackButton);
  17080. function SubsCapsButton(player, options) {
  17081. var _this;
  17082. if (options === void 0) {
  17083. options = {};
  17084. }
  17085. _this = _TextTrackButton.call(this, player, options) || this; // Although North America uses "captions" in most cases for
  17086. // "captions and subtitles" other locales use "subtitles"
  17087. _this.label_ = 'subtitles';
  17088. if (['en', 'en-us', 'en-ca', 'fr-ca'].indexOf(_this.player_.language_) > -1) {
  17089. _this.label_ = 'captions';
  17090. }
  17091. _this.menuButton_.controlText(toTitleCase$1(_this.label_));
  17092. return _this;
  17093. }
  17094. /**
  17095. * Builds the default DOM `className`.
  17096. *
  17097. * @return {string}
  17098. * The DOM `className` for this object.
  17099. */
  17100. var _proto = SubsCapsButton.prototype;
  17101. _proto.buildCSSClass = function buildCSSClass() {
  17102. return "vjs-subs-caps-button " + _TextTrackButton.prototype.buildCSSClass.call(this);
  17103. };
  17104. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  17105. return "vjs-subs-caps-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
  17106. }
  17107. /**
  17108. * Create caption/subtitles menu items
  17109. *
  17110. * @return {CaptionSettingsMenuItem[]}
  17111. * The array of current menu items.
  17112. */
  17113. ;
  17114. _proto.createItems = function createItems() {
  17115. var items = [];
  17116. if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
  17117. items.push(new CaptionSettingsMenuItem(this.player_, {
  17118. kind: this.label_
  17119. }));
  17120. this.hideThreshold_ += 1;
  17121. }
  17122. items = _TextTrackButton.prototype.createItems.call(this, items, SubsCapsMenuItem);
  17123. return items;
  17124. };
  17125. return SubsCapsButton;
  17126. }(TextTrackButton);
  17127. /**
  17128. * `kind`s of TextTrack to look for to associate it with this menu.
  17129. *
  17130. * @type {array}
  17131. * @private
  17132. */
  17133. SubsCapsButton.prototype.kinds_ = ['captions', 'subtitles'];
  17134. /**
  17135. * The text that should display over the `SubsCapsButton`s controls.
  17136. *
  17137. *
  17138. * @type {string}
  17139. * @private
  17140. */
  17141. SubsCapsButton.prototype.controlText_ = 'Subtitles';
  17142. Component$1.registerComponent('SubsCapsButton', SubsCapsButton);
  17143. /**
  17144. * An {@link AudioTrack} {@link MenuItem}
  17145. *
  17146. * @extends MenuItem
  17147. */
  17148. var AudioTrackMenuItem = /*#__PURE__*/function (_MenuItem) {
  17149. inheritsLoose(AudioTrackMenuItem, _MenuItem);
  17150. /**
  17151. * Creates an instance of this class.
  17152. *
  17153. * @param {Player} player
  17154. * The `Player` that this class should be attached to.
  17155. *
  17156. * @param {Object} [options]
  17157. * The key/value store of player options.
  17158. */
  17159. function AudioTrackMenuItem(player, options) {
  17160. var _this;
  17161. var track = options.track;
  17162. var tracks = player.audioTracks(); // Modify options for parent MenuItem class's init.
  17163. options.label = track.label || track.language || 'Unknown';
  17164. options.selected = track.enabled;
  17165. _this = _MenuItem.call(this, player, options) || this;
  17166. _this.track = track;
  17167. _this.addClass("vjs-" + track.kind + "-menu-item");
  17168. var changeHandler = function changeHandler() {
  17169. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  17170. args[_key] = arguments[_key];
  17171. }
  17172. _this.handleTracksChange.apply(assertThisInitialized(_this), args);
  17173. };
  17174. tracks.addEventListener('change', changeHandler);
  17175. _this.on('dispose', function () {
  17176. tracks.removeEventListener('change', changeHandler);
  17177. });
  17178. return _this;
  17179. }
  17180. var _proto = AudioTrackMenuItem.prototype;
  17181. _proto.createEl = function createEl$1(type, props, attrs) {
  17182. var el = _MenuItem.prototype.createEl.call(this, type, props, attrs);
  17183. var parentSpan = el.querySelector('.vjs-menu-item-text');
  17184. if (this.options_.track.kind === 'main-desc') {
  17185. parentSpan.appendChild(createEl('span', {
  17186. className: 'vjs-icon-placeholder'
  17187. }, {
  17188. 'aria-hidden': true
  17189. }));
  17190. parentSpan.appendChild(createEl('span', {
  17191. className: 'vjs-control-text',
  17192. textContent: ' ' + this.localize('Descriptions')
  17193. }));
  17194. }
  17195. return el;
  17196. }
  17197. /**
  17198. * This gets called when an `AudioTrackMenuItem is "clicked". See {@link ClickableComponent}
  17199. * for more detailed information on what a click can be.
  17200. *
  17201. * @param {EventTarget~Event} [event]
  17202. * The `keydown`, `tap`, or `click` event that caused this function to be
  17203. * called.
  17204. *
  17205. * @listens tap
  17206. * @listens click
  17207. */
  17208. ;
  17209. _proto.handleClick = function handleClick(event) {
  17210. _MenuItem.prototype.handleClick.call(this, event); // the audio track list will automatically toggle other tracks
  17211. // off for us.
  17212. this.track.enabled = true; // when native audio tracks are used, we want to make sure that other tracks are turned off
  17213. if (this.player_.tech_.featuresNativeAudioTracks) {
  17214. var tracks = this.player_.audioTracks();
  17215. for (var i = 0; i < tracks.length; i++) {
  17216. var track = tracks[i]; // skip the current track since we enabled it above
  17217. if (track === this.track) {
  17218. continue;
  17219. }
  17220. track.enabled = track === this.track;
  17221. }
  17222. }
  17223. }
  17224. /**
  17225. * Handle any {@link AudioTrack} change.
  17226. *
  17227. * @param {EventTarget~Event} [event]
  17228. * The {@link AudioTrackList#change} event that caused this to run.
  17229. *
  17230. * @listens AudioTrackList#change
  17231. */
  17232. ;
  17233. _proto.handleTracksChange = function handleTracksChange(event) {
  17234. this.selected(this.track.enabled);
  17235. };
  17236. return AudioTrackMenuItem;
  17237. }(MenuItem);
  17238. Component$1.registerComponent('AudioTrackMenuItem', AudioTrackMenuItem);
  17239. /**
  17240. * The base class for buttons that toggle specific {@link AudioTrack} types.
  17241. *
  17242. * @extends TrackButton
  17243. */
  17244. var AudioTrackButton = /*#__PURE__*/function (_TrackButton) {
  17245. inheritsLoose(AudioTrackButton, _TrackButton);
  17246. /**
  17247. * Creates an instance of this class.
  17248. *
  17249. * @param {Player} player
  17250. * The `Player` that this class should be attached to.
  17251. *
  17252. * @param {Object} [options={}]
  17253. * The key/value store of player options.
  17254. */
  17255. function AudioTrackButton(player, options) {
  17256. if (options === void 0) {
  17257. options = {};
  17258. }
  17259. options.tracks = player.audioTracks();
  17260. return _TrackButton.call(this, player, options) || this;
  17261. }
  17262. /**
  17263. * Builds the default DOM `className`.
  17264. *
  17265. * @return {string}
  17266. * The DOM `className` for this object.
  17267. */
  17268. var _proto = AudioTrackButton.prototype;
  17269. _proto.buildCSSClass = function buildCSSClass() {
  17270. return "vjs-audio-button " + _TrackButton.prototype.buildCSSClass.call(this);
  17271. };
  17272. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  17273. return "vjs-audio-button " + _TrackButton.prototype.buildWrapperCSSClass.call(this);
  17274. }
  17275. /**
  17276. * Create a menu item for each audio track
  17277. *
  17278. * @param {AudioTrackMenuItem[]} [items=[]]
  17279. * An array of existing menu items to use.
  17280. *
  17281. * @return {AudioTrackMenuItem[]}
  17282. * An array of menu items
  17283. */
  17284. ;
  17285. _proto.createItems = function createItems(items) {
  17286. if (items === void 0) {
  17287. items = [];
  17288. }
  17289. // if there's only one audio track, there no point in showing it
  17290. this.hideThreshold_ = 1;
  17291. var tracks = this.player_.audioTracks();
  17292. for (var i = 0; i < tracks.length; i++) {
  17293. var track = tracks[i];
  17294. items.push(new AudioTrackMenuItem(this.player_, {
  17295. track: track,
  17296. // MenuItem is selectable
  17297. selectable: true,
  17298. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  17299. multiSelectable: false
  17300. }));
  17301. }
  17302. return items;
  17303. };
  17304. return AudioTrackButton;
  17305. }(TrackButton);
  17306. /**
  17307. * The text that should display over the `AudioTrackButton`s controls. Added for localization.
  17308. *
  17309. * @type {string}
  17310. * @private
  17311. */
  17312. AudioTrackButton.prototype.controlText_ = 'Audio Track';
  17313. Component$1.registerComponent('AudioTrackButton', AudioTrackButton);
  17314. /**
  17315. * The specific menu item type for selecting a playback rate.
  17316. *
  17317. * @extends MenuItem
  17318. */
  17319. var PlaybackRateMenuItem = /*#__PURE__*/function (_MenuItem) {
  17320. inheritsLoose(PlaybackRateMenuItem, _MenuItem);
  17321. /**
  17322. * Creates an instance of this class.
  17323. *
  17324. * @param {Player} player
  17325. * The `Player` that this class should be attached to.
  17326. *
  17327. * @param {Object} [options]
  17328. * The key/value store of player options.
  17329. */
  17330. function PlaybackRateMenuItem(player, options) {
  17331. var _this;
  17332. var label = options.rate;
  17333. var rate = parseFloat(label, 10); // Modify options for parent MenuItem class's init.
  17334. options.label = label;
  17335. options.selected = rate === player.playbackRate();
  17336. options.selectable = true;
  17337. options.multiSelectable = false;
  17338. _this = _MenuItem.call(this, player, options) || this;
  17339. _this.label = label;
  17340. _this.rate = rate;
  17341. _this.on(player, 'ratechange', function (e) {
  17342. return _this.update(e);
  17343. });
  17344. return _this;
  17345. }
  17346. /**
  17347. * This gets called when an `PlaybackRateMenuItem` is "clicked". See
  17348. * {@link ClickableComponent} for more detailed information on what a click can be.
  17349. *
  17350. * @param {EventTarget~Event} [event]
  17351. * The `keydown`, `tap`, or `click` event that caused this function to be
  17352. * called.
  17353. *
  17354. * @listens tap
  17355. * @listens click
  17356. */
  17357. var _proto = PlaybackRateMenuItem.prototype;
  17358. _proto.handleClick = function handleClick(event) {
  17359. _MenuItem.prototype.handleClick.call(this);
  17360. this.player().playbackRate(this.rate);
  17361. }
  17362. /**
  17363. * Update the PlaybackRateMenuItem when the playbackrate changes.
  17364. *
  17365. * @param {EventTarget~Event} [event]
  17366. * The `ratechange` event that caused this function to run.
  17367. *
  17368. * @listens Player#ratechange
  17369. */
  17370. ;
  17371. _proto.update = function update(event) {
  17372. this.selected(this.player().playbackRate() === this.rate);
  17373. };
  17374. return PlaybackRateMenuItem;
  17375. }(MenuItem);
  17376. /**
  17377. * The text that should display over the `PlaybackRateMenuItem`s controls. Added for localization.
  17378. *
  17379. * @type {string}
  17380. * @private
  17381. */
  17382. PlaybackRateMenuItem.prototype.contentElType = 'button';
  17383. Component$1.registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem);
  17384. /**
  17385. * The component for controlling the playback rate.
  17386. *
  17387. * @extends MenuButton
  17388. */
  17389. var PlaybackRateMenuButton = /*#__PURE__*/function (_MenuButton) {
  17390. inheritsLoose(PlaybackRateMenuButton, _MenuButton);
  17391. /**
  17392. * Creates an instance of this class.
  17393. *
  17394. * @param {Player} player
  17395. * The `Player` that this class should be attached to.
  17396. *
  17397. * @param {Object} [options]
  17398. * The key/value store of player options.
  17399. */
  17400. function PlaybackRateMenuButton(player, options) {
  17401. var _this;
  17402. _this = _MenuButton.call(this, player, options) || this;
  17403. _this.menuButton_.el_.setAttribute('aria-describedby', _this.labelElId_);
  17404. _this.updateVisibility();
  17405. _this.updateLabel();
  17406. _this.on(player, 'loadstart', function (e) {
  17407. return _this.updateVisibility(e);
  17408. });
  17409. _this.on(player, 'ratechange', function (e) {
  17410. return _this.updateLabel(e);
  17411. });
  17412. _this.on(player, 'playbackrateschange', function (e) {
  17413. return _this.handlePlaybackRateschange(e);
  17414. });
  17415. return _this;
  17416. }
  17417. /**
  17418. * Create the `Component`'s DOM element
  17419. *
  17420. * @return {Element}
  17421. * The element that was created.
  17422. */
  17423. var _proto = PlaybackRateMenuButton.prototype;
  17424. _proto.createEl = function createEl$1() {
  17425. var el = _MenuButton.prototype.createEl.call(this);
  17426. this.labelElId_ = 'vjs-playback-rate-value-label-' + this.id_;
  17427. this.labelEl_ = createEl('div', {
  17428. className: 'vjs-playback-rate-value',
  17429. id: this.labelElId_,
  17430. textContent: '1x'
  17431. });
  17432. el.appendChild(this.labelEl_);
  17433. return el;
  17434. };
  17435. _proto.dispose = function dispose() {
  17436. this.labelEl_ = null;
  17437. _MenuButton.prototype.dispose.call(this);
  17438. }
  17439. /**
  17440. * Builds the default DOM `className`.
  17441. *
  17442. * @return {string}
  17443. * The DOM `className` for this object.
  17444. */
  17445. ;
  17446. _proto.buildCSSClass = function buildCSSClass() {
  17447. return "vjs-playback-rate " + _MenuButton.prototype.buildCSSClass.call(this);
  17448. };
  17449. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  17450. return "vjs-playback-rate " + _MenuButton.prototype.buildWrapperCSSClass.call(this);
  17451. }
  17452. /**
  17453. * Create the list of menu items. Specific to each subclass.
  17454. *
  17455. */
  17456. ;
  17457. _proto.createItems = function createItems() {
  17458. var rates = this.playbackRates();
  17459. var items = [];
  17460. for (var i = rates.length - 1; i >= 0; i--) {
  17461. items.push(new PlaybackRateMenuItem(this.player(), {
  17462. rate: rates[i] + 'x'
  17463. }));
  17464. }
  17465. return items;
  17466. }
  17467. /**
  17468. * Updates ARIA accessibility attributes
  17469. */
  17470. ;
  17471. _proto.updateARIAAttributes = function updateARIAAttributes() {
  17472. // Current playback rate
  17473. this.el().setAttribute('aria-valuenow', this.player().playbackRate());
  17474. }
  17475. /**
  17476. * This gets called when an `PlaybackRateMenuButton` is "clicked". See
  17477. * {@link ClickableComponent} for more detailed information on what a click can be.
  17478. *
  17479. * @param {EventTarget~Event} [event]
  17480. * The `keydown`, `tap`, or `click` event that caused this function to be
  17481. * called.
  17482. *
  17483. * @listens tap
  17484. * @listens click
  17485. */
  17486. ;
  17487. _proto.handleClick = function handleClick(event) {
  17488. // select next rate option
  17489. var currentRate = this.player().playbackRate();
  17490. var rates = this.playbackRates();
  17491. var currentIndex = rates.indexOf(currentRate); // this get the next rate and it will select first one if the last one currently selected
  17492. var newIndex = (currentIndex + 1) % rates.length;
  17493. this.player().playbackRate(rates[newIndex]);
  17494. }
  17495. /**
  17496. * On playbackrateschange, update the menu to account for the new items.
  17497. *
  17498. * @listens Player#playbackrateschange
  17499. */
  17500. ;
  17501. _proto.handlePlaybackRateschange = function handlePlaybackRateschange(event) {
  17502. this.update();
  17503. }
  17504. /**
  17505. * Get possible playback rates
  17506. *
  17507. * @return {Array}
  17508. * All possible playback rates
  17509. */
  17510. ;
  17511. _proto.playbackRates = function playbackRates() {
  17512. var player = this.player();
  17513. return player.playbackRates && player.playbackRates() || [];
  17514. }
  17515. /**
  17516. * Get whether playback rates is supported by the tech
  17517. * and an array of playback rates exists
  17518. *
  17519. * @return {boolean}
  17520. * Whether changing playback rate is supported
  17521. */
  17522. ;
  17523. _proto.playbackRateSupported = function playbackRateSupported() {
  17524. return this.player().tech_ && this.player().tech_.featuresPlaybackRate && this.playbackRates() && this.playbackRates().length > 0;
  17525. }
  17526. /**
  17527. * Hide playback rate controls when they're no playback rate options to select
  17528. *
  17529. * @param {EventTarget~Event} [event]
  17530. * The event that caused this function to run.
  17531. *
  17532. * @listens Player#loadstart
  17533. */
  17534. ;
  17535. _proto.updateVisibility = function updateVisibility(event) {
  17536. if (this.playbackRateSupported()) {
  17537. this.removeClass('vjs-hidden');
  17538. } else {
  17539. this.addClass('vjs-hidden');
  17540. }
  17541. }
  17542. /**
  17543. * Update button label when rate changed
  17544. *
  17545. * @param {EventTarget~Event} [event]
  17546. * The event that caused this function to run.
  17547. *
  17548. * @listens Player#ratechange
  17549. */
  17550. ;
  17551. _proto.updateLabel = function updateLabel(event) {
  17552. if (this.playbackRateSupported()) {
  17553. this.labelEl_.textContent = this.player().playbackRate() + 'x';
  17554. }
  17555. };
  17556. return PlaybackRateMenuButton;
  17557. }(MenuButton);
  17558. /**
  17559. * The text that should display over the `FullscreenToggle`s controls. Added for localization.
  17560. *
  17561. * @type {string}
  17562. * @private
  17563. */
  17564. PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate';
  17565. Component$1.registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton);
  17566. /**
  17567. * Just an empty spacer element that can be used as an append point for plugins, etc.
  17568. * Also can be used to create space between elements when necessary.
  17569. *
  17570. * @extends Component
  17571. */
  17572. var Spacer = /*#__PURE__*/function (_Component) {
  17573. inheritsLoose(Spacer, _Component);
  17574. function Spacer() {
  17575. return _Component.apply(this, arguments) || this;
  17576. }
  17577. var _proto = Spacer.prototype;
  17578. /**
  17579. * Builds the default DOM `className`.
  17580. *
  17581. * @return {string}
  17582. * The DOM `className` for this object.
  17583. */
  17584. _proto.buildCSSClass = function buildCSSClass() {
  17585. return "vjs-spacer " + _Component.prototype.buildCSSClass.call(this);
  17586. }
  17587. /**
  17588. * Create the `Component`'s DOM element
  17589. *
  17590. * @return {Element}
  17591. * The element that was created.
  17592. */
  17593. ;
  17594. _proto.createEl = function createEl(tag, props, attributes) {
  17595. if (tag === void 0) {
  17596. tag = 'div';
  17597. }
  17598. if (props === void 0) {
  17599. props = {};
  17600. }
  17601. if (attributes === void 0) {
  17602. attributes = {};
  17603. }
  17604. if (!props.className) {
  17605. props.className = this.buildCSSClass();
  17606. }
  17607. return _Component.prototype.createEl.call(this, tag, props, attributes);
  17608. };
  17609. return Spacer;
  17610. }(Component$1);
  17611. Component$1.registerComponent('Spacer', Spacer);
  17612. /**
  17613. * Spacer specifically meant to be used as an insertion point for new plugins, etc.
  17614. *
  17615. * @extends Spacer
  17616. */
  17617. var CustomControlSpacer = /*#__PURE__*/function (_Spacer) {
  17618. inheritsLoose(CustomControlSpacer, _Spacer);
  17619. function CustomControlSpacer() {
  17620. return _Spacer.apply(this, arguments) || this;
  17621. }
  17622. var _proto = CustomControlSpacer.prototype;
  17623. /**
  17624. * Builds the default DOM `className`.
  17625. *
  17626. * @return {string}
  17627. * The DOM `className` for this object.
  17628. */
  17629. _proto.buildCSSClass = function buildCSSClass() {
  17630. return "vjs-custom-control-spacer " + _Spacer.prototype.buildCSSClass.call(this);
  17631. }
  17632. /**
  17633. * Create the `Component`'s DOM element
  17634. *
  17635. * @return {Element}
  17636. * The element that was created.
  17637. */
  17638. ;
  17639. _proto.createEl = function createEl() {
  17640. return _Spacer.prototype.createEl.call(this, 'div', {
  17641. className: this.buildCSSClass(),
  17642. // No-flex/table-cell mode requires there be some content
  17643. // in the cell to fill the remaining space of the table.
  17644. textContent: "\xA0"
  17645. });
  17646. };
  17647. return CustomControlSpacer;
  17648. }(Spacer);
  17649. Component$1.registerComponent('CustomControlSpacer', CustomControlSpacer);
  17650. /**
  17651. * Container of main controls.
  17652. *
  17653. * @extends Component
  17654. */
  17655. var ControlBar = /*#__PURE__*/function (_Component) {
  17656. inheritsLoose(ControlBar, _Component);
  17657. function ControlBar() {
  17658. return _Component.apply(this, arguments) || this;
  17659. }
  17660. var _proto = ControlBar.prototype;
  17661. /**
  17662. * Create the `Component`'s DOM element
  17663. *
  17664. * @return {Element}
  17665. * The element that was created.
  17666. */
  17667. _proto.createEl = function createEl() {
  17668. return _Component.prototype.createEl.call(this, 'div', {
  17669. className: 'vjs-control-bar',
  17670. dir: 'ltr'
  17671. });
  17672. };
  17673. return ControlBar;
  17674. }(Component$1);
  17675. /**
  17676. * Default options for `ControlBar`
  17677. *
  17678. * @type {Object}
  17679. * @private
  17680. */
  17681. ControlBar.prototype.options_ = {
  17682. children: ['playToggle', 'volumePanel', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'seekToLive', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'chaptersButton', 'descriptionsButton', 'subsCapsButton', 'audioTrackButton', 'fullscreenToggle']
  17683. };
  17684. if ('exitPictureInPicture' in document) {
  17685. ControlBar.prototype.options_.children.splice(ControlBar.prototype.options_.children.length - 1, 0, 'pictureInPictureToggle');
  17686. }
  17687. Component$1.registerComponent('ControlBar', ControlBar);
  17688. /**
  17689. * A display that indicates an error has occurred. This means that the video
  17690. * is unplayable.
  17691. *
  17692. * @extends ModalDialog
  17693. */
  17694. var ErrorDisplay = /*#__PURE__*/function (_ModalDialog) {
  17695. inheritsLoose(ErrorDisplay, _ModalDialog);
  17696. /**
  17697. * Creates an instance of this class.
  17698. *
  17699. * @param {Player} player
  17700. * The `Player` that this class should be attached to.
  17701. *
  17702. * @param {Object} [options]
  17703. * The key/value store of player options.
  17704. */
  17705. function ErrorDisplay(player, options) {
  17706. var _this;
  17707. _this = _ModalDialog.call(this, player, options) || this;
  17708. _this.on(player, 'error', function (e) {
  17709. return _this.open(e);
  17710. });
  17711. return _this;
  17712. }
  17713. /**
  17714. * Builds the default DOM `className`.
  17715. *
  17716. * @return {string}
  17717. * The DOM `className` for this object.
  17718. *
  17719. * @deprecated Since version 5.
  17720. */
  17721. var _proto = ErrorDisplay.prototype;
  17722. _proto.buildCSSClass = function buildCSSClass() {
  17723. return "vjs-error-display " + _ModalDialog.prototype.buildCSSClass.call(this);
  17724. }
  17725. /**
  17726. * Gets the localized error message based on the `Player`s error.
  17727. *
  17728. * @return {string}
  17729. * The `Player`s error message localized or an empty string.
  17730. */
  17731. ;
  17732. _proto.content = function content() {
  17733. var error = this.player().error();
  17734. return error ? this.localize(error.message) : '';
  17735. };
  17736. return ErrorDisplay;
  17737. }(ModalDialog);
  17738. /**
  17739. * The default options for an `ErrorDisplay`.
  17740. *
  17741. * @private
  17742. */
  17743. ErrorDisplay.prototype.options_ = _extends_1({}, ModalDialog.prototype.options_, {
  17744. pauseOnOpen: false,
  17745. fillAlways: true,
  17746. temporary: false,
  17747. uncloseable: true
  17748. });
  17749. Component$1.registerComponent('ErrorDisplay', ErrorDisplay);
  17750. var LOCAL_STORAGE_KEY$1 = 'vjs-text-track-settings';
  17751. var COLOR_BLACK = ['#000', 'Black'];
  17752. var COLOR_BLUE = ['#00F', 'Blue'];
  17753. var COLOR_CYAN = ['#0FF', 'Cyan'];
  17754. var COLOR_GREEN = ['#0F0', 'Green'];
  17755. var COLOR_MAGENTA = ['#F0F', 'Magenta'];
  17756. var COLOR_RED = ['#F00', 'Red'];
  17757. var COLOR_WHITE = ['#FFF', 'White'];
  17758. var COLOR_YELLOW = ['#FF0', 'Yellow'];
  17759. var OPACITY_OPAQUE = ['1', 'Opaque'];
  17760. var OPACITY_SEMI = ['0.5', 'Semi-Transparent'];
  17761. var OPACITY_TRANS = ['0', 'Transparent']; // Configuration for the various <select> elements in the DOM of this component.
  17762. //
  17763. // Possible keys include:
  17764. //
  17765. // `default`:
  17766. // The default option index. Only needs to be provided if not zero.
  17767. // `parser`:
  17768. // A function which is used to parse the value from the selected option in
  17769. // a customized way.
  17770. // `selector`:
  17771. // The selector used to find the associated <select> element.
  17772. var selectConfigs = {
  17773. backgroundColor: {
  17774. selector: '.vjs-bg-color > select',
  17775. id: 'captions-background-color-%s',
  17776. label: 'Color',
  17777. options: [COLOR_BLACK, COLOR_WHITE, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN]
  17778. },
  17779. backgroundOpacity: {
  17780. selector: '.vjs-bg-opacity > select',
  17781. id: 'captions-background-opacity-%s',
  17782. label: 'Transparency',
  17783. options: [OPACITY_OPAQUE, OPACITY_SEMI, OPACITY_TRANS]
  17784. },
  17785. color: {
  17786. selector: '.vjs-fg-color > select',
  17787. id: 'captions-foreground-color-%s',
  17788. label: 'Color',
  17789. options: [COLOR_WHITE, COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN]
  17790. },
  17791. edgeStyle: {
  17792. selector: '.vjs-edge-style > select',
  17793. id: '%s',
  17794. label: 'Text Edge Style',
  17795. options: [['none', 'None'], ['raised', 'Raised'], ['depressed', 'Depressed'], ['uniform', 'Uniform'], ['dropshadow', 'Dropshadow']]
  17796. },
  17797. fontFamily: {
  17798. selector: '.vjs-font-family > select',
  17799. id: 'captions-font-family-%s',
  17800. label: 'Font Family',
  17801. options: [['proportionalSansSerif', 'Proportional Sans-Serif'], ['monospaceSansSerif', 'Monospace Sans-Serif'], ['proportionalSerif', 'Proportional Serif'], ['monospaceSerif', 'Monospace Serif'], ['casual', 'Casual'], ['script', 'Script'], ['small-caps', 'Small Caps']]
  17802. },
  17803. fontPercent: {
  17804. selector: '.vjs-font-percent > select',
  17805. id: 'captions-font-size-%s',
  17806. label: 'Font Size',
  17807. options: [['0.50', '50%'], ['0.75', '75%'], ['1.00', '100%'], ['1.25', '125%'], ['1.50', '150%'], ['1.75', '175%'], ['2.00', '200%'], ['3.00', '300%'], ['4.00', '400%']],
  17808. "default": 2,
  17809. parser: function parser(v) {
  17810. return v === '1.00' ? null : Number(v);
  17811. }
  17812. },
  17813. textOpacity: {
  17814. selector: '.vjs-text-opacity > select',
  17815. id: 'captions-foreground-opacity-%s',
  17816. label: 'Transparency',
  17817. options: [OPACITY_OPAQUE, OPACITY_SEMI]
  17818. },
  17819. // Options for this object are defined below.
  17820. windowColor: {
  17821. selector: '.vjs-window-color > select',
  17822. id: 'captions-window-color-%s',
  17823. label: 'Color'
  17824. },
  17825. // Options for this object are defined below.
  17826. windowOpacity: {
  17827. selector: '.vjs-window-opacity > select',
  17828. id: 'captions-window-opacity-%s',
  17829. label: 'Transparency',
  17830. options: [OPACITY_TRANS, OPACITY_SEMI, OPACITY_OPAQUE]
  17831. }
  17832. };
  17833. selectConfigs.windowColor.options = selectConfigs.backgroundColor.options;
  17834. /**
  17835. * Get the actual value of an option.
  17836. *
  17837. * @param {string} value
  17838. * The value to get
  17839. *
  17840. * @param {Function} [parser]
  17841. * Optional function to adjust the value.
  17842. *
  17843. * @return {Mixed}
  17844. * - Will be `undefined` if no value exists
  17845. * - Will be `undefined` if the given value is "none".
  17846. * - Will be the actual value otherwise.
  17847. *
  17848. * @private
  17849. */
  17850. function parseOptionValue(value, parser) {
  17851. if (parser) {
  17852. value = parser(value);
  17853. }
  17854. if (value && value !== 'none') {
  17855. return value;
  17856. }
  17857. }
  17858. /**
  17859. * Gets the value of the selected <option> element within a <select> element.
  17860. *
  17861. * @param {Element} el
  17862. * the element to look in
  17863. *
  17864. * @param {Function} [parser]
  17865. * Optional function to adjust the value.
  17866. *
  17867. * @return {Mixed}
  17868. * - Will be `undefined` if no value exists
  17869. * - Will be `undefined` if the given value is "none".
  17870. * - Will be the actual value otherwise.
  17871. *
  17872. * @private
  17873. */
  17874. function getSelectedOptionValue(el, parser) {
  17875. var value = el.options[el.options.selectedIndex].value;
  17876. return parseOptionValue(value, parser);
  17877. }
  17878. /**
  17879. * Sets the selected <option> element within a <select> element based on a
  17880. * given value.
  17881. *
  17882. * @param {Element} el
  17883. * The element to look in.
  17884. *
  17885. * @param {string} value
  17886. * the property to look on.
  17887. *
  17888. * @param {Function} [parser]
  17889. * Optional function to adjust the value before comparing.
  17890. *
  17891. * @private
  17892. */
  17893. function setSelectedOption(el, value, parser) {
  17894. if (!value) {
  17895. return;
  17896. }
  17897. for (var i = 0; i < el.options.length; i++) {
  17898. if (parseOptionValue(el.options[i].value, parser) === value) {
  17899. el.selectedIndex = i;
  17900. break;
  17901. }
  17902. }
  17903. }
  17904. /**
  17905. * Manipulate Text Tracks settings.
  17906. *
  17907. * @extends ModalDialog
  17908. */
  17909. var TextTrackSettings = /*#__PURE__*/function (_ModalDialog) {
  17910. inheritsLoose(TextTrackSettings, _ModalDialog);
  17911. /**
  17912. * Creates an instance of this class.
  17913. *
  17914. * @param {Player} player
  17915. * The `Player` that this class should be attached to.
  17916. *
  17917. * @param {Object} [options]
  17918. * The key/value store of player options.
  17919. */
  17920. function TextTrackSettings(player, options) {
  17921. var _this;
  17922. options.temporary = false;
  17923. _this = _ModalDialog.call(this, player, options) || this;
  17924. _this.updateDisplay = _this.updateDisplay.bind(assertThisInitialized(_this)); // fill the modal and pretend we have opened it
  17925. _this.fill();
  17926. _this.hasBeenOpened_ = _this.hasBeenFilled_ = true;
  17927. _this.endDialog = createEl('p', {
  17928. className: 'vjs-control-text',
  17929. textContent: _this.localize('End of dialog window.')
  17930. });
  17931. _this.el().appendChild(_this.endDialog);
  17932. _this.setDefaults(); // Grab `persistTextTrackSettings` from the player options if not passed in child options
  17933. if (options.persistTextTrackSettings === undefined) {
  17934. _this.options_.persistTextTrackSettings = _this.options_.playerOptions.persistTextTrackSettings;
  17935. }
  17936. _this.on(_this.$('.vjs-done-button'), 'click', function () {
  17937. _this.saveSettings();
  17938. _this.close();
  17939. });
  17940. _this.on(_this.$('.vjs-default-button'), 'click', function () {
  17941. _this.setDefaults();
  17942. _this.updateDisplay();
  17943. });
  17944. each(selectConfigs, function (config) {
  17945. _this.on(_this.$(config.selector), 'change', _this.updateDisplay);
  17946. });
  17947. if (_this.options_.persistTextTrackSettings) {
  17948. _this.restoreSettings();
  17949. }
  17950. return _this;
  17951. }
  17952. var _proto = TextTrackSettings.prototype;
  17953. _proto.dispose = function dispose() {
  17954. this.endDialog = null;
  17955. _ModalDialog.prototype.dispose.call(this);
  17956. }
  17957. /**
  17958. * Create a <select> element with configured options.
  17959. *
  17960. * @param {string} key
  17961. * Configuration key to use during creation.
  17962. *
  17963. * @return {string}
  17964. * An HTML string.
  17965. *
  17966. * @private
  17967. */
  17968. ;
  17969. _proto.createElSelect_ = function createElSelect_(key, legendId, type) {
  17970. var _this2 = this;
  17971. if (legendId === void 0) {
  17972. legendId = '';
  17973. }
  17974. if (type === void 0) {
  17975. type = 'label';
  17976. }
  17977. var config = selectConfigs[key];
  17978. var id = config.id.replace('%s', this.id_);
  17979. var selectLabelledbyIds = [legendId, id].join(' ').trim();
  17980. return ["<" + type + " id=\"" + id + "\" class=\"" + (type === 'label' ? 'vjs-label' : '') + "\">", this.localize(config.label), "</" + type + ">", "<select aria-labelledby=\"" + selectLabelledbyIds + "\">"].concat(config.options.map(function (o) {
  17981. var optionId = id + '-' + o[1].replace(/\W+/g, '');
  17982. return ["<option id=\"" + optionId + "\" value=\"" + o[0] + "\" ", "aria-labelledby=\"" + selectLabelledbyIds + " " + optionId + "\">", _this2.localize(o[1]), '</option>'].join('');
  17983. })).concat('</select>').join('');
  17984. }
  17985. /**
  17986. * Create foreground color element for the component
  17987. *
  17988. * @return {string}
  17989. * An HTML string.
  17990. *
  17991. * @private
  17992. */
  17993. ;
  17994. _proto.createElFgColor_ = function createElFgColor_() {
  17995. var legendId = "captions-text-legend-" + this.id_;
  17996. return ['<fieldset class="vjs-fg-color vjs-track-setting">', "<legend id=\"" + legendId + "\">", this.localize('Text'), '</legend>', this.createElSelect_('color', legendId), '<span class="vjs-text-opacity vjs-opacity">', this.createElSelect_('textOpacity', legendId), '</span>', '</fieldset>'].join('');
  17997. }
  17998. /**
  17999. * Create background color element for the component
  18000. *
  18001. * @return {string}
  18002. * An HTML string.
  18003. *
  18004. * @private
  18005. */
  18006. ;
  18007. _proto.createElBgColor_ = function createElBgColor_() {
  18008. var legendId = "captions-background-" + this.id_;
  18009. return ['<fieldset class="vjs-bg-color vjs-track-setting">', "<legend id=\"" + legendId + "\">", this.localize('Background'), '</legend>', this.createElSelect_('backgroundColor', legendId), '<span class="vjs-bg-opacity vjs-opacity">', this.createElSelect_('backgroundOpacity', legendId), '</span>', '</fieldset>'].join('');
  18010. }
  18011. /**
  18012. * Create window color element for the component
  18013. *
  18014. * @return {string}
  18015. * An HTML string.
  18016. *
  18017. * @private
  18018. */
  18019. ;
  18020. _proto.createElWinColor_ = function createElWinColor_() {
  18021. var legendId = "captions-window-" + this.id_;
  18022. return ['<fieldset class="vjs-window-color vjs-track-setting">', "<legend id=\"" + legendId + "\">", this.localize('Window'), '</legend>', this.createElSelect_('windowColor', legendId), '<span class="vjs-window-opacity vjs-opacity">', this.createElSelect_('windowOpacity', legendId), '</span>', '</fieldset>'].join('');
  18023. }
  18024. /**
  18025. * Create color elements for the component
  18026. *
  18027. * @return {Element}
  18028. * The element that was created
  18029. *
  18030. * @private
  18031. */
  18032. ;
  18033. _proto.createElColors_ = function createElColors_() {
  18034. return createEl('div', {
  18035. className: 'vjs-track-settings-colors',
  18036. innerHTML: [this.createElFgColor_(), this.createElBgColor_(), this.createElWinColor_()].join('')
  18037. });
  18038. }
  18039. /**
  18040. * Create font elements for the component
  18041. *
  18042. * @return {Element}
  18043. * The element that was created.
  18044. *
  18045. * @private
  18046. */
  18047. ;
  18048. _proto.createElFont_ = function createElFont_() {
  18049. return createEl('div', {
  18050. className: 'vjs-track-settings-font',
  18051. innerHTML: ['<fieldset class="vjs-font-percent vjs-track-setting">', this.createElSelect_('fontPercent', '', 'legend'), '</fieldset>', '<fieldset class="vjs-edge-style vjs-track-setting">', this.createElSelect_('edgeStyle', '', 'legend'), '</fieldset>', '<fieldset class="vjs-font-family vjs-track-setting">', this.createElSelect_('fontFamily', '', 'legend'), '</fieldset>'].join('')
  18052. });
  18053. }
  18054. /**
  18055. * Create controls for the component
  18056. *
  18057. * @return {Element}
  18058. * The element that was created.
  18059. *
  18060. * @private
  18061. */
  18062. ;
  18063. _proto.createElControls_ = function createElControls_() {
  18064. var defaultsDescription = this.localize('restore all settings to the default values');
  18065. return createEl('div', {
  18066. className: 'vjs-track-settings-controls',
  18067. innerHTML: ["<button type=\"button\" class=\"vjs-default-button\" title=\"" + defaultsDescription + "\">", this.localize('Reset'), "<span class=\"vjs-control-text\"> " + defaultsDescription + "</span>", '</button>', "<button type=\"button\" class=\"vjs-done-button\">" + this.localize('Done') + "</button>"].join('')
  18068. });
  18069. };
  18070. _proto.content = function content() {
  18071. return [this.createElColors_(), this.createElFont_(), this.createElControls_()];
  18072. };
  18073. _proto.label = function label() {
  18074. return this.localize('Caption Settings Dialog');
  18075. };
  18076. _proto.description = function description() {
  18077. return this.localize('Beginning of dialog window. Escape will cancel and close the window.');
  18078. };
  18079. _proto.buildCSSClass = function buildCSSClass() {
  18080. return _ModalDialog.prototype.buildCSSClass.call(this) + ' vjs-text-track-settings';
  18081. }
  18082. /**
  18083. * Gets an object of text track settings (or null).
  18084. *
  18085. * @return {Object}
  18086. * An object with config values parsed from the DOM or localStorage.
  18087. */
  18088. ;
  18089. _proto.getValues = function getValues() {
  18090. var _this3 = this;
  18091. return reduce(selectConfigs, function (accum, config, key) {
  18092. var value = getSelectedOptionValue(_this3.$(config.selector), config.parser);
  18093. if (value !== undefined) {
  18094. accum[key] = value;
  18095. }
  18096. return accum;
  18097. }, {});
  18098. }
  18099. /**
  18100. * Sets text track settings from an object of values.
  18101. *
  18102. * @param {Object} values
  18103. * An object with config values parsed from the DOM or localStorage.
  18104. */
  18105. ;
  18106. _proto.setValues = function setValues(values) {
  18107. var _this4 = this;
  18108. each(selectConfigs, function (config, key) {
  18109. setSelectedOption(_this4.$(config.selector), values[key], config.parser);
  18110. });
  18111. }
  18112. /**
  18113. * Sets all `<select>` elements to their default values.
  18114. */
  18115. ;
  18116. _proto.setDefaults = function setDefaults() {
  18117. var _this5 = this;
  18118. each(selectConfigs, function (config) {
  18119. var index = config.hasOwnProperty('default') ? config["default"] : 0;
  18120. _this5.$(config.selector).selectedIndex = index;
  18121. });
  18122. }
  18123. /**
  18124. * Restore texttrack settings from localStorage
  18125. */
  18126. ;
  18127. _proto.restoreSettings = function restoreSettings() {
  18128. var values;
  18129. try {
  18130. values = JSON.parse(window.localStorage.getItem(LOCAL_STORAGE_KEY$1));
  18131. } catch (err) {
  18132. log$1.warn(err);
  18133. }
  18134. if (values) {
  18135. this.setValues(values);
  18136. }
  18137. }
  18138. /**
  18139. * Save text track settings to localStorage
  18140. */
  18141. ;
  18142. _proto.saveSettings = function saveSettings() {
  18143. if (!this.options_.persistTextTrackSettings) {
  18144. return;
  18145. }
  18146. var values = this.getValues();
  18147. try {
  18148. if (Object.keys(values).length) {
  18149. window.localStorage.setItem(LOCAL_STORAGE_KEY$1, JSON.stringify(values));
  18150. } else {
  18151. window.localStorage.removeItem(LOCAL_STORAGE_KEY$1);
  18152. }
  18153. } catch (err) {
  18154. log$1.warn(err);
  18155. }
  18156. }
  18157. /**
  18158. * Update display of text track settings
  18159. */
  18160. ;
  18161. _proto.updateDisplay = function updateDisplay() {
  18162. var ttDisplay = this.player_.getChild('textTrackDisplay');
  18163. if (ttDisplay) {
  18164. ttDisplay.updateDisplay();
  18165. }
  18166. }
  18167. /**
  18168. * conditionally blur the element and refocus the captions button
  18169. *
  18170. * @private
  18171. */
  18172. ;
  18173. _proto.conditionalBlur_ = function conditionalBlur_() {
  18174. this.previouslyActiveEl_ = null;
  18175. var cb = this.player_.controlBar;
  18176. var subsCapsBtn = cb && cb.subsCapsButton;
  18177. var ccBtn = cb && cb.captionsButton;
  18178. if (subsCapsBtn) {
  18179. subsCapsBtn.focus();
  18180. } else if (ccBtn) {
  18181. ccBtn.focus();
  18182. }
  18183. };
  18184. return TextTrackSettings;
  18185. }(ModalDialog);
  18186. Component$1.registerComponent('TextTrackSettings', TextTrackSettings);
  18187. /**
  18188. * A Resize Manager. It is in charge of triggering `playerresize` on the player in the right conditions.
  18189. *
  18190. * It'll either create an iframe and use a debounced resize handler on it or use the new {@link https://wicg.github.io/ResizeObserver/|ResizeObserver}.
  18191. *
  18192. * If the ResizeObserver is available natively, it will be used. A polyfill can be passed in as an option.
  18193. * If a `playerresize` event is not needed, the ResizeManager component can be removed from the player, see the example below.
  18194. * @example <caption>How to disable the resize manager</caption>
  18195. * const player = videojs('#vid', {
  18196. * resizeManager: false
  18197. * });
  18198. *
  18199. * @see {@link https://wicg.github.io/ResizeObserver/|ResizeObserver specification}
  18200. *
  18201. * @extends Component
  18202. */
  18203. var ResizeManager = /*#__PURE__*/function (_Component) {
  18204. inheritsLoose(ResizeManager, _Component);
  18205. /**
  18206. * Create the ResizeManager.
  18207. *
  18208. * @param {Object} player
  18209. * The `Player` that this class should be attached to.
  18210. *
  18211. * @param {Object} [options]
  18212. * The key/value store of ResizeManager options.
  18213. *
  18214. * @param {Object} [options.ResizeObserver]
  18215. * A polyfill for ResizeObserver can be passed in here.
  18216. * If this is set to null it will ignore the native ResizeObserver and fall back to the iframe fallback.
  18217. */
  18218. function ResizeManager(player, options) {
  18219. var _this;
  18220. var RESIZE_OBSERVER_AVAILABLE = options.ResizeObserver || window.ResizeObserver; // if `null` was passed, we want to disable the ResizeObserver
  18221. if (options.ResizeObserver === null) {
  18222. RESIZE_OBSERVER_AVAILABLE = false;
  18223. } // Only create an element when ResizeObserver isn't available
  18224. var options_ = mergeOptions$3({
  18225. createEl: !RESIZE_OBSERVER_AVAILABLE,
  18226. reportTouchActivity: false
  18227. }, options);
  18228. _this = _Component.call(this, player, options_) || this;
  18229. _this.ResizeObserver = options.ResizeObserver || window.ResizeObserver;
  18230. _this.loadListener_ = null;
  18231. _this.resizeObserver_ = null;
  18232. _this.debouncedHandler_ = debounce(function () {
  18233. _this.resizeHandler();
  18234. }, 100, false, assertThisInitialized(_this));
  18235. if (RESIZE_OBSERVER_AVAILABLE) {
  18236. _this.resizeObserver_ = new _this.ResizeObserver(_this.debouncedHandler_);
  18237. _this.resizeObserver_.observe(player.el());
  18238. } else {
  18239. _this.loadListener_ = function () {
  18240. if (!_this.el_ || !_this.el_.contentWindow) {
  18241. return;
  18242. }
  18243. var debouncedHandler_ = _this.debouncedHandler_;
  18244. var unloadListener_ = _this.unloadListener_ = function () {
  18245. off(this, 'resize', debouncedHandler_);
  18246. off(this, 'unload', unloadListener_);
  18247. unloadListener_ = null;
  18248. }; // safari and edge can unload the iframe before resizemanager dispose
  18249. // we have to dispose of event handlers correctly before that happens
  18250. on(_this.el_.contentWindow, 'unload', unloadListener_);
  18251. on(_this.el_.contentWindow, 'resize', debouncedHandler_);
  18252. };
  18253. _this.one('load', _this.loadListener_);
  18254. }
  18255. return _this;
  18256. }
  18257. var _proto = ResizeManager.prototype;
  18258. _proto.createEl = function createEl() {
  18259. return _Component.prototype.createEl.call(this, 'iframe', {
  18260. className: 'vjs-resize-manager',
  18261. tabIndex: -1,
  18262. title: this.localize('No content')
  18263. }, {
  18264. 'aria-hidden': 'true'
  18265. });
  18266. }
  18267. /**
  18268. * Called when a resize is triggered on the iframe or a resize is observed via the ResizeObserver
  18269. *
  18270. * @fires Player#playerresize
  18271. */
  18272. ;
  18273. _proto.resizeHandler = function resizeHandler() {
  18274. /**
  18275. * Called when the player size has changed
  18276. *
  18277. * @event Player#playerresize
  18278. * @type {EventTarget~Event}
  18279. */
  18280. // make sure player is still around to trigger
  18281. // prevents this from causing an error after dispose
  18282. if (!this.player_ || !this.player_.trigger) {
  18283. return;
  18284. }
  18285. this.player_.trigger('playerresize');
  18286. };
  18287. _proto.dispose = function dispose() {
  18288. if (this.debouncedHandler_) {
  18289. this.debouncedHandler_.cancel();
  18290. }
  18291. if (this.resizeObserver_) {
  18292. if (this.player_.el()) {
  18293. this.resizeObserver_.unobserve(this.player_.el());
  18294. }
  18295. this.resizeObserver_.disconnect();
  18296. }
  18297. if (this.loadListener_) {
  18298. this.off('load', this.loadListener_);
  18299. }
  18300. if (this.el_ && this.el_.contentWindow && this.unloadListener_) {
  18301. this.unloadListener_.call(this.el_.contentWindow);
  18302. }
  18303. this.ResizeObserver = null;
  18304. this.resizeObserver = null;
  18305. this.debouncedHandler_ = null;
  18306. this.loadListener_ = null;
  18307. _Component.prototype.dispose.call(this);
  18308. };
  18309. return ResizeManager;
  18310. }(Component$1);
  18311. Component$1.registerComponent('ResizeManager', ResizeManager);
  18312. var defaults = {
  18313. trackingThreshold: 20,
  18314. liveTolerance: 15
  18315. };
  18316. /*
  18317. track when we are at the live edge, and other helpers for live playback */
  18318. /**
  18319. * A class for checking live current time and determining when the player
  18320. * is at or behind the live edge.
  18321. */
  18322. var LiveTracker = /*#__PURE__*/function (_Component) {
  18323. inheritsLoose(LiveTracker, _Component);
  18324. /**
  18325. * Creates an instance of this class.
  18326. *
  18327. * @param {Player} player
  18328. * The `Player` that this class should be attached to.
  18329. *
  18330. * @param {Object} [options]
  18331. * The key/value store of player options.
  18332. *
  18333. * @param {number} [options.trackingThreshold=20]
  18334. * Number of seconds of live window (seekableEnd - seekableStart) that
  18335. * media needs to have before the liveui will be shown.
  18336. *
  18337. * @param {number} [options.liveTolerance=15]
  18338. * Number of seconds behind live that we have to be
  18339. * before we will be considered non-live. Note that this will only
  18340. * be used when playing at the live edge. This allows large seekable end
  18341. * changes to not effect wether we are live or not.
  18342. */
  18343. function LiveTracker(player, options) {
  18344. var _this;
  18345. // LiveTracker does not need an element
  18346. var options_ = mergeOptions$3(defaults, options, {
  18347. createEl: false
  18348. });
  18349. _this = _Component.call(this, player, options_) || this;
  18350. _this.handleVisibilityChange_ = function (e) {
  18351. return _this.handleVisibilityChange(e);
  18352. };
  18353. _this.trackLiveHandler_ = function () {
  18354. return _this.trackLive_();
  18355. };
  18356. _this.handlePlay_ = function (e) {
  18357. return _this.handlePlay(e);
  18358. };
  18359. _this.handleFirstTimeupdate_ = function (e) {
  18360. return _this.handleFirstTimeupdate(e);
  18361. };
  18362. _this.handleSeeked_ = function (e) {
  18363. return _this.handleSeeked(e);
  18364. };
  18365. _this.seekToLiveEdge_ = function (e) {
  18366. return _this.seekToLiveEdge(e);
  18367. };
  18368. _this.reset_();
  18369. _this.on(_this.player_, 'durationchange', function (e) {
  18370. return _this.handleDurationchange(e);
  18371. }); // we should try to toggle tracking on canplay as native playback engines, like Safari
  18372. // may not have the proper values for things like seekableEnd until then
  18373. _this.on(_this.player_, 'canplay', function () {
  18374. return _this.toggleTracking();
  18375. }); // we don't need to track live playback if the document is hidden,
  18376. // also, tracking when the document is hidden can
  18377. // cause the CPU to spike and eventually crash the page on IE11.
  18378. if (IE_VERSION && 'hidden' in document && 'visibilityState' in document) {
  18379. _this.on(document, 'visibilitychange', _this.handleVisibilityChange_);
  18380. }
  18381. return _this;
  18382. }
  18383. /**
  18384. * toggle tracking based on document visiblility
  18385. */
  18386. var _proto = LiveTracker.prototype;
  18387. _proto.handleVisibilityChange = function handleVisibilityChange() {
  18388. if (this.player_.duration() !== Infinity) {
  18389. return;
  18390. }
  18391. if (document.hidden) {
  18392. this.stopTracking();
  18393. } else {
  18394. this.startTracking();
  18395. }
  18396. }
  18397. /**
  18398. * all the functionality for tracking when seek end changes
  18399. * and for tracking how far past seek end we should be
  18400. */
  18401. ;
  18402. _proto.trackLive_ = function trackLive_() {
  18403. var seekable = this.player_.seekable(); // skip undefined seekable
  18404. if (!seekable || !seekable.length) {
  18405. return;
  18406. }
  18407. var newTime = Number(window.performance.now().toFixed(4));
  18408. var deltaTime = this.lastTime_ === -1 ? 0 : (newTime - this.lastTime_) / 1000;
  18409. this.lastTime_ = newTime;
  18410. this.pastSeekEnd_ = this.pastSeekEnd() + deltaTime;
  18411. var liveCurrentTime = this.liveCurrentTime();
  18412. var currentTime = this.player_.currentTime(); // we are behind live if any are true
  18413. // 1. the player is paused
  18414. // 2. the user seeked to a location 2 seconds away from live
  18415. // 3. the difference between live and current time is greater
  18416. // liveTolerance which defaults to 15s
  18417. var isBehind = this.player_.paused() || this.seekedBehindLive_ || Math.abs(liveCurrentTime - currentTime) > this.options_.liveTolerance; // we cannot be behind if
  18418. // 1. until we have not seen a timeupdate yet
  18419. // 2. liveCurrentTime is Infinity, which happens on Android and Native Safari
  18420. if (!this.timeupdateSeen_ || liveCurrentTime === Infinity) {
  18421. isBehind = false;
  18422. }
  18423. if (isBehind !== this.behindLiveEdge_) {
  18424. this.behindLiveEdge_ = isBehind;
  18425. this.trigger('liveedgechange');
  18426. }
  18427. }
  18428. /**
  18429. * handle a durationchange event on the player
  18430. * and start/stop tracking accordingly.
  18431. */
  18432. ;
  18433. _proto.handleDurationchange = function handleDurationchange() {
  18434. this.toggleTracking();
  18435. }
  18436. /**
  18437. * start/stop tracking
  18438. */
  18439. ;
  18440. _proto.toggleTracking = function toggleTracking() {
  18441. if (this.player_.duration() === Infinity && this.liveWindow() >= this.options_.trackingThreshold) {
  18442. if (this.player_.options_.liveui) {
  18443. this.player_.addClass('vjs-liveui');
  18444. }
  18445. this.startTracking();
  18446. } else {
  18447. this.player_.removeClass('vjs-liveui');
  18448. this.stopTracking();
  18449. }
  18450. }
  18451. /**
  18452. * start tracking live playback
  18453. */
  18454. ;
  18455. _proto.startTracking = function startTracking() {
  18456. if (this.isTracking()) {
  18457. return;
  18458. } // If we haven't seen a timeupdate, we need to check whether playback
  18459. // began before this component started tracking. This can happen commonly
  18460. // when using autoplay.
  18461. if (!this.timeupdateSeen_) {
  18462. this.timeupdateSeen_ = this.player_.hasStarted();
  18463. }
  18464. this.trackingInterval_ = this.setInterval(this.trackLiveHandler_, UPDATE_REFRESH_INTERVAL);
  18465. this.trackLive_();
  18466. this.on(this.player_, ['play', 'pause'], this.trackLiveHandler_);
  18467. if (!this.timeupdateSeen_) {
  18468. this.one(this.player_, 'play', this.handlePlay_);
  18469. this.one(this.player_, 'timeupdate', this.handleFirstTimeupdate_);
  18470. } else {
  18471. this.on(this.player_, 'seeked', this.handleSeeked_);
  18472. }
  18473. }
  18474. /**
  18475. * handle the first timeupdate on the player if it wasn't already playing
  18476. * when live tracker started tracking.
  18477. */
  18478. ;
  18479. _proto.handleFirstTimeupdate = function handleFirstTimeupdate() {
  18480. this.timeupdateSeen_ = true;
  18481. this.on(this.player_, 'seeked', this.handleSeeked_);
  18482. }
  18483. /**
  18484. * Keep track of what time a seek starts, and listen for seeked
  18485. * to find where a seek ends.
  18486. */
  18487. ;
  18488. _proto.handleSeeked = function handleSeeked() {
  18489. var timeDiff = Math.abs(this.liveCurrentTime() - this.player_.currentTime());
  18490. this.seekedBehindLive_ = this.nextSeekedFromUser_ && timeDiff > 2;
  18491. this.nextSeekedFromUser_ = false;
  18492. this.trackLive_();
  18493. }
  18494. /**
  18495. * handle the first play on the player, and make sure that we seek
  18496. * right to the live edge.
  18497. */
  18498. ;
  18499. _proto.handlePlay = function handlePlay() {
  18500. this.one(this.player_, 'timeupdate', this.seekToLiveEdge_);
  18501. }
  18502. /**
  18503. * Stop tracking, and set all internal variables to
  18504. * their initial value.
  18505. */
  18506. ;
  18507. _proto.reset_ = function reset_() {
  18508. this.lastTime_ = -1;
  18509. this.pastSeekEnd_ = 0;
  18510. this.lastSeekEnd_ = -1;
  18511. this.behindLiveEdge_ = true;
  18512. this.timeupdateSeen_ = false;
  18513. this.seekedBehindLive_ = false;
  18514. this.nextSeekedFromUser_ = false;
  18515. this.clearInterval(this.trackingInterval_);
  18516. this.trackingInterval_ = null;
  18517. this.off(this.player_, ['play', 'pause'], this.trackLiveHandler_);
  18518. this.off(this.player_, 'seeked', this.handleSeeked_);
  18519. this.off(this.player_, 'play', this.handlePlay_);
  18520. this.off(this.player_, 'timeupdate', this.handleFirstTimeupdate_);
  18521. this.off(this.player_, 'timeupdate', this.seekToLiveEdge_);
  18522. }
  18523. /**
  18524. * The next seeked event is from the user. Meaning that any seek
  18525. * > 2s behind live will be considered behind live for real and
  18526. * liveTolerance will be ignored.
  18527. */
  18528. ;
  18529. _proto.nextSeekedFromUser = function nextSeekedFromUser() {
  18530. this.nextSeekedFromUser_ = true;
  18531. }
  18532. /**
  18533. * stop tracking live playback
  18534. */
  18535. ;
  18536. _proto.stopTracking = function stopTracking() {
  18537. if (!this.isTracking()) {
  18538. return;
  18539. }
  18540. this.reset_();
  18541. this.trigger('liveedgechange');
  18542. }
  18543. /**
  18544. * A helper to get the player seekable end
  18545. * so that we don't have to null check everywhere
  18546. *
  18547. * @return {number}
  18548. * The furthest seekable end or Infinity.
  18549. */
  18550. ;
  18551. _proto.seekableEnd = function seekableEnd() {
  18552. var seekable = this.player_.seekable();
  18553. var seekableEnds = [];
  18554. var i = seekable ? seekable.length : 0;
  18555. while (i--) {
  18556. seekableEnds.push(seekable.end(i));
  18557. } // grab the furthest seekable end after sorting, or if there are none
  18558. // default to Infinity
  18559. return seekableEnds.length ? seekableEnds.sort()[seekableEnds.length - 1] : Infinity;
  18560. }
  18561. /**
  18562. * A helper to get the player seekable start
  18563. * so that we don't have to null check everywhere
  18564. *
  18565. * @return {number}
  18566. * The earliest seekable start or 0.
  18567. */
  18568. ;
  18569. _proto.seekableStart = function seekableStart() {
  18570. var seekable = this.player_.seekable();
  18571. var seekableStarts = [];
  18572. var i = seekable ? seekable.length : 0;
  18573. while (i--) {
  18574. seekableStarts.push(seekable.start(i));
  18575. } // grab the first seekable start after sorting, or if there are none
  18576. // default to 0
  18577. return seekableStarts.length ? seekableStarts.sort()[0] : 0;
  18578. }
  18579. /**
  18580. * Get the live time window aka
  18581. * the amount of time between seekable start and
  18582. * live current time.
  18583. *
  18584. * @return {number}
  18585. * The amount of seconds that are seekable in
  18586. * the live video.
  18587. */
  18588. ;
  18589. _proto.liveWindow = function liveWindow() {
  18590. var liveCurrentTime = this.liveCurrentTime(); // if liveCurrenTime is Infinity then we don't have a liveWindow at all
  18591. if (liveCurrentTime === Infinity) {
  18592. return 0;
  18593. }
  18594. return liveCurrentTime - this.seekableStart();
  18595. }
  18596. /**
  18597. * Determines if the player is live, only checks if this component
  18598. * is tracking live playback or not
  18599. *
  18600. * @return {boolean}
  18601. * Wether liveTracker is tracking
  18602. */
  18603. ;
  18604. _proto.isLive = function isLive() {
  18605. return this.isTracking();
  18606. }
  18607. /**
  18608. * Determines if currentTime is at the live edge and won't fall behind
  18609. * on each seekableendchange
  18610. *
  18611. * @return {boolean}
  18612. * Wether playback is at the live edge
  18613. */
  18614. ;
  18615. _proto.atLiveEdge = function atLiveEdge() {
  18616. return !this.behindLiveEdge();
  18617. }
  18618. /**
  18619. * get what we expect the live current time to be
  18620. *
  18621. * @return {number}
  18622. * The expected live current time
  18623. */
  18624. ;
  18625. _proto.liveCurrentTime = function liveCurrentTime() {
  18626. return this.pastSeekEnd() + this.seekableEnd();
  18627. }
  18628. /**
  18629. * The number of seconds that have occured after seekable end
  18630. * changed. This will be reset to 0 once seekable end changes.
  18631. *
  18632. * @return {number}
  18633. * Seconds past the current seekable end
  18634. */
  18635. ;
  18636. _proto.pastSeekEnd = function pastSeekEnd() {
  18637. var seekableEnd = this.seekableEnd();
  18638. if (this.lastSeekEnd_ !== -1 && seekableEnd !== this.lastSeekEnd_) {
  18639. this.pastSeekEnd_ = 0;
  18640. }
  18641. this.lastSeekEnd_ = seekableEnd;
  18642. return this.pastSeekEnd_;
  18643. }
  18644. /**
  18645. * If we are currently behind the live edge, aka currentTime will be
  18646. * behind on a seekableendchange
  18647. *
  18648. * @return {boolean}
  18649. * If we are behind the live edge
  18650. */
  18651. ;
  18652. _proto.behindLiveEdge = function behindLiveEdge() {
  18653. return this.behindLiveEdge_;
  18654. }
  18655. /**
  18656. * Wether live tracker is currently tracking or not.
  18657. */
  18658. ;
  18659. _proto.isTracking = function isTracking() {
  18660. return typeof this.trackingInterval_ === 'number';
  18661. }
  18662. /**
  18663. * Seek to the live edge if we are behind the live edge
  18664. */
  18665. ;
  18666. _proto.seekToLiveEdge = function seekToLiveEdge() {
  18667. this.seekedBehindLive_ = false;
  18668. if (this.atLiveEdge()) {
  18669. return;
  18670. }
  18671. this.nextSeekedFromUser_ = false;
  18672. this.player_.currentTime(this.liveCurrentTime());
  18673. }
  18674. /**
  18675. * Dispose of liveTracker
  18676. */
  18677. ;
  18678. _proto.dispose = function dispose() {
  18679. this.off(document, 'visibilitychange', this.handleVisibilityChange_);
  18680. this.stopTracking();
  18681. _Component.prototype.dispose.call(this);
  18682. };
  18683. return LiveTracker;
  18684. }(Component$1);
  18685. Component$1.registerComponent('LiveTracker', LiveTracker);
  18686. /**
  18687. * This function is used to fire a sourceset when there is something
  18688. * similar to `mediaEl.load()` being called. It will try to find the source via
  18689. * the `src` attribute and then the `<source>` elements. It will then fire `sourceset`
  18690. * with the source that was found or empty string if we cannot know. If it cannot
  18691. * find a source then `sourceset` will not be fired.
  18692. *
  18693. * @param {Html5} tech
  18694. * The tech object that sourceset was setup on
  18695. *
  18696. * @return {boolean}
  18697. * returns false if the sourceset was not fired and true otherwise.
  18698. */
  18699. var sourcesetLoad = function sourcesetLoad(tech) {
  18700. var el = tech.el(); // if `el.src` is set, that source will be loaded.
  18701. if (el.hasAttribute('src')) {
  18702. tech.triggerSourceset(el.src);
  18703. return true;
  18704. }
  18705. /**
  18706. * Since there isn't a src property on the media element, source elements will be used for
  18707. * implementing the source selection algorithm. This happens asynchronously and
  18708. * for most cases were there is more than one source we cannot tell what source will
  18709. * be loaded, without re-implementing the source selection algorithm. At this time we are not
  18710. * going to do that. There are three special cases that we do handle here though:
  18711. *
  18712. * 1. If there are no sources, do not fire `sourceset`.
  18713. * 2. If there is only one `<source>` with a `src` property/attribute that is our `src`
  18714. * 3. If there is more than one `<source>` but all of them have the same `src` url.
  18715. * That will be our src.
  18716. */
  18717. var sources = tech.$$('source');
  18718. var srcUrls = [];
  18719. var src = ''; // if there are no sources, do not fire sourceset
  18720. if (!sources.length) {
  18721. return false;
  18722. } // only count valid/non-duplicate source elements
  18723. for (var i = 0; i < sources.length; i++) {
  18724. var url = sources[i].src;
  18725. if (url && srcUrls.indexOf(url) === -1) {
  18726. srcUrls.push(url);
  18727. }
  18728. } // there were no valid sources
  18729. if (!srcUrls.length) {
  18730. return false;
  18731. } // there is only one valid source element url
  18732. // use that
  18733. if (srcUrls.length === 1) {
  18734. src = srcUrls[0];
  18735. }
  18736. tech.triggerSourceset(src);
  18737. return true;
  18738. };
  18739. /**
  18740. * our implementation of an `innerHTML` descriptor for browsers
  18741. * that do not have one.
  18742. */
  18743. var innerHTMLDescriptorPolyfill = Object.defineProperty({}, 'innerHTML', {
  18744. get: function get() {
  18745. return this.cloneNode(true).innerHTML;
  18746. },
  18747. set: function set(v) {
  18748. // make a dummy node to use innerHTML on
  18749. var dummy = document.createElement(this.nodeName.toLowerCase()); // set innerHTML to the value provided
  18750. dummy.innerHTML = v; // make a document fragment to hold the nodes from dummy
  18751. var docFrag = document.createDocumentFragment(); // copy all of the nodes created by the innerHTML on dummy
  18752. // to the document fragment
  18753. while (dummy.childNodes.length) {
  18754. docFrag.appendChild(dummy.childNodes[0]);
  18755. } // remove content
  18756. this.innerText = ''; // now we add all of that html in one by appending the
  18757. // document fragment. This is how innerHTML does it.
  18758. window.Element.prototype.appendChild.call(this, docFrag); // then return the result that innerHTML's setter would
  18759. return this.innerHTML;
  18760. }
  18761. });
  18762. /**
  18763. * Get a property descriptor given a list of priorities and the
  18764. * property to get.
  18765. */
  18766. var getDescriptor = function getDescriptor(priority, prop) {
  18767. var descriptor = {};
  18768. for (var i = 0; i < priority.length; i++) {
  18769. descriptor = Object.getOwnPropertyDescriptor(priority[i], prop);
  18770. if (descriptor && descriptor.set && descriptor.get) {
  18771. break;
  18772. }
  18773. }
  18774. descriptor.enumerable = true;
  18775. descriptor.configurable = true;
  18776. return descriptor;
  18777. };
  18778. var getInnerHTMLDescriptor = function getInnerHTMLDescriptor(tech) {
  18779. return getDescriptor([tech.el(), window.HTMLMediaElement.prototype, window.Element.prototype, innerHTMLDescriptorPolyfill], 'innerHTML');
  18780. };
  18781. /**
  18782. * Patches browser internal functions so that we can tell synchronously
  18783. * if a `<source>` was appended to the media element. For some reason this
  18784. * causes a `sourceset` if the the media element is ready and has no source.
  18785. * This happens when:
  18786. * - The page has just loaded and the media element does not have a source.
  18787. * - The media element was emptied of all sources, then `load()` was called.
  18788. *
  18789. * It does this by patching the following functions/properties when they are supported:
  18790. *
  18791. * - `append()` - can be used to add a `<source>` element to the media element
  18792. * - `appendChild()` - can be used to add a `<source>` element to the media element
  18793. * - `insertAdjacentHTML()` - can be used to add a `<source>` element to the media element
  18794. * - `innerHTML` - can be used to add a `<source>` element to the media element
  18795. *
  18796. * @param {Html5} tech
  18797. * The tech object that sourceset is being setup on.
  18798. */
  18799. var firstSourceWatch = function firstSourceWatch(tech) {
  18800. var el = tech.el(); // make sure firstSourceWatch isn't setup twice.
  18801. if (el.resetSourceWatch_) {
  18802. return;
  18803. }
  18804. var old = {};
  18805. var innerDescriptor = getInnerHTMLDescriptor(tech);
  18806. var appendWrapper = function appendWrapper(appendFn) {
  18807. return function () {
  18808. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  18809. args[_key] = arguments[_key];
  18810. }
  18811. var retval = appendFn.apply(el, args);
  18812. sourcesetLoad(tech);
  18813. return retval;
  18814. };
  18815. };
  18816. ['append', 'appendChild', 'insertAdjacentHTML'].forEach(function (k) {
  18817. if (!el[k]) {
  18818. return;
  18819. } // store the old function
  18820. old[k] = el[k]; // call the old function with a sourceset if a source
  18821. // was loaded
  18822. el[k] = appendWrapper(old[k]);
  18823. });
  18824. Object.defineProperty(el, 'innerHTML', mergeOptions$3(innerDescriptor, {
  18825. set: appendWrapper(innerDescriptor.set)
  18826. }));
  18827. el.resetSourceWatch_ = function () {
  18828. el.resetSourceWatch_ = null;
  18829. Object.keys(old).forEach(function (k) {
  18830. el[k] = old[k];
  18831. });
  18832. Object.defineProperty(el, 'innerHTML', innerDescriptor);
  18833. }; // on the first sourceset, we need to revert our changes
  18834. tech.one('sourceset', el.resetSourceWatch_);
  18835. };
  18836. /**
  18837. * our implementation of a `src` descriptor for browsers
  18838. * that do not have one.
  18839. */
  18840. var srcDescriptorPolyfill = Object.defineProperty({}, 'src', {
  18841. get: function get() {
  18842. if (this.hasAttribute('src')) {
  18843. return getAbsoluteURL(window.Element.prototype.getAttribute.call(this, 'src'));
  18844. }
  18845. return '';
  18846. },
  18847. set: function set(v) {
  18848. window.Element.prototype.setAttribute.call(this, 'src', v);
  18849. return v;
  18850. }
  18851. });
  18852. var getSrcDescriptor = function getSrcDescriptor(tech) {
  18853. return getDescriptor([tech.el(), window.HTMLMediaElement.prototype, srcDescriptorPolyfill], 'src');
  18854. };
  18855. /**
  18856. * setup `sourceset` handling on the `Html5` tech. This function
  18857. * patches the following element properties/functions:
  18858. *
  18859. * - `src` - to determine when `src` is set
  18860. * - `setAttribute()` - to determine when `src` is set
  18861. * - `load()` - this re-triggers the source selection algorithm, and can
  18862. * cause a sourceset.
  18863. *
  18864. * If there is no source when we are adding `sourceset` support or during a `load()`
  18865. * we also patch the functions listed in `firstSourceWatch`.
  18866. *
  18867. * @param {Html5} tech
  18868. * The tech to patch
  18869. */
  18870. var setupSourceset = function setupSourceset(tech) {
  18871. if (!tech.featuresSourceset) {
  18872. return;
  18873. }
  18874. var el = tech.el(); // make sure sourceset isn't setup twice.
  18875. if (el.resetSourceset_) {
  18876. return;
  18877. }
  18878. var srcDescriptor = getSrcDescriptor(tech);
  18879. var oldSetAttribute = el.setAttribute;
  18880. var oldLoad = el.load;
  18881. Object.defineProperty(el, 'src', mergeOptions$3(srcDescriptor, {
  18882. set: function set(v) {
  18883. var retval = srcDescriptor.set.call(el, v); // we use the getter here to get the actual value set on src
  18884. tech.triggerSourceset(el.src);
  18885. return retval;
  18886. }
  18887. }));
  18888. el.setAttribute = function (n, v) {
  18889. var retval = oldSetAttribute.call(el, n, v);
  18890. if (/src/i.test(n)) {
  18891. tech.triggerSourceset(el.src);
  18892. }
  18893. return retval;
  18894. };
  18895. el.load = function () {
  18896. var retval = oldLoad.call(el); // if load was called, but there was no source to fire
  18897. // sourceset on. We have to watch for a source append
  18898. // as that can trigger a `sourceset` when the media element
  18899. // has no source
  18900. if (!sourcesetLoad(tech)) {
  18901. tech.triggerSourceset('');
  18902. firstSourceWatch(tech);
  18903. }
  18904. return retval;
  18905. };
  18906. if (el.currentSrc) {
  18907. tech.triggerSourceset(el.currentSrc);
  18908. } else if (!sourcesetLoad(tech)) {
  18909. firstSourceWatch(tech);
  18910. }
  18911. el.resetSourceset_ = function () {
  18912. el.resetSourceset_ = null;
  18913. el.load = oldLoad;
  18914. el.setAttribute = oldSetAttribute;
  18915. Object.defineProperty(el, 'src', srcDescriptor);
  18916. if (el.resetSourceWatch_) {
  18917. el.resetSourceWatch_();
  18918. }
  18919. };
  18920. };
  18921. /**
  18922. * Object.defineProperty but "lazy", which means that the value is only set after
  18923. * it retrieved the first time, rather than being set right away.
  18924. *
  18925. * @param {Object} obj the object to set the property on
  18926. * @param {string} key the key for the property to set
  18927. * @param {Function} getValue the function used to get the value when it is needed.
  18928. * @param {boolean} setter wether a setter shoould be allowed or not
  18929. */
  18930. var defineLazyProperty = function defineLazyProperty(obj, key, getValue, setter) {
  18931. if (setter === void 0) {
  18932. setter = true;
  18933. }
  18934. var set = function set(value) {
  18935. return Object.defineProperty(obj, key, {
  18936. value: value,
  18937. enumerable: true,
  18938. writable: true
  18939. });
  18940. };
  18941. var options = {
  18942. configurable: true,
  18943. enumerable: true,
  18944. get: function get() {
  18945. var value = getValue();
  18946. set(value);
  18947. return value;
  18948. }
  18949. };
  18950. if (setter) {
  18951. options.set = set;
  18952. }
  18953. return Object.defineProperty(obj, key, options);
  18954. };
  18955. /**
  18956. * HTML5 Media Controller - Wrapper for HTML5 Media API
  18957. *
  18958. * @mixes Tech~SourceHandlerAdditions
  18959. * @extends Tech
  18960. */
  18961. var Html5 = /*#__PURE__*/function (_Tech) {
  18962. inheritsLoose(Html5, _Tech);
  18963. /**
  18964. * Create an instance of this Tech.
  18965. *
  18966. * @param {Object} [options]
  18967. * The key/value store of player options.
  18968. *
  18969. * @param {Component~ReadyCallback} ready
  18970. * Callback function to call when the `HTML5` Tech is ready.
  18971. */
  18972. function Html5(options, ready) {
  18973. var _this;
  18974. _this = _Tech.call(this, options, ready) || this;
  18975. var source = options.source;
  18976. var crossoriginTracks = false;
  18977. _this.featuresVideoFrameCallback = _this.featuresVideoFrameCallback && _this.el_.tagName === 'VIDEO'; // Set the source if one is provided
  18978. // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted)
  18979. // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source
  18980. // anyway so the error gets fired.
  18981. if (source && (_this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) {
  18982. _this.setSource(source);
  18983. } else {
  18984. _this.handleLateInit_(_this.el_);
  18985. } // setup sourceset after late sourceset/init
  18986. if (options.enableSourceset) {
  18987. _this.setupSourcesetHandling_();
  18988. }
  18989. _this.isScrubbing_ = false;
  18990. if (_this.el_.hasChildNodes()) {
  18991. var nodes = _this.el_.childNodes;
  18992. var nodesLength = nodes.length;
  18993. var removeNodes = [];
  18994. while (nodesLength--) {
  18995. var node = nodes[nodesLength];
  18996. var nodeName = node.nodeName.toLowerCase();
  18997. if (nodeName === 'track') {
  18998. if (!_this.featuresNativeTextTracks) {
  18999. // Empty video tag tracks so the built-in player doesn't use them also.
  19000. // This may not be fast enough to stop HTML5 browsers from reading the tags
  19001. // so we'll need to turn off any default tracks if we're manually doing
  19002. // captions and subtitles. videoElement.textTracks
  19003. removeNodes.push(node);
  19004. } else {
  19005. // store HTMLTrackElement and TextTrack to remote list
  19006. _this.remoteTextTrackEls().addTrackElement_(node);
  19007. _this.remoteTextTracks().addTrack(node.track);
  19008. _this.textTracks().addTrack(node.track);
  19009. if (!crossoriginTracks && !_this.el_.hasAttribute('crossorigin') && isCrossOrigin(node.src)) {
  19010. crossoriginTracks = true;
  19011. }
  19012. }
  19013. }
  19014. }
  19015. for (var i = 0; i < removeNodes.length; i++) {
  19016. _this.el_.removeChild(removeNodes[i]);
  19017. }
  19018. }
  19019. _this.proxyNativeTracks_();
  19020. if (_this.featuresNativeTextTracks && crossoriginTracks) {
  19021. log$1.warn('Text Tracks are being loaded from another origin but the crossorigin attribute isn\'t used.\n' + 'This may prevent text tracks from loading.');
  19022. } // prevent iOS Safari from disabling metadata text tracks during native playback
  19023. _this.restoreMetadataTracksInIOSNativePlayer_(); // Determine if native controls should be used
  19024. // Our goal should be to get the custom controls on mobile solid everywhere
  19025. // so we can remove this all together. Right now this will block custom
  19026. // controls on touch enabled laptops like the Chrome Pixel
  19027. if ((TOUCH_ENABLED || IS_IPHONE || IS_NATIVE_ANDROID) && options.nativeControlsForTouch === true) {
  19028. _this.setControls(true);
  19029. } // on iOS, we want to proxy `webkitbeginfullscreen` and `webkitendfullscreen`
  19030. // into a `fullscreenchange` event
  19031. _this.proxyWebkitFullscreen_();
  19032. _this.triggerReady();
  19033. return _this;
  19034. }
  19035. /**
  19036. * Dispose of `HTML5` media element and remove all tracks.
  19037. */
  19038. var _proto = Html5.prototype;
  19039. _proto.dispose = function dispose() {
  19040. if (this.el_ && this.el_.resetSourceset_) {
  19041. this.el_.resetSourceset_();
  19042. }
  19043. Html5.disposeMediaElement(this.el_);
  19044. this.options_ = null; // tech will handle clearing of the emulated track list
  19045. _Tech.prototype.dispose.call(this);
  19046. }
  19047. /**
  19048. * Modify the media element so that we can detect when
  19049. * the source is changed. Fires `sourceset` just after the source has changed
  19050. */
  19051. ;
  19052. _proto.setupSourcesetHandling_ = function setupSourcesetHandling_() {
  19053. setupSourceset(this);
  19054. }
  19055. /**
  19056. * When a captions track is enabled in the iOS Safari native player, all other
  19057. * tracks are disabled (including metadata tracks), which nulls all of their
  19058. * associated cue points. This will restore metadata tracks to their pre-fullscreen
  19059. * state in those cases so that cue points are not needlessly lost.
  19060. *
  19061. * @private
  19062. */
  19063. ;
  19064. _proto.restoreMetadataTracksInIOSNativePlayer_ = function restoreMetadataTracksInIOSNativePlayer_() {
  19065. var textTracks = this.textTracks();
  19066. var metadataTracksPreFullscreenState; // captures a snapshot of every metadata track's current state
  19067. var takeMetadataTrackSnapshot = function takeMetadataTrackSnapshot() {
  19068. metadataTracksPreFullscreenState = [];
  19069. for (var i = 0; i < textTracks.length; i++) {
  19070. var track = textTracks[i];
  19071. if (track.kind === 'metadata') {
  19072. metadataTracksPreFullscreenState.push({
  19073. track: track,
  19074. storedMode: track.mode
  19075. });
  19076. }
  19077. }
  19078. }; // snapshot each metadata track's initial state, and update the snapshot
  19079. // each time there is a track 'change' event
  19080. takeMetadataTrackSnapshot();
  19081. textTracks.addEventListener('change', takeMetadataTrackSnapshot);
  19082. this.on('dispose', function () {
  19083. return textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
  19084. });
  19085. var restoreTrackMode = function restoreTrackMode() {
  19086. for (var i = 0; i < metadataTracksPreFullscreenState.length; i++) {
  19087. var storedTrack = metadataTracksPreFullscreenState[i];
  19088. if (storedTrack.track.mode === 'disabled' && storedTrack.track.mode !== storedTrack.storedMode) {
  19089. storedTrack.track.mode = storedTrack.storedMode;
  19090. }
  19091. } // we only want this handler to be executed on the first 'change' event
  19092. textTracks.removeEventListener('change', restoreTrackMode);
  19093. }; // when we enter fullscreen playback, stop updating the snapshot and
  19094. // restore all track modes to their pre-fullscreen state
  19095. this.on('webkitbeginfullscreen', function () {
  19096. textTracks.removeEventListener('change', takeMetadataTrackSnapshot); // remove the listener before adding it just in case it wasn't previously removed
  19097. textTracks.removeEventListener('change', restoreTrackMode);
  19098. textTracks.addEventListener('change', restoreTrackMode);
  19099. }); // start updating the snapshot again after leaving fullscreen
  19100. this.on('webkitendfullscreen', function () {
  19101. // remove the listener before adding it just in case it wasn't previously removed
  19102. textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
  19103. textTracks.addEventListener('change', takeMetadataTrackSnapshot); // remove the restoreTrackMode handler in case it wasn't triggered during fullscreen playback
  19104. textTracks.removeEventListener('change', restoreTrackMode);
  19105. });
  19106. }
  19107. /**
  19108. * Attempt to force override of tracks for the given type
  19109. *
  19110. * @param {string} type - Track type to override, possible values include 'Audio',
  19111. * 'Video', and 'Text'.
  19112. * @param {boolean} override - If set to true native audio/video will be overridden,
  19113. * otherwise native audio/video will potentially be used.
  19114. * @private
  19115. */
  19116. ;
  19117. _proto.overrideNative_ = function overrideNative_(type, override) {
  19118. var _this2 = this;
  19119. // If there is no behavioral change don't add/remove listeners
  19120. if (override !== this["featuresNative" + type + "Tracks"]) {
  19121. return;
  19122. }
  19123. var lowerCaseType = type.toLowerCase();
  19124. if (this[lowerCaseType + "TracksListeners_"]) {
  19125. Object.keys(this[lowerCaseType + "TracksListeners_"]).forEach(function (eventName) {
  19126. var elTracks = _this2.el()[lowerCaseType + "Tracks"];
  19127. elTracks.removeEventListener(eventName, _this2[lowerCaseType + "TracksListeners_"][eventName]);
  19128. });
  19129. }
  19130. this["featuresNative" + type + "Tracks"] = !override;
  19131. this[lowerCaseType + "TracksListeners_"] = null;
  19132. this.proxyNativeTracksForType_(lowerCaseType);
  19133. }
  19134. /**
  19135. * Attempt to force override of native audio tracks.
  19136. *
  19137. * @param {boolean} override - If set to true native audio will be overridden,
  19138. * otherwise native audio will potentially be used.
  19139. */
  19140. ;
  19141. _proto.overrideNativeAudioTracks = function overrideNativeAudioTracks(override) {
  19142. this.overrideNative_('Audio', override);
  19143. }
  19144. /**
  19145. * Attempt to force override of native video tracks.
  19146. *
  19147. * @param {boolean} override - If set to true native video will be overridden,
  19148. * otherwise native video will potentially be used.
  19149. */
  19150. ;
  19151. _proto.overrideNativeVideoTracks = function overrideNativeVideoTracks(override) {
  19152. this.overrideNative_('Video', override);
  19153. }
  19154. /**
  19155. * Proxy native track list events for the given type to our track
  19156. * lists if the browser we are playing in supports that type of track list.
  19157. *
  19158. * @param {string} name - Track type; values include 'audio', 'video', and 'text'
  19159. * @private
  19160. */
  19161. ;
  19162. _proto.proxyNativeTracksForType_ = function proxyNativeTracksForType_(name) {
  19163. var _this3 = this;
  19164. var props = NORMAL[name];
  19165. var elTracks = this.el()[props.getterName];
  19166. var techTracks = this[props.getterName]();
  19167. if (!this["featuresNative" + props.capitalName + "Tracks"] || !elTracks || !elTracks.addEventListener) {
  19168. return;
  19169. }
  19170. var listeners = {
  19171. change: function change(e) {
  19172. var event = {
  19173. type: 'change',
  19174. target: techTracks,
  19175. currentTarget: techTracks,
  19176. srcElement: techTracks
  19177. };
  19178. techTracks.trigger(event); // if we are a text track change event, we should also notify the
  19179. // remote text track list. This can potentially cause a false positive
  19180. // if we were to get a change event on a non-remote track and
  19181. // we triggered the event on the remote text track list which doesn't
  19182. // contain that track. However, best practices mean looping through the
  19183. // list of tracks and searching for the appropriate mode value, so,
  19184. // this shouldn't pose an issue
  19185. if (name === 'text') {
  19186. _this3[REMOTE.remoteText.getterName]().trigger(event);
  19187. }
  19188. },
  19189. addtrack: function addtrack(e) {
  19190. techTracks.addTrack(e.track);
  19191. },
  19192. removetrack: function removetrack(e) {
  19193. techTracks.removeTrack(e.track);
  19194. }
  19195. };
  19196. var removeOldTracks = function removeOldTracks() {
  19197. var removeTracks = [];
  19198. for (var i = 0; i < techTracks.length; i++) {
  19199. var found = false;
  19200. for (var j = 0; j < elTracks.length; j++) {
  19201. if (elTracks[j] === techTracks[i]) {
  19202. found = true;
  19203. break;
  19204. }
  19205. }
  19206. if (!found) {
  19207. removeTracks.push(techTracks[i]);
  19208. }
  19209. }
  19210. while (removeTracks.length) {
  19211. techTracks.removeTrack(removeTracks.shift());
  19212. }
  19213. };
  19214. this[props.getterName + 'Listeners_'] = listeners;
  19215. Object.keys(listeners).forEach(function (eventName) {
  19216. var listener = listeners[eventName];
  19217. elTracks.addEventListener(eventName, listener);
  19218. _this3.on('dispose', function (e) {
  19219. return elTracks.removeEventListener(eventName, listener);
  19220. });
  19221. }); // Remove (native) tracks that are not used anymore
  19222. this.on('loadstart', removeOldTracks);
  19223. this.on('dispose', function (e) {
  19224. return _this3.off('loadstart', removeOldTracks);
  19225. });
  19226. }
  19227. /**
  19228. * Proxy all native track list events to our track lists if the browser we are playing
  19229. * in supports that type of track list.
  19230. *
  19231. * @private
  19232. */
  19233. ;
  19234. _proto.proxyNativeTracks_ = function proxyNativeTracks_() {
  19235. var _this4 = this;
  19236. NORMAL.names.forEach(function (name) {
  19237. _this4.proxyNativeTracksForType_(name);
  19238. });
  19239. }
  19240. /**
  19241. * Create the `Html5` Tech's DOM element.
  19242. *
  19243. * @return {Element}
  19244. * The element that gets created.
  19245. */
  19246. ;
  19247. _proto.createEl = function createEl() {
  19248. var el = this.options_.tag; // Check if this browser supports moving the element into the box.
  19249. // On the iPhone video will break if you move the element,
  19250. // So we have to create a brand new element.
  19251. // If we ingested the player div, we do not need to move the media element.
  19252. if (!el || !(this.options_.playerElIngest || this.movingMediaElementInDOM)) {
  19253. // If the original tag is still there, clone and remove it.
  19254. if (el) {
  19255. var clone = el.cloneNode(true);
  19256. if (el.parentNode) {
  19257. el.parentNode.insertBefore(clone, el);
  19258. }
  19259. Html5.disposeMediaElement(el);
  19260. el = clone;
  19261. } else {
  19262. el = document.createElement('video'); // determine if native controls should be used
  19263. var tagAttributes = this.options_.tag && getAttributes(this.options_.tag);
  19264. var attributes = mergeOptions$3({}, tagAttributes);
  19265. if (!TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) {
  19266. delete attributes.controls;
  19267. }
  19268. setAttributes(el, assign$1(attributes, {
  19269. id: this.options_.techId,
  19270. "class": 'vjs-tech'
  19271. }));
  19272. }
  19273. el.playerId = this.options_.playerId;
  19274. }
  19275. if (typeof this.options_.preload !== 'undefined') {
  19276. setAttribute(el, 'preload', this.options_.preload);
  19277. }
  19278. if (this.options_.disablePictureInPicture !== undefined) {
  19279. el.disablePictureInPicture = this.options_.disablePictureInPicture;
  19280. } // Update specific tag settings, in case they were overridden
  19281. // `autoplay` has to be *last* so that `muted` and `playsinline` are present
  19282. // when iOS/Safari or other browsers attempt to autoplay.
  19283. var settingsAttrs = ['loop', 'muted', 'playsinline', 'autoplay'];
  19284. for (var i = 0; i < settingsAttrs.length; i++) {
  19285. var attr = settingsAttrs[i];
  19286. var value = this.options_[attr];
  19287. if (typeof value !== 'undefined') {
  19288. if (value) {
  19289. setAttribute(el, attr, attr);
  19290. } else {
  19291. removeAttribute(el, attr);
  19292. }
  19293. el[attr] = value;
  19294. }
  19295. }
  19296. return el;
  19297. }
  19298. /**
  19299. * This will be triggered if the loadstart event has already fired, before videojs was
  19300. * ready. Two known examples of when this can happen are:
  19301. * 1. If we're loading the playback object after it has started loading
  19302. * 2. The media is already playing the (often with autoplay on) then
  19303. *
  19304. * This function will fire another loadstart so that videojs can catchup.
  19305. *
  19306. * @fires Tech#loadstart
  19307. *
  19308. * @return {undefined}
  19309. * returns nothing.
  19310. */
  19311. ;
  19312. _proto.handleLateInit_ = function handleLateInit_(el) {
  19313. if (el.networkState === 0 || el.networkState === 3) {
  19314. // The video element hasn't started loading the source yet
  19315. // or didn't find a source
  19316. return;
  19317. }
  19318. if (el.readyState === 0) {
  19319. // NetworkState is set synchronously BUT loadstart is fired at the
  19320. // end of the current stack, usually before setInterval(fn, 0).
  19321. // So at this point we know loadstart may have already fired or is
  19322. // about to fire, and either way the player hasn't seen it yet.
  19323. // We don't want to fire loadstart prematurely here and cause a
  19324. // double loadstart so we'll wait and see if it happens between now
  19325. // and the next loop, and fire it if not.
  19326. // HOWEVER, we also want to make sure it fires before loadedmetadata
  19327. // which could also happen between now and the next loop, so we'll
  19328. // watch for that also.
  19329. var loadstartFired = false;
  19330. var setLoadstartFired = function setLoadstartFired() {
  19331. loadstartFired = true;
  19332. };
  19333. this.on('loadstart', setLoadstartFired);
  19334. var triggerLoadstart = function triggerLoadstart() {
  19335. // We did miss the original loadstart. Make sure the player
  19336. // sees loadstart before loadedmetadata
  19337. if (!loadstartFired) {
  19338. this.trigger('loadstart');
  19339. }
  19340. };
  19341. this.on('loadedmetadata', triggerLoadstart);
  19342. this.ready(function () {
  19343. this.off('loadstart', setLoadstartFired);
  19344. this.off('loadedmetadata', triggerLoadstart);
  19345. if (!loadstartFired) {
  19346. // We did miss the original native loadstart. Fire it now.
  19347. this.trigger('loadstart');
  19348. }
  19349. });
  19350. return;
  19351. } // From here on we know that loadstart already fired and we missed it.
  19352. // The other readyState events aren't as much of a problem if we double
  19353. // them, so not going to go to as much trouble as loadstart to prevent
  19354. // that unless we find reason to.
  19355. var eventsToTrigger = ['loadstart']; // loadedmetadata: newly equal to HAVE_METADATA (1) or greater
  19356. eventsToTrigger.push('loadedmetadata'); // loadeddata: newly increased to HAVE_CURRENT_DATA (2) or greater
  19357. if (el.readyState >= 2) {
  19358. eventsToTrigger.push('loadeddata');
  19359. } // canplay: newly increased to HAVE_FUTURE_DATA (3) or greater
  19360. if (el.readyState >= 3) {
  19361. eventsToTrigger.push('canplay');
  19362. } // canplaythrough: newly equal to HAVE_ENOUGH_DATA (4)
  19363. if (el.readyState >= 4) {
  19364. eventsToTrigger.push('canplaythrough');
  19365. } // We still need to give the player time to add event listeners
  19366. this.ready(function () {
  19367. eventsToTrigger.forEach(function (type) {
  19368. this.trigger(type);
  19369. }, this);
  19370. });
  19371. }
  19372. /**
  19373. * Set whether we are scrubbing or not.
  19374. * This is used to decide whether we should use `fastSeek` or not.
  19375. * `fastSeek` is used to provide trick play on Safari browsers.
  19376. *
  19377. * @param {boolean} isScrubbing
  19378. * - true for we are currently scrubbing
  19379. * - false for we are no longer scrubbing
  19380. */
  19381. ;
  19382. _proto.setScrubbing = function setScrubbing(isScrubbing) {
  19383. this.isScrubbing_ = isScrubbing;
  19384. }
  19385. /**
  19386. * Get whether we are scrubbing or not.
  19387. *
  19388. * @return {boolean} isScrubbing
  19389. * - true for we are currently scrubbing
  19390. * - false for we are no longer scrubbing
  19391. */
  19392. ;
  19393. _proto.scrubbing = function scrubbing() {
  19394. return this.isScrubbing_;
  19395. }
  19396. /**
  19397. * Set current time for the `HTML5` tech.
  19398. *
  19399. * @param {number} seconds
  19400. * Set the current time of the media to this.
  19401. */
  19402. ;
  19403. _proto.setCurrentTime = function setCurrentTime(seconds) {
  19404. try {
  19405. if (this.isScrubbing_ && this.el_.fastSeek && IS_ANY_SAFARI) {
  19406. this.el_.fastSeek(seconds);
  19407. } else {
  19408. this.el_.currentTime = seconds;
  19409. }
  19410. } catch (e) {
  19411. log$1(e, 'Video is not ready. (Video.js)'); // this.warning(VideoJS.warnings.videoNotReady);
  19412. }
  19413. }
  19414. /**
  19415. * Get the current duration of the HTML5 media element.
  19416. *
  19417. * @return {number}
  19418. * The duration of the media or 0 if there is no duration.
  19419. */
  19420. ;
  19421. _proto.duration = function duration() {
  19422. var _this5 = this;
  19423. // Android Chrome will report duration as Infinity for VOD HLS until after
  19424. // playback has started, which triggers the live display erroneously.
  19425. // Return NaN if playback has not started and trigger a durationupdate once
  19426. // the duration can be reliably known.
  19427. if (this.el_.duration === Infinity && IS_ANDROID && IS_CHROME && this.el_.currentTime === 0) {
  19428. // Wait for the first `timeupdate` with currentTime > 0 - there may be
  19429. // several with 0
  19430. var checkProgress = function checkProgress() {
  19431. if (_this5.el_.currentTime > 0) {
  19432. // Trigger durationchange for genuinely live video
  19433. if (_this5.el_.duration === Infinity) {
  19434. _this5.trigger('durationchange');
  19435. }
  19436. _this5.off('timeupdate', checkProgress);
  19437. }
  19438. };
  19439. this.on('timeupdate', checkProgress);
  19440. return NaN;
  19441. }
  19442. return this.el_.duration || NaN;
  19443. }
  19444. /**
  19445. * Get the current width of the HTML5 media element.
  19446. *
  19447. * @return {number}
  19448. * The width of the HTML5 media element.
  19449. */
  19450. ;
  19451. _proto.width = function width() {
  19452. return this.el_.offsetWidth;
  19453. }
  19454. /**
  19455. * Get the current height of the HTML5 media element.
  19456. *
  19457. * @return {number}
  19458. * The height of the HTML5 media element.
  19459. */
  19460. ;
  19461. _proto.height = function height() {
  19462. return this.el_.offsetHeight;
  19463. }
  19464. /**
  19465. * Proxy iOS `webkitbeginfullscreen` and `webkitendfullscreen` into
  19466. * `fullscreenchange` event.
  19467. *
  19468. * @private
  19469. * @fires fullscreenchange
  19470. * @listens webkitendfullscreen
  19471. * @listens webkitbeginfullscreen
  19472. * @listens webkitbeginfullscreen
  19473. */
  19474. ;
  19475. _proto.proxyWebkitFullscreen_ = function proxyWebkitFullscreen_() {
  19476. var _this6 = this;
  19477. if (!('webkitDisplayingFullscreen' in this.el_)) {
  19478. return;
  19479. }
  19480. var endFn = function endFn() {
  19481. this.trigger('fullscreenchange', {
  19482. isFullscreen: false
  19483. }); // Safari will sometimes set contols on the videoelement when existing fullscreen.
  19484. if (this.el_.controls && !this.options_.nativeControlsForTouch && this.controls()) {
  19485. this.el_.controls = false;
  19486. }
  19487. };
  19488. var beginFn = function beginFn() {
  19489. if ('webkitPresentationMode' in this.el_ && this.el_.webkitPresentationMode !== 'picture-in-picture') {
  19490. this.one('webkitendfullscreen', endFn);
  19491. this.trigger('fullscreenchange', {
  19492. isFullscreen: true,
  19493. // set a flag in case another tech triggers fullscreenchange
  19494. nativeIOSFullscreen: true
  19495. });
  19496. }
  19497. };
  19498. this.on('webkitbeginfullscreen', beginFn);
  19499. this.on('dispose', function () {
  19500. _this6.off('webkitbeginfullscreen', beginFn);
  19501. _this6.off('webkitendfullscreen', endFn);
  19502. });
  19503. }
  19504. /**
  19505. * Check if fullscreen is supported on the current playback device.
  19506. *
  19507. * @return {boolean}
  19508. * - True if fullscreen is supported.
  19509. * - False if fullscreen is not supported.
  19510. */
  19511. ;
  19512. _proto.supportsFullScreen = function supportsFullScreen() {
  19513. if (typeof this.el_.webkitEnterFullScreen === 'function') {
  19514. var userAgent = window.navigator && window.navigator.userAgent || ''; // Seems to be broken in Chromium/Chrome && Safari in Leopard
  19515. if (/Android/.test(userAgent) || !/Chrome|Mac OS X 10.5/.test(userAgent)) {
  19516. return true;
  19517. }
  19518. }
  19519. return false;
  19520. }
  19521. /**
  19522. * Request that the `HTML5` Tech enter fullscreen.
  19523. */
  19524. ;
  19525. _proto.enterFullScreen = function enterFullScreen() {
  19526. var video = this.el_;
  19527. if (video.paused && video.networkState <= video.HAVE_METADATA) {
  19528. // attempt to prime the video element for programmatic access
  19529. // this isn't necessary on the desktop but shouldn't hurt
  19530. silencePromise(this.el_.play()); // playing and pausing synchronously during the transition to fullscreen
  19531. // can get iOS ~6.1 devices into a play/pause loop
  19532. this.setTimeout(function () {
  19533. video.pause();
  19534. try {
  19535. video.webkitEnterFullScreen();
  19536. } catch (e) {
  19537. this.trigger('fullscreenerror', e);
  19538. }
  19539. }, 0);
  19540. } else {
  19541. try {
  19542. video.webkitEnterFullScreen();
  19543. } catch (e) {
  19544. this.trigger('fullscreenerror', e);
  19545. }
  19546. }
  19547. }
  19548. /**
  19549. * Request that the `HTML5` Tech exit fullscreen.
  19550. */
  19551. ;
  19552. _proto.exitFullScreen = function exitFullScreen() {
  19553. if (!this.el_.webkitDisplayingFullscreen) {
  19554. this.trigger('fullscreenerror', new Error('The video is not fullscreen'));
  19555. return;
  19556. }
  19557. this.el_.webkitExitFullScreen();
  19558. }
  19559. /**
  19560. * Create a floating video window always on top of other windows so that users may
  19561. * continue consuming media while they interact with other content sites, or
  19562. * applications on their device.
  19563. *
  19564. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  19565. *
  19566. * @return {Promise}
  19567. * A promise with a Picture-in-Picture window.
  19568. */
  19569. ;
  19570. _proto.requestPictureInPicture = function requestPictureInPicture() {
  19571. return this.el_.requestPictureInPicture();
  19572. }
  19573. /**
  19574. * Native requestVideoFrameCallback if supported by browser/tech, or fallback
  19575. * Don't use rVCF on Safari when DRM is playing, as it doesn't fire
  19576. * Needs to be checked later than the constructor
  19577. * This will be a false positive for clear sources loaded after a Fairplay source
  19578. *
  19579. * @param {function} cb function to call
  19580. * @return {number} id of request
  19581. */
  19582. ;
  19583. _proto.requestVideoFrameCallback = function requestVideoFrameCallback(cb) {
  19584. if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
  19585. return this.el_.requestVideoFrameCallback(cb);
  19586. }
  19587. return _Tech.prototype.requestVideoFrameCallback.call(this, cb);
  19588. }
  19589. /**
  19590. * Native or fallback requestVideoFrameCallback
  19591. *
  19592. * @param {number} id request id to cancel
  19593. */
  19594. ;
  19595. _proto.cancelVideoFrameCallback = function cancelVideoFrameCallback(id) {
  19596. if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
  19597. this.el_.cancelVideoFrameCallback(id);
  19598. } else {
  19599. _Tech.prototype.cancelVideoFrameCallback.call(this, id);
  19600. }
  19601. }
  19602. /**
  19603. * A getter/setter for the `Html5` Tech's source object.
  19604. * > Note: Please use {@link Html5#setSource}
  19605. *
  19606. * @param {Tech~SourceObject} [src]
  19607. * The source object you want to set on the `HTML5` techs element.
  19608. *
  19609. * @return {Tech~SourceObject|undefined}
  19610. * - The current source object when a source is not passed in.
  19611. * - undefined when setting
  19612. *
  19613. * @deprecated Since version 5.
  19614. */
  19615. ;
  19616. _proto.src = function src(_src) {
  19617. if (_src === undefined) {
  19618. return this.el_.src;
  19619. } // Setting src through `src` instead of `setSrc` will be deprecated
  19620. this.setSrc(_src);
  19621. }
  19622. /**
  19623. * Reset the tech by removing all sources and then calling
  19624. * {@link Html5.resetMediaElement}.
  19625. */
  19626. ;
  19627. _proto.reset = function reset() {
  19628. Html5.resetMediaElement(this.el_);
  19629. }
  19630. /**
  19631. * Get the current source on the `HTML5` Tech. Falls back to returning the source from
  19632. * the HTML5 media element.
  19633. *
  19634. * @return {Tech~SourceObject}
  19635. * The current source object from the HTML5 tech. With a fallback to the
  19636. * elements source.
  19637. */
  19638. ;
  19639. _proto.currentSrc = function currentSrc() {
  19640. if (this.currentSource_) {
  19641. return this.currentSource_.src;
  19642. }
  19643. return this.el_.currentSrc;
  19644. }
  19645. /**
  19646. * Set controls attribute for the HTML5 media Element.
  19647. *
  19648. * @param {string} val
  19649. * Value to set the controls attribute to
  19650. */
  19651. ;
  19652. _proto.setControls = function setControls(val) {
  19653. this.el_.controls = !!val;
  19654. }
  19655. /**
  19656. * Create and returns a remote {@link TextTrack} object.
  19657. *
  19658. * @param {string} kind
  19659. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  19660. *
  19661. * @param {string} [label]
  19662. * Label to identify the text track
  19663. *
  19664. * @param {string} [language]
  19665. * Two letter language abbreviation
  19666. *
  19667. * @return {TextTrack}
  19668. * The TextTrack that gets created.
  19669. */
  19670. ;
  19671. _proto.addTextTrack = function addTextTrack(kind, label, language) {
  19672. if (!this.featuresNativeTextTracks) {
  19673. return _Tech.prototype.addTextTrack.call(this, kind, label, language);
  19674. }
  19675. return this.el_.addTextTrack(kind, label, language);
  19676. }
  19677. /**
  19678. * Creates either native TextTrack or an emulated TextTrack depending
  19679. * on the value of `featuresNativeTextTracks`
  19680. *
  19681. * @param {Object} options
  19682. * The object should contain the options to initialize the TextTrack with.
  19683. *
  19684. * @param {string} [options.kind]
  19685. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
  19686. *
  19687. * @param {string} [options.label]
  19688. * Label to identify the text track
  19689. *
  19690. * @param {string} [options.language]
  19691. * Two letter language abbreviation.
  19692. *
  19693. * @param {boolean} [options.default]
  19694. * Default this track to on.
  19695. *
  19696. * @param {string} [options.id]
  19697. * The internal id to assign this track.
  19698. *
  19699. * @param {string} [options.src]
  19700. * A source url for the track.
  19701. *
  19702. * @return {HTMLTrackElement}
  19703. * The track element that gets created.
  19704. */
  19705. ;
  19706. _proto.createRemoteTextTrack = function createRemoteTextTrack(options) {
  19707. if (!this.featuresNativeTextTracks) {
  19708. return _Tech.prototype.createRemoteTextTrack.call(this, options);
  19709. }
  19710. var htmlTrackElement = document.createElement('track');
  19711. if (options.kind) {
  19712. htmlTrackElement.kind = options.kind;
  19713. }
  19714. if (options.label) {
  19715. htmlTrackElement.label = options.label;
  19716. }
  19717. if (options.language || options.srclang) {
  19718. htmlTrackElement.srclang = options.language || options.srclang;
  19719. }
  19720. if (options["default"]) {
  19721. htmlTrackElement["default"] = options["default"];
  19722. }
  19723. if (options.id) {
  19724. htmlTrackElement.id = options.id;
  19725. }
  19726. if (options.src) {
  19727. htmlTrackElement.src = options.src;
  19728. }
  19729. return htmlTrackElement;
  19730. }
  19731. /**
  19732. * Creates a remote text track object and returns an html track element.
  19733. *
  19734. * @param {Object} options The object should contain values for
  19735. * kind, language, label, and src (location of the WebVTT file)
  19736. * @param {boolean} [manualCleanup=true] if set to false, the TextTrack will be
  19737. * automatically removed from the video element whenever the source changes
  19738. * @return {HTMLTrackElement} An Html Track Element.
  19739. * This can be an emulated {@link HTMLTrackElement} or a native one.
  19740. * @deprecated The default value of the "manualCleanup" parameter will default
  19741. * to "false" in upcoming versions of Video.js
  19742. */
  19743. ;
  19744. _proto.addRemoteTextTrack = function addRemoteTextTrack(options, manualCleanup) {
  19745. var htmlTrackElement = _Tech.prototype.addRemoteTextTrack.call(this, options, manualCleanup);
  19746. if (this.featuresNativeTextTracks) {
  19747. this.el().appendChild(htmlTrackElement);
  19748. }
  19749. return htmlTrackElement;
  19750. }
  19751. /**
  19752. * Remove remote `TextTrack` from `TextTrackList` object
  19753. *
  19754. * @param {TextTrack} track
  19755. * `TextTrack` object to remove
  19756. */
  19757. ;
  19758. _proto.removeRemoteTextTrack = function removeRemoteTextTrack(track) {
  19759. _Tech.prototype.removeRemoteTextTrack.call(this, track);
  19760. if (this.featuresNativeTextTracks) {
  19761. var tracks = this.$$('track');
  19762. var i = tracks.length;
  19763. while (i--) {
  19764. if (track === tracks[i] || track === tracks[i].track) {
  19765. this.el().removeChild(tracks[i]);
  19766. }
  19767. }
  19768. }
  19769. }
  19770. /**
  19771. * Gets available media playback quality metrics as specified by the W3C's Media
  19772. * Playback Quality API.
  19773. *
  19774. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  19775. *
  19776. * @return {Object}
  19777. * An object with supported media playback quality metrics
  19778. */
  19779. ;
  19780. _proto.getVideoPlaybackQuality = function getVideoPlaybackQuality() {
  19781. if (typeof this.el().getVideoPlaybackQuality === 'function') {
  19782. return this.el().getVideoPlaybackQuality();
  19783. }
  19784. var videoPlaybackQuality = {};
  19785. if (typeof this.el().webkitDroppedFrameCount !== 'undefined' && typeof this.el().webkitDecodedFrameCount !== 'undefined') {
  19786. videoPlaybackQuality.droppedVideoFrames = this.el().webkitDroppedFrameCount;
  19787. videoPlaybackQuality.totalVideoFrames = this.el().webkitDecodedFrameCount;
  19788. }
  19789. if (window.performance && typeof window.performance.now === 'function') {
  19790. videoPlaybackQuality.creationTime = window.performance.now();
  19791. } else if (window.performance && window.performance.timing && typeof window.performance.timing.navigationStart === 'number') {
  19792. videoPlaybackQuality.creationTime = window.Date.now() - window.performance.timing.navigationStart;
  19793. }
  19794. return videoPlaybackQuality;
  19795. };
  19796. return Html5;
  19797. }(Tech);
  19798. /* HTML5 Support Testing ---------------------------------------------------- */
  19799. /**
  19800. * Element for testing browser HTML5 media capabilities
  19801. *
  19802. * @type {Element}
  19803. * @constant
  19804. * @private
  19805. */
  19806. defineLazyProperty(Html5, 'TEST_VID', function () {
  19807. if (!isReal()) {
  19808. return;
  19809. }
  19810. var video = document.createElement('video');
  19811. var track = document.createElement('track');
  19812. track.kind = 'captions';
  19813. track.srclang = 'en';
  19814. track.label = 'English';
  19815. video.appendChild(track);
  19816. return video;
  19817. });
  19818. /**
  19819. * Check if HTML5 media is supported by this browser/device.
  19820. *
  19821. * @return {boolean}
  19822. * - True if HTML5 media is supported.
  19823. * - False if HTML5 media is not supported.
  19824. */
  19825. Html5.isSupported = function () {
  19826. // IE with no Media Player is a LIAR! (#984)
  19827. try {
  19828. Html5.TEST_VID.volume = 0.5;
  19829. } catch (e) {
  19830. return false;
  19831. }
  19832. return !!(Html5.TEST_VID && Html5.TEST_VID.canPlayType);
  19833. };
  19834. /**
  19835. * Check if the tech can support the given type
  19836. *
  19837. * @param {string} type
  19838. * The mimetype to check
  19839. * @return {string} 'probably', 'maybe', or '' (empty string)
  19840. */
  19841. Html5.canPlayType = function (type) {
  19842. return Html5.TEST_VID.canPlayType(type);
  19843. };
  19844. /**
  19845. * Check if the tech can support the given source
  19846. *
  19847. * @param {Object} srcObj
  19848. * The source object
  19849. * @param {Object} options
  19850. * The options passed to the tech
  19851. * @return {string} 'probably', 'maybe', or '' (empty string)
  19852. */
  19853. Html5.canPlaySource = function (srcObj, options) {
  19854. return Html5.canPlayType(srcObj.type);
  19855. };
  19856. /**
  19857. * Check if the volume can be changed in this browser/device.
  19858. * Volume cannot be changed in a lot of mobile devices.
  19859. * Specifically, it can't be changed from 1 on iOS.
  19860. *
  19861. * @return {boolean}
  19862. * - True if volume can be controlled
  19863. * - False otherwise
  19864. */
  19865. Html5.canControlVolume = function () {
  19866. // IE will error if Windows Media Player not installed #3315
  19867. try {
  19868. var volume = Html5.TEST_VID.volume;
  19869. Html5.TEST_VID.volume = volume / 2 + 0.1;
  19870. var canControl = volume !== Html5.TEST_VID.volume; // With the introduction of iOS 15, there are cases where the volume is read as
  19871. // changed but reverts back to its original state at the start of the next tick.
  19872. // To determine whether volume can be controlled on iOS,
  19873. // a timeout is set and the volume is checked asynchronously.
  19874. // Since `features` doesn't currently work asynchronously, the value is manually set.
  19875. if (canControl && IS_IOS) {
  19876. window.setTimeout(function () {
  19877. if (Html5 && Html5.prototype) {
  19878. Html5.prototype.featuresVolumeControl = volume !== Html5.TEST_VID.volume;
  19879. }
  19880. }); // default iOS to false, which will be updated in the timeout above.
  19881. return false;
  19882. }
  19883. return canControl;
  19884. } catch (e) {
  19885. return false;
  19886. }
  19887. };
  19888. /**
  19889. * Check if the volume can be muted in this browser/device.
  19890. * Some devices, e.g. iOS, don't allow changing volume
  19891. * but permits muting/unmuting.
  19892. *
  19893. * @return {bolean}
  19894. * - True if volume can be muted
  19895. * - False otherwise
  19896. */
  19897. Html5.canMuteVolume = function () {
  19898. try {
  19899. var muted = Html5.TEST_VID.muted; // in some versions of iOS muted property doesn't always
  19900. // work, so we want to set both property and attribute
  19901. Html5.TEST_VID.muted = !muted;
  19902. if (Html5.TEST_VID.muted) {
  19903. setAttribute(Html5.TEST_VID, 'muted', 'muted');
  19904. } else {
  19905. removeAttribute(Html5.TEST_VID, 'muted', 'muted');
  19906. }
  19907. return muted !== Html5.TEST_VID.muted;
  19908. } catch (e) {
  19909. return false;
  19910. }
  19911. };
  19912. /**
  19913. * Check if the playback rate can be changed in this browser/device.
  19914. *
  19915. * @return {boolean}
  19916. * - True if playback rate can be controlled
  19917. * - False otherwise
  19918. */
  19919. Html5.canControlPlaybackRate = function () {
  19920. // Playback rate API is implemented in Android Chrome, but doesn't do anything
  19921. // https://github.com/videojs/video.js/issues/3180
  19922. if (IS_ANDROID && IS_CHROME && CHROME_VERSION < 58) {
  19923. return false;
  19924. } // IE will error if Windows Media Player not installed #3315
  19925. try {
  19926. var playbackRate = Html5.TEST_VID.playbackRate;
  19927. Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1;
  19928. return playbackRate !== Html5.TEST_VID.playbackRate;
  19929. } catch (e) {
  19930. return false;
  19931. }
  19932. };
  19933. /**
  19934. * Check if we can override a video/audio elements attributes, with
  19935. * Object.defineProperty.
  19936. *
  19937. * @return {boolean}
  19938. * - True if builtin attributes can be overridden
  19939. * - False otherwise
  19940. */
  19941. Html5.canOverrideAttributes = function () {
  19942. // if we cannot overwrite the src/innerHTML property, there is no support
  19943. // iOS 7 safari for instance cannot do this.
  19944. try {
  19945. var noop = function noop() {};
  19946. Object.defineProperty(document.createElement('video'), 'src', {
  19947. get: noop,
  19948. set: noop
  19949. });
  19950. Object.defineProperty(document.createElement('audio'), 'src', {
  19951. get: noop,
  19952. set: noop
  19953. });
  19954. Object.defineProperty(document.createElement('video'), 'innerHTML', {
  19955. get: noop,
  19956. set: noop
  19957. });
  19958. Object.defineProperty(document.createElement('audio'), 'innerHTML', {
  19959. get: noop,
  19960. set: noop
  19961. });
  19962. } catch (e) {
  19963. return false;
  19964. }
  19965. return true;
  19966. };
  19967. /**
  19968. * Check to see if native `TextTrack`s are supported by this browser/device.
  19969. *
  19970. * @return {boolean}
  19971. * - True if native `TextTrack`s are supported.
  19972. * - False otherwise
  19973. */
  19974. Html5.supportsNativeTextTracks = function () {
  19975. return IS_ANY_SAFARI || IS_IOS && IS_CHROME;
  19976. };
  19977. /**
  19978. * Check to see if native `VideoTrack`s are supported by this browser/device
  19979. *
  19980. * @return {boolean}
  19981. * - True if native `VideoTrack`s are supported.
  19982. * - False otherwise
  19983. */
  19984. Html5.supportsNativeVideoTracks = function () {
  19985. return !!(Html5.TEST_VID && Html5.TEST_VID.videoTracks);
  19986. };
  19987. /**
  19988. * Check to see if native `AudioTrack`s are supported by this browser/device
  19989. *
  19990. * @return {boolean}
  19991. * - True if native `AudioTrack`s are supported.
  19992. * - False otherwise
  19993. */
  19994. Html5.supportsNativeAudioTracks = function () {
  19995. return !!(Html5.TEST_VID && Html5.TEST_VID.audioTracks);
  19996. };
  19997. /**
  19998. * An array of events available on the Html5 tech.
  19999. *
  20000. * @private
  20001. * @type {Array}
  20002. */
  20003. Html5.Events = ['loadstart', 'suspend', 'abort', 'error', 'emptied', 'stalled', 'loadedmetadata', 'loadeddata', 'canplay', 'canplaythrough', 'playing', 'waiting', 'seeking', 'seeked', 'ended', 'durationchange', 'timeupdate', 'progress', 'play', 'pause', 'ratechange', 'resize', 'volumechange'];
  20004. /**
  20005. * Boolean indicating whether the `Tech` supports volume control.
  20006. *
  20007. * @type {boolean}
  20008. * @default {@link Html5.canControlVolume}
  20009. */
  20010. /**
  20011. * Boolean indicating whether the `Tech` supports muting volume.
  20012. *
  20013. * @type {bolean}
  20014. * @default {@link Html5.canMuteVolume}
  20015. */
  20016. /**
  20017. * Boolean indicating whether the `Tech` supports changing the speed at which the media
  20018. * plays. Examples:
  20019. * - Set player to play 2x (twice) as fast
  20020. * - Set player to play 0.5x (half) as fast
  20021. *
  20022. * @type {boolean}
  20023. * @default {@link Html5.canControlPlaybackRate}
  20024. */
  20025. /**
  20026. * Boolean indicating whether the `Tech` supports the `sourceset` event.
  20027. *
  20028. * @type {boolean}
  20029. * @default
  20030. */
  20031. /**
  20032. * Boolean indicating whether the `HTML5` tech currently supports native `TextTrack`s.
  20033. *
  20034. * @type {boolean}
  20035. * @default {@link Html5.supportsNativeTextTracks}
  20036. */
  20037. /**
  20038. * Boolean indicating whether the `HTML5` tech currently supports native `VideoTrack`s.
  20039. *
  20040. * @type {boolean}
  20041. * @default {@link Html5.supportsNativeVideoTracks}
  20042. */
  20043. /**
  20044. * Boolean indicating whether the `HTML5` tech currently supports native `AudioTrack`s.
  20045. *
  20046. * @type {boolean}
  20047. * @default {@link Html5.supportsNativeAudioTracks}
  20048. */
  20049. [['featuresMuteControl', 'canMuteVolume'], ['featuresPlaybackRate', 'canControlPlaybackRate'], ['featuresSourceset', 'canOverrideAttributes'], ['featuresNativeTextTracks', 'supportsNativeTextTracks'], ['featuresNativeVideoTracks', 'supportsNativeVideoTracks'], ['featuresNativeAudioTracks', 'supportsNativeAudioTracks']].forEach(function (_ref) {
  20050. var key = _ref[0],
  20051. fn = _ref[1];
  20052. defineLazyProperty(Html5.prototype, key, function () {
  20053. return Html5[fn]();
  20054. }, true);
  20055. });
  20056. Html5.prototype.featuresVolumeControl = Html5.canControlVolume();
  20057. /**
  20058. * Boolean indicating whether the `HTML5` tech currently supports the media element
  20059. * moving in the DOM. iOS breaks if you move the media element, so this is set this to
  20060. * false there. Everywhere else this should be true.
  20061. *
  20062. * @type {boolean}
  20063. * @default
  20064. */
  20065. Html5.prototype.movingMediaElementInDOM = !IS_IOS; // TODO: Previous comment: No longer appears to be used. Can probably be removed.
  20066. // Is this true?
  20067. /**
  20068. * Boolean indicating whether the `HTML5` tech currently supports automatic media resize
  20069. * when going into fullscreen.
  20070. *
  20071. * @type {boolean}
  20072. * @default
  20073. */
  20074. Html5.prototype.featuresFullscreenResize = true;
  20075. /**
  20076. * Boolean indicating whether the `HTML5` tech currently supports the progress event.
  20077. * If this is false, manual `progress` events will be triggered instead.
  20078. *
  20079. * @type {boolean}
  20080. * @default
  20081. */
  20082. Html5.prototype.featuresProgressEvents = true;
  20083. /**
  20084. * Boolean indicating whether the `HTML5` tech currently supports the timeupdate event.
  20085. * If this is false, manual `timeupdate` events will be triggered instead.
  20086. *
  20087. * @default
  20088. */
  20089. Html5.prototype.featuresTimeupdateEvents = true;
  20090. /**
  20091. * Whether the HTML5 el supports `requestVideoFrameCallback`
  20092. *
  20093. * @type {boolean}
  20094. */
  20095. Html5.prototype.featuresVideoFrameCallback = !!(Html5.TEST_VID && Html5.TEST_VID.requestVideoFrameCallback); // HTML5 Feature detection and Device Fixes --------------------------------- //
  20096. var canPlayType;
  20097. Html5.patchCanPlayType = function () {
  20098. // Android 4.0 and above can play HLS to some extent but it reports being unable to do so
  20099. // Firefox and Chrome report correctly
  20100. if (ANDROID_VERSION >= 4.0 && !IS_FIREFOX && !IS_CHROME) {
  20101. canPlayType = Html5.TEST_VID && Html5.TEST_VID.constructor.prototype.canPlayType;
  20102. Html5.TEST_VID.constructor.prototype.canPlayType = function (type) {
  20103. var mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i;
  20104. if (type && mpegurlRE.test(type)) {
  20105. return 'maybe';
  20106. }
  20107. return canPlayType.call(this, type);
  20108. };
  20109. }
  20110. };
  20111. Html5.unpatchCanPlayType = function () {
  20112. var r = Html5.TEST_VID.constructor.prototype.canPlayType;
  20113. if (canPlayType) {
  20114. Html5.TEST_VID.constructor.prototype.canPlayType = canPlayType;
  20115. }
  20116. return r;
  20117. }; // by default, patch the media element
  20118. Html5.patchCanPlayType();
  20119. Html5.disposeMediaElement = function (el) {
  20120. if (!el) {
  20121. return;
  20122. }
  20123. if (el.parentNode) {
  20124. el.parentNode.removeChild(el);
  20125. } // remove any child track or source nodes to prevent their loading
  20126. while (el.hasChildNodes()) {
  20127. el.removeChild(el.firstChild);
  20128. } // remove any src reference. not setting `src=''` because that causes a warning
  20129. // in firefox
  20130. el.removeAttribute('src'); // force the media element to update its loading state by calling load()
  20131. // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793)
  20132. if (typeof el.load === 'function') {
  20133. // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
  20134. (function () {
  20135. try {
  20136. el.load();
  20137. } catch (e) {// not supported
  20138. }
  20139. })();
  20140. }
  20141. };
  20142. Html5.resetMediaElement = function (el) {
  20143. if (!el) {
  20144. return;
  20145. }
  20146. var sources = el.querySelectorAll('source');
  20147. var i = sources.length;
  20148. while (i--) {
  20149. el.removeChild(sources[i]);
  20150. } // remove any src reference.
  20151. // not setting `src=''` because that throws an error
  20152. el.removeAttribute('src');
  20153. if (typeof el.load === 'function') {
  20154. // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
  20155. (function () {
  20156. try {
  20157. el.load();
  20158. } catch (e) {// satisfy linter
  20159. }
  20160. })();
  20161. }
  20162. };
  20163. /* Native HTML5 element property wrapping ----------------------------------- */
  20164. // Wrap native boolean attributes with getters that check both property and attribute
  20165. // The list is as followed:
  20166. // muted, defaultMuted, autoplay, controls, loop, playsinline
  20167. [
  20168. /**
  20169. * Get the value of `muted` from the media element. `muted` indicates
  20170. * that the volume for the media should be set to silent. This does not actually change
  20171. * the `volume` attribute.
  20172. *
  20173. * @method Html5#muted
  20174. * @return {boolean}
  20175. * - True if the value of `volume` should be ignored and the audio set to silent.
  20176. * - False if the value of `volume` should be used.
  20177. *
  20178. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
  20179. */
  20180. 'muted',
  20181. /**
  20182. * Get the value of `defaultMuted` from the media element. `defaultMuted` indicates
  20183. * whether the media should start muted or not. Only changes the default state of the
  20184. * media. `muted` and `defaultMuted` can have different values. {@link Html5#muted} indicates the
  20185. * current state.
  20186. *
  20187. * @method Html5#defaultMuted
  20188. * @return {boolean}
  20189. * - The value of `defaultMuted` from the media element.
  20190. * - True indicates that the media should start muted.
  20191. * - False indicates that the media should not start muted
  20192. *
  20193. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
  20194. */
  20195. 'defaultMuted',
  20196. /**
  20197. * Get the value of `autoplay` from the media element. `autoplay` indicates
  20198. * that the media should start to play as soon as the page is ready.
  20199. *
  20200. * @method Html5#autoplay
  20201. * @return {boolean}
  20202. * - The value of `autoplay` from the media element.
  20203. * - True indicates that the media should start as soon as the page loads.
  20204. * - False indicates that the media should not start as soon as the page loads.
  20205. *
  20206. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
  20207. */
  20208. 'autoplay',
  20209. /**
  20210. * Get the value of `controls` from the media element. `controls` indicates
  20211. * whether the native media controls should be shown or hidden.
  20212. *
  20213. * @method Html5#controls
  20214. * @return {boolean}
  20215. * - The value of `controls` from the media element.
  20216. * - True indicates that native controls should be showing.
  20217. * - False indicates that native controls should be hidden.
  20218. *
  20219. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-controls}
  20220. */
  20221. 'controls',
  20222. /**
  20223. * Get the value of `loop` from the media element. `loop` indicates
  20224. * that the media should return to the start of the media and continue playing once
  20225. * it reaches the end.
  20226. *
  20227. * @method Html5#loop
  20228. * @return {boolean}
  20229. * - The value of `loop` from the media element.
  20230. * - True indicates that playback should seek back to start once
  20231. * the end of a media is reached.
  20232. * - False indicates that playback should not loop back to the start when the
  20233. * end of the media is reached.
  20234. *
  20235. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
  20236. */
  20237. 'loop',
  20238. /**
  20239. * Get the value of `playsinline` from the media element. `playsinline` indicates
  20240. * to the browser that non-fullscreen playback is preferred when fullscreen
  20241. * playback is the native default, such as in iOS Safari.
  20242. *
  20243. * @method Html5#playsinline
  20244. * @return {boolean}
  20245. * - The value of `playsinline` from the media element.
  20246. * - True indicates that the media should play inline.
  20247. * - False indicates that the media should not play inline.
  20248. *
  20249. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  20250. */
  20251. 'playsinline'].forEach(function (prop) {
  20252. Html5.prototype[prop] = function () {
  20253. return this.el_[prop] || this.el_.hasAttribute(prop);
  20254. };
  20255. }); // Wrap native boolean attributes with setters that set both property and attribute
  20256. // The list is as followed:
  20257. // setMuted, setDefaultMuted, setAutoplay, setLoop, setPlaysinline
  20258. // setControls is special-cased above
  20259. [
  20260. /**
  20261. * Set the value of `muted` on the media element. `muted` indicates that the current
  20262. * audio level should be silent.
  20263. *
  20264. * @method Html5#setMuted
  20265. * @param {boolean} muted
  20266. * - True if the audio should be set to silent
  20267. * - False otherwise
  20268. *
  20269. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
  20270. */
  20271. 'muted',
  20272. /**
  20273. * Set the value of `defaultMuted` on the media element. `defaultMuted` indicates that the current
  20274. * audio level should be silent, but will only effect the muted level on initial playback..
  20275. *
  20276. * @method Html5.prototype.setDefaultMuted
  20277. * @param {boolean} defaultMuted
  20278. * - True if the audio should be set to silent
  20279. * - False otherwise
  20280. *
  20281. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
  20282. */
  20283. 'defaultMuted',
  20284. /**
  20285. * Set the value of `autoplay` on the media element. `autoplay` indicates
  20286. * that the media should start to play as soon as the page is ready.
  20287. *
  20288. * @method Html5#setAutoplay
  20289. * @param {boolean} autoplay
  20290. * - True indicates that the media should start as soon as the page loads.
  20291. * - False indicates that the media should not start as soon as the page loads.
  20292. *
  20293. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
  20294. */
  20295. 'autoplay',
  20296. /**
  20297. * Set the value of `loop` on the media element. `loop` indicates
  20298. * that the media should return to the start of the media and continue playing once
  20299. * it reaches the end.
  20300. *
  20301. * @method Html5#setLoop
  20302. * @param {boolean} loop
  20303. * - True indicates that playback should seek back to start once
  20304. * the end of a media is reached.
  20305. * - False indicates that playback should not loop back to the start when the
  20306. * end of the media is reached.
  20307. *
  20308. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
  20309. */
  20310. 'loop',
  20311. /**
  20312. * Set the value of `playsinline` from the media element. `playsinline` indicates
  20313. * to the browser that non-fullscreen playback is preferred when fullscreen
  20314. * playback is the native default, such as in iOS Safari.
  20315. *
  20316. * @method Html5#setPlaysinline
  20317. * @param {boolean} playsinline
  20318. * - True indicates that the media should play inline.
  20319. * - False indicates that the media should not play inline.
  20320. *
  20321. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  20322. */
  20323. 'playsinline'].forEach(function (prop) {
  20324. Html5.prototype['set' + toTitleCase$1(prop)] = function (v) {
  20325. this.el_[prop] = v;
  20326. if (v) {
  20327. this.el_.setAttribute(prop, prop);
  20328. } else {
  20329. this.el_.removeAttribute(prop);
  20330. }
  20331. };
  20332. }); // Wrap native properties with a getter
  20333. // The list is as followed
  20334. // paused, currentTime, buffered, volume, poster, preload, error, seeking
  20335. // seekable, ended, playbackRate, defaultPlaybackRate, disablePictureInPicture
  20336. // played, networkState, readyState, videoWidth, videoHeight, crossOrigin
  20337. [
  20338. /**
  20339. * Get the value of `paused` from the media element. `paused` indicates whether the media element
  20340. * is currently paused or not.
  20341. *
  20342. * @method Html5#paused
  20343. * @return {boolean}
  20344. * The value of `paused` from the media element.
  20345. *
  20346. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-paused}
  20347. */
  20348. 'paused',
  20349. /**
  20350. * Get the value of `currentTime` from the media element. `currentTime` indicates
  20351. * the current second that the media is at in playback.
  20352. *
  20353. * @method Html5#currentTime
  20354. * @return {number}
  20355. * The value of `currentTime` from the media element.
  20356. *
  20357. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-currenttime}
  20358. */
  20359. 'currentTime',
  20360. /**
  20361. * Get the value of `buffered` from the media element. `buffered` is a `TimeRange`
  20362. * object that represents the parts of the media that are already downloaded and
  20363. * available for playback.
  20364. *
  20365. * @method Html5#buffered
  20366. * @return {TimeRange}
  20367. * The value of `buffered` from the media element.
  20368. *
  20369. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-buffered}
  20370. */
  20371. 'buffered',
  20372. /**
  20373. * Get the value of `volume` from the media element. `volume` indicates
  20374. * the current playback volume of audio for a media. `volume` will be a value from 0
  20375. * (silent) to 1 (loudest and default).
  20376. *
  20377. * @method Html5#volume
  20378. * @return {number}
  20379. * The value of `volume` from the media element. Value will be between 0-1.
  20380. *
  20381. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
  20382. */
  20383. 'volume',
  20384. /**
  20385. * Get the value of `poster` from the media element. `poster` indicates
  20386. * that the url of an image file that can/will be shown when no media data is available.
  20387. *
  20388. * @method Html5#poster
  20389. * @return {string}
  20390. * The value of `poster` from the media element. Value will be a url to an
  20391. * image.
  20392. *
  20393. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-video-poster}
  20394. */
  20395. 'poster',
  20396. /**
  20397. * Get the value of `preload` from the media element. `preload` indicates
  20398. * what should download before the media is interacted with. It can have the following
  20399. * values:
  20400. * - none: nothing should be downloaded
  20401. * - metadata: poster and the first few frames of the media may be downloaded to get
  20402. * media dimensions and other metadata
  20403. * - auto: allow the media and metadata for the media to be downloaded before
  20404. * interaction
  20405. *
  20406. * @method Html5#preload
  20407. * @return {string}
  20408. * The value of `preload` from the media element. Will be 'none', 'metadata',
  20409. * or 'auto'.
  20410. *
  20411. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
  20412. */
  20413. 'preload',
  20414. /**
  20415. * Get the value of the `error` from the media element. `error` indicates any
  20416. * MediaError that may have occurred during playback. If error returns null there is no
  20417. * current error.
  20418. *
  20419. * @method Html5#error
  20420. * @return {MediaError|null}
  20421. * The value of `error` from the media element. Will be `MediaError` if there
  20422. * is a current error and null otherwise.
  20423. *
  20424. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-error}
  20425. */
  20426. 'error',
  20427. /**
  20428. * Get the value of `seeking` from the media element. `seeking` indicates whether the
  20429. * media is currently seeking to a new position or not.
  20430. *
  20431. * @method Html5#seeking
  20432. * @return {boolean}
  20433. * - The value of `seeking` from the media element.
  20434. * - True indicates that the media is currently seeking to a new position.
  20435. * - False indicates that the media is not seeking to a new position at this time.
  20436. *
  20437. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seeking}
  20438. */
  20439. 'seeking',
  20440. /**
  20441. * Get the value of `seekable` from the media element. `seekable` returns a
  20442. * `TimeRange` object indicating ranges of time that can currently be `seeked` to.
  20443. *
  20444. * @method Html5#seekable
  20445. * @return {TimeRange}
  20446. * The value of `seekable` from the media element. A `TimeRange` object
  20447. * indicating the current ranges of time that can be seeked to.
  20448. *
  20449. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seekable}
  20450. */
  20451. 'seekable',
  20452. /**
  20453. * Get the value of `ended` from the media element. `ended` indicates whether
  20454. * the media has reached the end or not.
  20455. *
  20456. * @method Html5#ended
  20457. * @return {boolean}
  20458. * - The value of `ended` from the media element.
  20459. * - True indicates that the media has ended.
  20460. * - False indicates that the media has not ended.
  20461. *
  20462. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-ended}
  20463. */
  20464. 'ended',
  20465. /**
  20466. * Get the value of `playbackRate` from the media element. `playbackRate` indicates
  20467. * the rate at which the media is currently playing back. Examples:
  20468. * - if playbackRate is set to 2, media will play twice as fast.
  20469. * - if playbackRate is set to 0.5, media will play half as fast.
  20470. *
  20471. * @method Html5#playbackRate
  20472. * @return {number}
  20473. * The value of `playbackRate` from the media element. A number indicating
  20474. * the current playback speed of the media, where 1 is normal speed.
  20475. *
  20476. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  20477. */
  20478. 'playbackRate',
  20479. /**
  20480. * Get the value of `defaultPlaybackRate` from the media element. `defaultPlaybackRate` indicates
  20481. * the rate at which the media is currently playing back. This value will not indicate the current
  20482. * `playbackRate` after playback has started, use {@link Html5#playbackRate} for that.
  20483. *
  20484. * Examples:
  20485. * - if defaultPlaybackRate is set to 2, media will play twice as fast.
  20486. * - if defaultPlaybackRate is set to 0.5, media will play half as fast.
  20487. *
  20488. * @method Html5.prototype.defaultPlaybackRate
  20489. * @return {number}
  20490. * The value of `defaultPlaybackRate` from the media element. A number indicating
  20491. * the current playback speed of the media, where 1 is normal speed.
  20492. *
  20493. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  20494. */
  20495. 'defaultPlaybackRate',
  20496. /**
  20497. * Get the value of 'disablePictureInPicture' from the video element.
  20498. *
  20499. * @method Html5#disablePictureInPicture
  20500. * @return {boolean} value
  20501. * - The value of `disablePictureInPicture` from the video element.
  20502. * - True indicates that the video can't be played in Picture-In-Picture mode
  20503. * - False indicates that the video can be played in Picture-In-Picture mode
  20504. *
  20505. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
  20506. */
  20507. 'disablePictureInPicture',
  20508. /**
  20509. * Get the value of `played` from the media element. `played` returns a `TimeRange`
  20510. * object representing points in the media timeline that have been played.
  20511. *
  20512. * @method Html5#played
  20513. * @return {TimeRange}
  20514. * The value of `played` from the media element. A `TimeRange` object indicating
  20515. * the ranges of time that have been played.
  20516. *
  20517. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-played}
  20518. */
  20519. 'played',
  20520. /**
  20521. * Get the value of `networkState` from the media element. `networkState` indicates
  20522. * the current network state. It returns an enumeration from the following list:
  20523. * - 0: NETWORK_EMPTY
  20524. * - 1: NETWORK_IDLE
  20525. * - 2: NETWORK_LOADING
  20526. * - 3: NETWORK_NO_SOURCE
  20527. *
  20528. * @method Html5#networkState
  20529. * @return {number}
  20530. * The value of `networkState` from the media element. This will be a number
  20531. * from the list in the description.
  20532. *
  20533. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-networkstate}
  20534. */
  20535. 'networkState',
  20536. /**
  20537. * Get the value of `readyState` from the media element. `readyState` indicates
  20538. * the current state of the media element. It returns an enumeration from the
  20539. * following list:
  20540. * - 0: HAVE_NOTHING
  20541. * - 1: HAVE_METADATA
  20542. * - 2: HAVE_CURRENT_DATA
  20543. * - 3: HAVE_FUTURE_DATA
  20544. * - 4: HAVE_ENOUGH_DATA
  20545. *
  20546. * @method Html5#readyState
  20547. * @return {number}
  20548. * The value of `readyState` from the media element. This will be a number
  20549. * from the list in the description.
  20550. *
  20551. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#ready-states}
  20552. */
  20553. 'readyState',
  20554. /**
  20555. * Get the value of `videoWidth` from the video element. `videoWidth` indicates
  20556. * the current width of the video in css pixels.
  20557. *
  20558. * @method Html5#videoWidth
  20559. * @return {number}
  20560. * The value of `videoWidth` from the video element. This will be a number
  20561. * in css pixels.
  20562. *
  20563. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
  20564. */
  20565. 'videoWidth',
  20566. /**
  20567. * Get the value of `videoHeight` from the video element. `videoHeight` indicates
  20568. * the current height of the video in css pixels.
  20569. *
  20570. * @method Html5#videoHeight
  20571. * @return {number}
  20572. * The value of `videoHeight` from the video element. This will be a number
  20573. * in css pixels.
  20574. *
  20575. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
  20576. */
  20577. 'videoHeight',
  20578. /**
  20579. * Get the value of `crossOrigin` from the media element. `crossOrigin` indicates
  20580. * to the browser that should sent the cookies along with the requests for the
  20581. * different assets/playlists
  20582. *
  20583. * @method Html5#crossOrigin
  20584. * @return {string}
  20585. * - anonymous indicates that the media should not sent cookies.
  20586. * - use-credentials indicates that the media should sent cookies along the requests.
  20587. *
  20588. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
  20589. */
  20590. 'crossOrigin'].forEach(function (prop) {
  20591. Html5.prototype[prop] = function () {
  20592. return this.el_[prop];
  20593. };
  20594. }); // Wrap native properties with a setter in this format:
  20595. // set + toTitleCase(name)
  20596. // The list is as follows:
  20597. // setVolume, setSrc, setPoster, setPreload, setPlaybackRate, setDefaultPlaybackRate,
  20598. // setDisablePictureInPicture, setCrossOrigin
  20599. [
  20600. /**
  20601. * Set the value of `volume` on the media element. `volume` indicates the current
  20602. * audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and
  20603. * so on.
  20604. *
  20605. * @method Html5#setVolume
  20606. * @param {number} percentAsDecimal
  20607. * The volume percent as a decimal. Valid range is from 0-1.
  20608. *
  20609. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
  20610. */
  20611. 'volume',
  20612. /**
  20613. * Set the value of `src` on the media element. `src` indicates the current
  20614. * {@link Tech~SourceObject} for the media.
  20615. *
  20616. * @method Html5#setSrc
  20617. * @param {Tech~SourceObject} src
  20618. * The source object to set as the current source.
  20619. *
  20620. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-src}
  20621. */
  20622. 'src',
  20623. /**
  20624. * Set the value of `poster` on the media element. `poster` is the url to
  20625. * an image file that can/will be shown when no media data is available.
  20626. *
  20627. * @method Html5#setPoster
  20628. * @param {string} poster
  20629. * The url to an image that should be used as the `poster` for the media
  20630. * element.
  20631. *
  20632. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-poster}
  20633. */
  20634. 'poster',
  20635. /**
  20636. * Set the value of `preload` on the media element. `preload` indicates
  20637. * what should download before the media is interacted with. It can have the following
  20638. * values:
  20639. * - none: nothing should be downloaded
  20640. * - metadata: poster and the first few frames of the media may be downloaded to get
  20641. * media dimensions and other metadata
  20642. * - auto: allow the media and metadata for the media to be downloaded before
  20643. * interaction
  20644. *
  20645. * @method Html5#setPreload
  20646. * @param {string} preload
  20647. * The value of `preload` to set on the media element. Must be 'none', 'metadata',
  20648. * or 'auto'.
  20649. *
  20650. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
  20651. */
  20652. 'preload',
  20653. /**
  20654. * Set the value of `playbackRate` on the media element. `playbackRate` indicates
  20655. * the rate at which the media should play back. Examples:
  20656. * - if playbackRate is set to 2, media will play twice as fast.
  20657. * - if playbackRate is set to 0.5, media will play half as fast.
  20658. *
  20659. * @method Html5#setPlaybackRate
  20660. * @return {number}
  20661. * The value of `playbackRate` from the media element. A number indicating
  20662. * the current playback speed of the media, where 1 is normal speed.
  20663. *
  20664. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  20665. */
  20666. 'playbackRate',
  20667. /**
  20668. * Set the value of `defaultPlaybackRate` on the media element. `defaultPlaybackRate` indicates
  20669. * the rate at which the media should play back upon initial startup. Changing this value
  20670. * after a video has started will do nothing. Instead you should used {@link Html5#setPlaybackRate}.
  20671. *
  20672. * Example Values:
  20673. * - if playbackRate is set to 2, media will play twice as fast.
  20674. * - if playbackRate is set to 0.5, media will play half as fast.
  20675. *
  20676. * @method Html5.prototype.setDefaultPlaybackRate
  20677. * @return {number}
  20678. * The value of `defaultPlaybackRate` from the media element. A number indicating
  20679. * the current playback speed of the media, where 1 is normal speed.
  20680. *
  20681. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultplaybackrate}
  20682. */
  20683. 'defaultPlaybackRate',
  20684. /**
  20685. * Prevents the browser from suggesting a Picture-in-Picture context menu
  20686. * or to request Picture-in-Picture automatically in some cases.
  20687. *
  20688. * @method Html5#setDisablePictureInPicture
  20689. * @param {boolean} value
  20690. * The true value will disable Picture-in-Picture mode.
  20691. *
  20692. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
  20693. */
  20694. 'disablePictureInPicture',
  20695. /**
  20696. * Set the value of `crossOrigin` from the media element. `crossOrigin` indicates
  20697. * to the browser that should sent the cookies along with the requests for the
  20698. * different assets/playlists
  20699. *
  20700. * @method Html5#setCrossOrigin
  20701. * @param {string} crossOrigin
  20702. * - anonymous indicates that the media should not sent cookies.
  20703. * - use-credentials indicates that the media should sent cookies along the requests.
  20704. *
  20705. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
  20706. */
  20707. 'crossOrigin'].forEach(function (prop) {
  20708. Html5.prototype['set' + toTitleCase$1(prop)] = function (v) {
  20709. this.el_[prop] = v;
  20710. };
  20711. }); // wrap native functions with a function
  20712. // The list is as follows:
  20713. // pause, load, play
  20714. [
  20715. /**
  20716. * A wrapper around the media elements `pause` function. This will call the `HTML5`
  20717. * media elements `pause` function.
  20718. *
  20719. * @method Html5#pause
  20720. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-pause}
  20721. */
  20722. 'pause',
  20723. /**
  20724. * A wrapper around the media elements `load` function. This will call the `HTML5`s
  20725. * media element `load` function.
  20726. *
  20727. * @method Html5#load
  20728. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-load}
  20729. */
  20730. 'load',
  20731. /**
  20732. * A wrapper around the media elements `play` function. This will call the `HTML5`s
  20733. * media element `play` function.
  20734. *
  20735. * @method Html5#play
  20736. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-play}
  20737. */
  20738. 'play'].forEach(function (prop) {
  20739. Html5.prototype[prop] = function () {
  20740. return this.el_[prop]();
  20741. };
  20742. });
  20743. Tech.withSourceHandlers(Html5);
  20744. /**
  20745. * Native source handler for Html5, simply passes the source to the media element.
  20746. *
  20747. * @property {Tech~SourceObject} source
  20748. * The source object
  20749. *
  20750. * @property {Html5} tech
  20751. * The instance of the HTML5 tech.
  20752. */
  20753. Html5.nativeSourceHandler = {};
  20754. /**
  20755. * Check if the media element can play the given mime type.
  20756. *
  20757. * @param {string} type
  20758. * The mimetype to check
  20759. *
  20760. * @return {string}
  20761. * 'probably', 'maybe', or '' (empty string)
  20762. */
  20763. Html5.nativeSourceHandler.canPlayType = function (type) {
  20764. // IE without MediaPlayer throws an error (#519)
  20765. try {
  20766. return Html5.TEST_VID.canPlayType(type);
  20767. } catch (e) {
  20768. return '';
  20769. }
  20770. };
  20771. /**
  20772. * Check if the media element can handle a source natively.
  20773. *
  20774. * @param {Tech~SourceObject} source
  20775. * The source object
  20776. *
  20777. * @param {Object} [options]
  20778. * Options to be passed to the tech.
  20779. *
  20780. * @return {string}
  20781. * 'probably', 'maybe', or '' (empty string).
  20782. */
  20783. Html5.nativeSourceHandler.canHandleSource = function (source, options) {
  20784. // If a type was provided we should rely on that
  20785. if (source.type) {
  20786. return Html5.nativeSourceHandler.canPlayType(source.type); // If no type, fall back to checking 'video/[EXTENSION]'
  20787. } else if (source.src) {
  20788. var ext = getFileExtension(source.src);
  20789. return Html5.nativeSourceHandler.canPlayType("video/" + ext);
  20790. }
  20791. return '';
  20792. };
  20793. /**
  20794. * Pass the source to the native media element.
  20795. *
  20796. * @param {Tech~SourceObject} source
  20797. * The source object
  20798. *
  20799. * @param {Html5} tech
  20800. * The instance of the Html5 tech
  20801. *
  20802. * @param {Object} [options]
  20803. * The options to pass to the source
  20804. */
  20805. Html5.nativeSourceHandler.handleSource = function (source, tech, options) {
  20806. tech.setSrc(source.src);
  20807. };
  20808. /**
  20809. * A noop for the native dispose function, as cleanup is not needed.
  20810. */
  20811. Html5.nativeSourceHandler.dispose = function () {}; // Register the native source handler
  20812. Html5.registerSourceHandler(Html5.nativeSourceHandler);
  20813. Tech.registerTech('Html5', Html5);
  20814. // on the player when they happen
  20815. var TECH_EVENTS_RETRIGGER = [
  20816. /**
  20817. * Fired while the user agent is downloading media data.
  20818. *
  20819. * @event Player#progress
  20820. * @type {EventTarget~Event}
  20821. */
  20822. /**
  20823. * Retrigger the `progress` event that was triggered by the {@link Tech}.
  20824. *
  20825. * @private
  20826. * @method Player#handleTechProgress_
  20827. * @fires Player#progress
  20828. * @listens Tech#progress
  20829. */
  20830. 'progress',
  20831. /**
  20832. * Fires when the loading of an audio/video is aborted.
  20833. *
  20834. * @event Player#abort
  20835. * @type {EventTarget~Event}
  20836. */
  20837. /**
  20838. * Retrigger the `abort` event that was triggered by the {@link Tech}.
  20839. *
  20840. * @private
  20841. * @method Player#handleTechAbort_
  20842. * @fires Player#abort
  20843. * @listens Tech#abort
  20844. */
  20845. 'abort',
  20846. /**
  20847. * Fires when the browser is intentionally not getting media data.
  20848. *
  20849. * @event Player#suspend
  20850. * @type {EventTarget~Event}
  20851. */
  20852. /**
  20853. * Retrigger the `suspend` event that was triggered by the {@link Tech}.
  20854. *
  20855. * @private
  20856. * @method Player#handleTechSuspend_
  20857. * @fires Player#suspend
  20858. * @listens Tech#suspend
  20859. */
  20860. 'suspend',
  20861. /**
  20862. * Fires when the current playlist is empty.
  20863. *
  20864. * @event Player#emptied
  20865. * @type {EventTarget~Event}
  20866. */
  20867. /**
  20868. * Retrigger the `emptied` event that was triggered by the {@link Tech}.
  20869. *
  20870. * @private
  20871. * @method Player#handleTechEmptied_
  20872. * @fires Player#emptied
  20873. * @listens Tech#emptied
  20874. */
  20875. 'emptied',
  20876. /**
  20877. * Fires when the browser is trying to get media data, but data is not available.
  20878. *
  20879. * @event Player#stalled
  20880. * @type {EventTarget~Event}
  20881. */
  20882. /**
  20883. * Retrigger the `stalled` event that was triggered by the {@link Tech}.
  20884. *
  20885. * @private
  20886. * @method Player#handleTechStalled_
  20887. * @fires Player#stalled
  20888. * @listens Tech#stalled
  20889. */
  20890. 'stalled',
  20891. /**
  20892. * Fires when the browser has loaded meta data for the audio/video.
  20893. *
  20894. * @event Player#loadedmetadata
  20895. * @type {EventTarget~Event}
  20896. */
  20897. /**
  20898. * Retrigger the `loadedmetadata` event that was triggered by the {@link Tech}.
  20899. *
  20900. * @private
  20901. * @method Player#handleTechLoadedmetadata_
  20902. * @fires Player#loadedmetadata
  20903. * @listens Tech#loadedmetadata
  20904. */
  20905. 'loadedmetadata',
  20906. /**
  20907. * Fires when the browser has loaded the current frame of the audio/video.
  20908. *
  20909. * @event Player#loadeddata
  20910. * @type {event}
  20911. */
  20912. /**
  20913. * Retrigger the `loadeddata` event that was triggered by the {@link Tech}.
  20914. *
  20915. * @private
  20916. * @method Player#handleTechLoaddeddata_
  20917. * @fires Player#loadeddata
  20918. * @listens Tech#loadeddata
  20919. */
  20920. 'loadeddata',
  20921. /**
  20922. * Fires when the current playback position has changed.
  20923. *
  20924. * @event Player#timeupdate
  20925. * @type {event}
  20926. */
  20927. /**
  20928. * Retrigger the `timeupdate` event that was triggered by the {@link Tech}.
  20929. *
  20930. * @private
  20931. * @method Player#handleTechTimeUpdate_
  20932. * @fires Player#timeupdate
  20933. * @listens Tech#timeupdate
  20934. */
  20935. 'timeupdate',
  20936. /**
  20937. * Fires when the video's intrinsic dimensions change
  20938. *
  20939. * @event Player#resize
  20940. * @type {event}
  20941. */
  20942. /**
  20943. * Retrigger the `resize` event that was triggered by the {@link Tech}.
  20944. *
  20945. * @private
  20946. * @method Player#handleTechResize_
  20947. * @fires Player#resize
  20948. * @listens Tech#resize
  20949. */
  20950. 'resize',
  20951. /**
  20952. * Fires when the volume has been changed
  20953. *
  20954. * @event Player#volumechange
  20955. * @type {event}
  20956. */
  20957. /**
  20958. * Retrigger the `volumechange` event that was triggered by the {@link Tech}.
  20959. *
  20960. * @private
  20961. * @method Player#handleTechVolumechange_
  20962. * @fires Player#volumechange
  20963. * @listens Tech#volumechange
  20964. */
  20965. 'volumechange',
  20966. /**
  20967. * Fires when the text track has been changed
  20968. *
  20969. * @event Player#texttrackchange
  20970. * @type {event}
  20971. */
  20972. /**
  20973. * Retrigger the `texttrackchange` event that was triggered by the {@link Tech}.
  20974. *
  20975. * @private
  20976. * @method Player#handleTechTexttrackchange_
  20977. * @fires Player#texttrackchange
  20978. * @listens Tech#texttrackchange
  20979. */
  20980. 'texttrackchange']; // events to queue when playback rate is zero
  20981. // this is a hash for the sole purpose of mapping non-camel-cased event names
  20982. // to camel-cased function names
  20983. var TECH_EVENTS_QUEUE = {
  20984. canplay: 'CanPlay',
  20985. canplaythrough: 'CanPlayThrough',
  20986. playing: 'Playing',
  20987. seeked: 'Seeked'
  20988. };
  20989. var BREAKPOINT_ORDER = ['tiny', 'xsmall', 'small', 'medium', 'large', 'xlarge', 'huge'];
  20990. var BREAKPOINT_CLASSES = {}; // grep: vjs-layout-tiny
  20991. // grep: vjs-layout-x-small
  20992. // grep: vjs-layout-small
  20993. // grep: vjs-layout-medium
  20994. // grep: vjs-layout-large
  20995. // grep: vjs-layout-x-large
  20996. // grep: vjs-layout-huge
  20997. BREAKPOINT_ORDER.forEach(function (k) {
  20998. var v = k.charAt(0) === 'x' ? "x-" + k.substring(1) : k;
  20999. BREAKPOINT_CLASSES[k] = "vjs-layout-" + v;
  21000. });
  21001. var DEFAULT_BREAKPOINTS = {
  21002. tiny: 210,
  21003. xsmall: 320,
  21004. small: 425,
  21005. medium: 768,
  21006. large: 1440,
  21007. xlarge: 2560,
  21008. huge: Infinity
  21009. };
  21010. /**
  21011. * An instance of the `Player` class is created when any of the Video.js setup methods
  21012. * are used to initialize a video.
  21013. *
  21014. * After an instance has been created it can be accessed globally in two ways:
  21015. * 1. By calling `videojs('example_video_1');`
  21016. * 2. By using it directly via `videojs.players.example_video_1;`
  21017. *
  21018. * @extends Component
  21019. */
  21020. var Player = /*#__PURE__*/function (_Component) {
  21021. inheritsLoose(Player, _Component);
  21022. /**
  21023. * Create an instance of this class.
  21024. *
  21025. * @param {Element} tag
  21026. * The original video DOM element used for configuring options.
  21027. *
  21028. * @param {Object} [options]
  21029. * Object of option names and values.
  21030. *
  21031. * @param {Component~ReadyCallback} [ready]
  21032. * Ready callback function.
  21033. */
  21034. function Player(tag, options, ready) {
  21035. var _this;
  21036. // Make sure tag ID exists
  21037. tag.id = tag.id || options.id || "vjs_video_" + newGUID(); // Set Options
  21038. // The options argument overrides options set in the video tag
  21039. // which overrides globally set options.
  21040. // This latter part coincides with the load order
  21041. // (tag must exist before Player)
  21042. options = assign$1(Player.getTagSettings(tag), options); // Delay the initialization of children because we need to set up
  21043. // player properties first, and can't use `this` before `super()`
  21044. options.initChildren = false; // Same with creating the element
  21045. options.createEl = false; // don't auto mixin the evented mixin
  21046. options.evented = false; // we don't want the player to report touch activity on itself
  21047. // see enableTouchActivity in Component
  21048. options.reportTouchActivity = false; // If language is not set, get the closest lang attribute
  21049. if (!options.language) {
  21050. if (typeof tag.closest === 'function') {
  21051. var closest = tag.closest('[lang]');
  21052. if (closest && closest.getAttribute) {
  21053. options.language = closest.getAttribute('lang');
  21054. }
  21055. } else {
  21056. var element = tag;
  21057. while (element && element.nodeType === 1) {
  21058. if (getAttributes(element).hasOwnProperty('lang')) {
  21059. options.language = element.getAttribute('lang');
  21060. break;
  21061. }
  21062. element = element.parentNode;
  21063. }
  21064. }
  21065. } // Run base component initializing with new options
  21066. _this = _Component.call(this, null, options, ready) || this; // Create bound methods for document listeners.
  21067. _this.boundDocumentFullscreenChange_ = function (e) {
  21068. return _this.documentFullscreenChange_(e);
  21069. };
  21070. _this.boundFullWindowOnEscKey_ = function (e) {
  21071. return _this.fullWindowOnEscKey(e);
  21072. };
  21073. _this.boundUpdateStyleEl_ = function (e) {
  21074. return _this.updateStyleEl_(e);
  21075. };
  21076. _this.boundApplyInitTime_ = function (e) {
  21077. return _this.applyInitTime_(e);
  21078. };
  21079. _this.boundUpdateCurrentBreakpoint_ = function (e) {
  21080. return _this.updateCurrentBreakpoint_(e);
  21081. };
  21082. _this.boundHandleTechClick_ = function (e) {
  21083. return _this.handleTechClick_(e);
  21084. };
  21085. _this.boundHandleTechDoubleClick_ = function (e) {
  21086. return _this.handleTechDoubleClick_(e);
  21087. };
  21088. _this.boundHandleTechTouchStart_ = function (e) {
  21089. return _this.handleTechTouchStart_(e);
  21090. };
  21091. _this.boundHandleTechTouchMove_ = function (e) {
  21092. return _this.handleTechTouchMove_(e);
  21093. };
  21094. _this.boundHandleTechTouchEnd_ = function (e) {
  21095. return _this.handleTechTouchEnd_(e);
  21096. };
  21097. _this.boundHandleTechTap_ = function (e) {
  21098. return _this.handleTechTap_(e);
  21099. }; // default isFullscreen_ to false
  21100. _this.isFullscreen_ = false; // create logger
  21101. _this.log = createLogger(_this.id_); // Hold our own reference to fullscreen api so it can be mocked in tests
  21102. _this.fsApi_ = FullscreenApi; // Tracks when a tech changes the poster
  21103. _this.isPosterFromTech_ = false; // Holds callback info that gets queued when playback rate is zero
  21104. // and a seek is happening
  21105. _this.queuedCallbacks_ = []; // Turn off API access because we're loading a new tech that might load asynchronously
  21106. _this.isReady_ = false; // Init state hasStarted_
  21107. _this.hasStarted_ = false; // Init state userActive_
  21108. _this.userActive_ = false; // Init debugEnabled_
  21109. _this.debugEnabled_ = false; // Init state audioOnlyMode_
  21110. _this.audioOnlyMode_ = false; // Init state audioPosterMode_
  21111. _this.audioPosterMode_ = false; // Init state audioOnlyCache_
  21112. _this.audioOnlyCache_ = {
  21113. playerHeight: null,
  21114. hiddenChildren: []
  21115. }; // if the global option object was accidentally blown away by
  21116. // someone, bail early with an informative error
  21117. if (!_this.options_ || !_this.options_.techOrder || !_this.options_.techOrder.length) {
  21118. throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?');
  21119. } // Store the original tag used to set options
  21120. _this.tag = tag; // Store the tag attributes used to restore html5 element
  21121. _this.tagAttributes = tag && getAttributes(tag); // Update current language
  21122. _this.language(_this.options_.language); // Update Supported Languages
  21123. if (options.languages) {
  21124. // Normalise player option languages to lowercase
  21125. var languagesToLower = {};
  21126. Object.getOwnPropertyNames(options.languages).forEach(function (name) {
  21127. languagesToLower[name.toLowerCase()] = options.languages[name];
  21128. });
  21129. _this.languages_ = languagesToLower;
  21130. } else {
  21131. _this.languages_ = Player.prototype.options_.languages;
  21132. }
  21133. _this.resetCache_(); // Set poster
  21134. _this.poster_ = options.poster || ''; // Set controls
  21135. _this.controls_ = !!options.controls; // Original tag settings stored in options
  21136. // now remove immediately so native controls don't flash.
  21137. // May be turned back on by HTML5 tech if nativeControlsForTouch is true
  21138. tag.controls = false;
  21139. tag.removeAttribute('controls');
  21140. _this.changingSrc_ = false;
  21141. _this.playCallbacks_ = [];
  21142. _this.playTerminatedQueue_ = []; // the attribute overrides the option
  21143. if (tag.hasAttribute('autoplay')) {
  21144. _this.autoplay(true);
  21145. } else {
  21146. // otherwise use the setter to validate and
  21147. // set the correct value.
  21148. _this.autoplay(_this.options_.autoplay);
  21149. } // check plugins
  21150. if (options.plugins) {
  21151. Object.keys(options.plugins).forEach(function (name) {
  21152. if (typeof _this[name] !== 'function') {
  21153. throw new Error("plugin \"" + name + "\" does not exist");
  21154. }
  21155. });
  21156. }
  21157. /*
  21158. * Store the internal state of scrubbing
  21159. *
  21160. * @private
  21161. * @return {Boolean} True if the user is scrubbing
  21162. */
  21163. _this.scrubbing_ = false;
  21164. _this.el_ = _this.createEl(); // Make this an evented object and use `el_` as its event bus.
  21165. evented(assertThisInitialized(_this), {
  21166. eventBusKey: 'el_'
  21167. }); // listen to document and player fullscreenchange handlers so we receive those events
  21168. // before a user can receive them so we can update isFullscreen appropriately.
  21169. // make sure that we listen to fullscreenchange events before everything else to make sure that
  21170. // our isFullscreen method is updated properly for internal components as well as external.
  21171. if (_this.fsApi_.requestFullscreen) {
  21172. on(document, _this.fsApi_.fullscreenchange, _this.boundDocumentFullscreenChange_);
  21173. _this.on(_this.fsApi_.fullscreenchange, _this.boundDocumentFullscreenChange_);
  21174. }
  21175. if (_this.fluid_) {
  21176. _this.on(['playerreset', 'resize'], _this.boundUpdateStyleEl_);
  21177. } // We also want to pass the original player options to each component and plugin
  21178. // as well so they don't need to reach back into the player for options later.
  21179. // We also need to do another copy of this.options_ so we don't end up with
  21180. // an infinite loop.
  21181. var playerOptionsCopy = mergeOptions$3(_this.options_); // Load plugins
  21182. if (options.plugins) {
  21183. Object.keys(options.plugins).forEach(function (name) {
  21184. _this[name](options.plugins[name]);
  21185. });
  21186. } // Enable debug mode to fire debugon event for all plugins.
  21187. if (options.debug) {
  21188. _this.debug(true);
  21189. }
  21190. _this.options_.playerOptions = playerOptionsCopy;
  21191. _this.middleware_ = [];
  21192. _this.playbackRates(options.playbackRates);
  21193. _this.initChildren(); // Set isAudio based on whether or not an audio tag was used
  21194. _this.isAudio(tag.nodeName.toLowerCase() === 'audio'); // Update controls className. Can't do this when the controls are initially
  21195. // set because the element doesn't exist yet.
  21196. if (_this.controls()) {
  21197. _this.addClass('vjs-controls-enabled');
  21198. } else {
  21199. _this.addClass('vjs-controls-disabled');
  21200. } // Set ARIA label and region role depending on player type
  21201. _this.el_.setAttribute('role', 'region');
  21202. if (_this.isAudio()) {
  21203. _this.el_.setAttribute('aria-label', _this.localize('Audio Player'));
  21204. } else {
  21205. _this.el_.setAttribute('aria-label', _this.localize('Video Player'));
  21206. }
  21207. if (_this.isAudio()) {
  21208. _this.addClass('vjs-audio');
  21209. }
  21210. if (_this.flexNotSupported_()) {
  21211. _this.addClass('vjs-no-flex');
  21212. } // TODO: Make this smarter. Toggle user state between touching/mousing
  21213. // using events, since devices can have both touch and mouse events.
  21214. // TODO: Make this check be performed again when the window switches between monitors
  21215. // (See https://github.com/videojs/video.js/issues/5683)
  21216. if (TOUCH_ENABLED) {
  21217. _this.addClass('vjs-touch-enabled');
  21218. } // iOS Safari has broken hover handling
  21219. if (!IS_IOS) {
  21220. _this.addClass('vjs-workinghover');
  21221. } // Make player easily findable by ID
  21222. Player.players[_this.id_] = assertThisInitialized(_this); // Add a major version class to aid css in plugins
  21223. var majorVersion = version$5.split('.')[0];
  21224. _this.addClass("vjs-v" + majorVersion); // When the player is first initialized, trigger activity so components
  21225. // like the control bar show themselves if needed
  21226. _this.userActive(true);
  21227. _this.reportUserActivity();
  21228. _this.one('play', function (e) {
  21229. return _this.listenForUserActivity_(e);
  21230. });
  21231. _this.on('stageclick', function (e) {
  21232. return _this.handleStageClick_(e);
  21233. });
  21234. _this.on('keydown', function (e) {
  21235. return _this.handleKeyDown(e);
  21236. });
  21237. _this.on('languagechange', function (e) {
  21238. return _this.handleLanguagechange(e);
  21239. });
  21240. _this.breakpoints(_this.options_.breakpoints);
  21241. _this.responsive(_this.options_.responsive); // Calling both the audio mode methods after the player is fully
  21242. // setup to be able to listen to the events triggered by them
  21243. _this.on('ready', function () {
  21244. // Calling the audioPosterMode method first so that
  21245. // the audioOnlyMode can take precedence when both options are set to true
  21246. _this.audioPosterMode(_this.options_.audioPosterMode);
  21247. _this.audioOnlyMode(_this.options_.audioOnlyMode);
  21248. });
  21249. return _this;
  21250. }
  21251. /**
  21252. * Destroys the video player and does any necessary cleanup.
  21253. *
  21254. * This is especially helpful if you are dynamically adding and removing videos
  21255. * to/from the DOM.
  21256. *
  21257. * @fires Player#dispose
  21258. */
  21259. var _proto = Player.prototype;
  21260. _proto.dispose = function dispose() {
  21261. var _this2 = this;
  21262. /**
  21263. * Called when the player is being disposed of.
  21264. *
  21265. * @event Player#dispose
  21266. * @type {EventTarget~Event}
  21267. */
  21268. this.trigger('dispose'); // prevent dispose from being called twice
  21269. this.off('dispose'); // Make sure all player-specific document listeners are unbound. This is
  21270. off(document, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  21271. off(document, 'keydown', this.boundFullWindowOnEscKey_);
  21272. if (this.styleEl_ && this.styleEl_.parentNode) {
  21273. this.styleEl_.parentNode.removeChild(this.styleEl_);
  21274. this.styleEl_ = null;
  21275. } // Kill reference to this player
  21276. Player.players[this.id_] = null;
  21277. if (this.tag && this.tag.player) {
  21278. this.tag.player = null;
  21279. }
  21280. if (this.el_ && this.el_.player) {
  21281. this.el_.player = null;
  21282. }
  21283. if (this.tech_) {
  21284. this.tech_.dispose();
  21285. this.isPosterFromTech_ = false;
  21286. this.poster_ = '';
  21287. }
  21288. if (this.playerElIngest_) {
  21289. this.playerElIngest_ = null;
  21290. }
  21291. if (this.tag) {
  21292. this.tag = null;
  21293. }
  21294. clearCacheForPlayer(this); // remove all event handlers for track lists
  21295. // all tracks and track listeners are removed on
  21296. // tech dispose
  21297. ALL.names.forEach(function (name) {
  21298. var props = ALL[name];
  21299. var list = _this2[props.getterName](); // if it is not a native list
  21300. // we have to manually remove event listeners
  21301. if (list && list.off) {
  21302. list.off();
  21303. }
  21304. }); // the actual .el_ is removed here, or replaced if
  21305. _Component.prototype.dispose.call(this, {
  21306. restoreEl: this.options_.restoreEl
  21307. });
  21308. }
  21309. /**
  21310. * Create the `Player`'s DOM element.
  21311. *
  21312. * @return {Element}
  21313. * The DOM element that gets created.
  21314. */
  21315. ;
  21316. _proto.createEl = function createEl() {
  21317. var tag = this.tag;
  21318. var el;
  21319. var playerElIngest = this.playerElIngest_ = tag.parentNode && tag.parentNode.hasAttribute && tag.parentNode.hasAttribute('data-vjs-player');
  21320. var divEmbed = this.tag.tagName.toLowerCase() === 'video-js';
  21321. if (playerElIngest) {
  21322. el = this.el_ = tag.parentNode;
  21323. } else if (!divEmbed) {
  21324. el = this.el_ = _Component.prototype.createEl.call(this, 'div');
  21325. } // Copy over all the attributes from the tag, including ID and class
  21326. // ID will now reference player box, not the video tag
  21327. var attrs = getAttributes(tag);
  21328. if (divEmbed) {
  21329. el = this.el_ = tag;
  21330. tag = this.tag = document.createElement('video');
  21331. while (el.children.length) {
  21332. tag.appendChild(el.firstChild);
  21333. }
  21334. if (!hasClass(el, 'video-js')) {
  21335. addClass(el, 'video-js');
  21336. }
  21337. el.appendChild(tag);
  21338. playerElIngest = this.playerElIngest_ = el; // move properties over from our custom `video-js` element
  21339. // to our new `video` element. This will move things like
  21340. // `src` or `controls` that were set via js before the player
  21341. // was initialized.
  21342. Object.keys(el).forEach(function (k) {
  21343. try {
  21344. tag[k] = el[k];
  21345. } catch (e) {// we got a a property like outerHTML which we can't actually copy, ignore it
  21346. }
  21347. });
  21348. } // set tabindex to -1 to remove the video element from the focus order
  21349. tag.setAttribute('tabindex', '-1');
  21350. attrs.tabindex = '-1'; // Workaround for #4583 (JAWS+IE doesn't announce BPB or play button), and
  21351. // for the same issue with Chrome (on Windows) with JAWS.
  21352. // See https://github.com/FreedomScientific/VFO-standards-support/issues/78
  21353. // Note that we can't detect if JAWS is being used, but this ARIA attribute
  21354. // doesn't change behavior of IE11 or Chrome if JAWS is not being used
  21355. if (IE_VERSION || IS_CHROME && IS_WINDOWS) {
  21356. tag.setAttribute('role', 'application');
  21357. attrs.role = 'application';
  21358. } // Remove width/height attrs from tag so CSS can make it 100% width/height
  21359. tag.removeAttribute('width');
  21360. tag.removeAttribute('height');
  21361. if ('width' in attrs) {
  21362. delete attrs.width;
  21363. }
  21364. if ('height' in attrs) {
  21365. delete attrs.height;
  21366. }
  21367. Object.getOwnPropertyNames(attrs).forEach(function (attr) {
  21368. // don't copy over the class attribute to the player element when we're in a div embed
  21369. // the class is already set up properly in the divEmbed case
  21370. // and we want to make sure that the `video-js` class doesn't get lost
  21371. if (!(divEmbed && attr === 'class')) {
  21372. el.setAttribute(attr, attrs[attr]);
  21373. }
  21374. if (divEmbed) {
  21375. tag.setAttribute(attr, attrs[attr]);
  21376. }
  21377. }); // Update tag id/class for use as HTML5 playback tech
  21378. // Might think we should do this after embedding in container so .vjs-tech class
  21379. // doesn't flash 100% width/height, but class only applies with .video-js parent
  21380. tag.playerId = tag.id;
  21381. tag.id += '_html5_api';
  21382. tag.className = 'vjs-tech'; // Make player findable on elements
  21383. tag.player = el.player = this; // Default state of video is paused
  21384. this.addClass('vjs-paused'); // Add a style element in the player that we'll use to set the width/height
  21385. // of the player in a way that's still overrideable by CSS, just like the
  21386. // video element
  21387. if (window.VIDEOJS_NO_DYNAMIC_STYLE !== true) {
  21388. this.styleEl_ = createStyleElement('vjs-styles-dimensions');
  21389. var defaultsStyleEl = $('.vjs-styles-defaults');
  21390. var head = $('head');
  21391. head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild);
  21392. }
  21393. this.fill_ = false;
  21394. this.fluid_ = false; // Pass in the width/height/aspectRatio options which will update the style el
  21395. this.width(this.options_.width);
  21396. this.height(this.options_.height);
  21397. this.fill(this.options_.fill);
  21398. this.fluid(this.options_.fluid);
  21399. this.aspectRatio(this.options_.aspectRatio); // support both crossOrigin and crossorigin to reduce confusion and issues around the name
  21400. this.crossOrigin(this.options_.crossOrigin || this.options_.crossorigin); // Hide any links within the video/audio tag,
  21401. // because IE doesn't hide them completely from screen readers.
  21402. var links = tag.getElementsByTagName('a');
  21403. for (var i = 0; i < links.length; i++) {
  21404. var linkEl = links.item(i);
  21405. addClass(linkEl, 'vjs-hidden');
  21406. linkEl.setAttribute('hidden', 'hidden');
  21407. } // insertElFirst seems to cause the networkState to flicker from 3 to 2, so
  21408. // keep track of the original for later so we can know if the source originally failed
  21409. tag.initNetworkState_ = tag.networkState; // Wrap video tag in div (el/box) container
  21410. if (tag.parentNode && !playerElIngest) {
  21411. tag.parentNode.insertBefore(el, tag);
  21412. } // insert the tag as the first child of the player element
  21413. // then manually add it to the children array so that this.addChild
  21414. // will work properly for other components
  21415. //
  21416. // Breaks iPhone, fixed in HTML5 setup.
  21417. prependTo(tag, el);
  21418. this.children_.unshift(tag); // Set lang attr on player to ensure CSS :lang() in consistent with player
  21419. // if it's been set to something different to the doc
  21420. this.el_.setAttribute('lang', this.language_);
  21421. this.el_.setAttribute('translate', 'no');
  21422. this.el_ = el;
  21423. return el;
  21424. }
  21425. /**
  21426. * Get or set the `Player`'s crossOrigin option. For the HTML5 player, this
  21427. * sets the `crossOrigin` property on the `<video>` tag to control the CORS
  21428. * behavior.
  21429. *
  21430. * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
  21431. *
  21432. * @param {string} [value]
  21433. * The value to set the `Player`'s crossOrigin to. If an argument is
  21434. * given, must be one of `anonymous` or `use-credentials`.
  21435. *
  21436. * @return {string|undefined}
  21437. * - The current crossOrigin value of the `Player` when getting.
  21438. * - undefined when setting
  21439. */
  21440. ;
  21441. _proto.crossOrigin = function crossOrigin(value) {
  21442. if (!value) {
  21443. return this.techGet_('crossOrigin');
  21444. }
  21445. if (value !== 'anonymous' && value !== 'use-credentials') {
  21446. log$1.warn("crossOrigin must be \"anonymous\" or \"use-credentials\", given \"" + value + "\"");
  21447. return;
  21448. }
  21449. this.techCall_('setCrossOrigin', value);
  21450. return;
  21451. }
  21452. /**
  21453. * A getter/setter for the `Player`'s width. Returns the player's configured value.
  21454. * To get the current width use `currentWidth()`.
  21455. *
  21456. * @param {number} [value]
  21457. * The value to set the `Player`'s width to.
  21458. *
  21459. * @return {number}
  21460. * The current width of the `Player` when getting.
  21461. */
  21462. ;
  21463. _proto.width = function width(value) {
  21464. return this.dimension('width', value);
  21465. }
  21466. /**
  21467. * A getter/setter for the `Player`'s height. Returns the player's configured value.
  21468. * To get the current height use `currentheight()`.
  21469. *
  21470. * @param {number} [value]
  21471. * The value to set the `Player`'s heigth to.
  21472. *
  21473. * @return {number}
  21474. * The current height of the `Player` when getting.
  21475. */
  21476. ;
  21477. _proto.height = function height(value) {
  21478. return this.dimension('height', value);
  21479. }
  21480. /**
  21481. * A getter/setter for the `Player`'s width & height.
  21482. *
  21483. * @param {string} dimension
  21484. * This string can be:
  21485. * - 'width'
  21486. * - 'height'
  21487. *
  21488. * @param {number} [value]
  21489. * Value for dimension specified in the first argument.
  21490. *
  21491. * @return {number}
  21492. * The dimension arguments value when getting (width/height).
  21493. */
  21494. ;
  21495. _proto.dimension = function dimension(_dimension, value) {
  21496. var privDimension = _dimension + '_';
  21497. if (value === undefined) {
  21498. return this[privDimension] || 0;
  21499. }
  21500. if (value === '' || value === 'auto') {
  21501. // If an empty string is given, reset the dimension to be automatic
  21502. this[privDimension] = undefined;
  21503. this.updateStyleEl_();
  21504. return;
  21505. }
  21506. var parsedVal = parseFloat(value);
  21507. if (isNaN(parsedVal)) {
  21508. log$1.error("Improper value \"" + value + "\" supplied for for " + _dimension);
  21509. return;
  21510. }
  21511. this[privDimension] = parsedVal;
  21512. this.updateStyleEl_();
  21513. }
  21514. /**
  21515. * A getter/setter/toggler for the vjs-fluid `className` on the `Player`.
  21516. *
  21517. * Turning this on will turn off fill mode.
  21518. *
  21519. * @param {boolean} [bool]
  21520. * - A value of true adds the class.
  21521. * - A value of false removes the class.
  21522. * - No value will be a getter.
  21523. *
  21524. * @return {boolean|undefined}
  21525. * - The value of fluid when getting.
  21526. * - `undefined` when setting.
  21527. */
  21528. ;
  21529. _proto.fluid = function fluid(bool) {
  21530. var _this3 = this;
  21531. if (bool === undefined) {
  21532. return !!this.fluid_;
  21533. }
  21534. this.fluid_ = !!bool;
  21535. if (isEvented(this)) {
  21536. this.off(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  21537. }
  21538. if (bool) {
  21539. this.addClass('vjs-fluid');
  21540. this.fill(false);
  21541. addEventedCallback(this, function () {
  21542. _this3.on(['playerreset', 'resize'], _this3.boundUpdateStyleEl_);
  21543. });
  21544. } else {
  21545. this.removeClass('vjs-fluid');
  21546. }
  21547. this.updateStyleEl_();
  21548. }
  21549. /**
  21550. * A getter/setter/toggler for the vjs-fill `className` on the `Player`.
  21551. *
  21552. * Turning this on will turn off fluid mode.
  21553. *
  21554. * @param {boolean} [bool]
  21555. * - A value of true adds the class.
  21556. * - A value of false removes the class.
  21557. * - No value will be a getter.
  21558. *
  21559. * @return {boolean|undefined}
  21560. * - The value of fluid when getting.
  21561. * - `undefined` when setting.
  21562. */
  21563. ;
  21564. _proto.fill = function fill(bool) {
  21565. if (bool === undefined) {
  21566. return !!this.fill_;
  21567. }
  21568. this.fill_ = !!bool;
  21569. if (bool) {
  21570. this.addClass('vjs-fill');
  21571. this.fluid(false);
  21572. } else {
  21573. this.removeClass('vjs-fill');
  21574. }
  21575. }
  21576. /**
  21577. * Get/Set the aspect ratio
  21578. *
  21579. * @param {string} [ratio]
  21580. * Aspect ratio for player
  21581. *
  21582. * @return {string|undefined}
  21583. * returns the current aspect ratio when getting
  21584. */
  21585. /**
  21586. * A getter/setter for the `Player`'s aspect ratio.
  21587. *
  21588. * @param {string} [ratio]
  21589. * The value to set the `Player`'s aspect ratio to.
  21590. *
  21591. * @return {string|undefined}
  21592. * - The current aspect ratio of the `Player` when getting.
  21593. * - undefined when setting
  21594. */
  21595. ;
  21596. _proto.aspectRatio = function aspectRatio(ratio) {
  21597. if (ratio === undefined) {
  21598. return this.aspectRatio_;
  21599. } // Check for width:height format
  21600. if (!/^\d+\:\d+$/.test(ratio)) {
  21601. throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.');
  21602. }
  21603. this.aspectRatio_ = ratio; // We're assuming if you set an aspect ratio you want fluid mode,
  21604. // because in fixed mode you could calculate width and height yourself.
  21605. this.fluid(true);
  21606. this.updateStyleEl_();
  21607. }
  21608. /**
  21609. * Update styles of the `Player` element (height, width and aspect ratio).
  21610. *
  21611. * @private
  21612. * @listens Tech#loadedmetadata
  21613. */
  21614. ;
  21615. _proto.updateStyleEl_ = function updateStyleEl_() {
  21616. if (window.VIDEOJS_NO_DYNAMIC_STYLE === true) {
  21617. var _width = typeof this.width_ === 'number' ? this.width_ : this.options_.width;
  21618. var _height = typeof this.height_ === 'number' ? this.height_ : this.options_.height;
  21619. var techEl = this.tech_ && this.tech_.el();
  21620. if (techEl) {
  21621. if (_width >= 0) {
  21622. techEl.width = _width;
  21623. }
  21624. if (_height >= 0) {
  21625. techEl.height = _height;
  21626. }
  21627. }
  21628. return;
  21629. }
  21630. var width;
  21631. var height;
  21632. var aspectRatio;
  21633. var idClass; // The aspect ratio is either used directly or to calculate width and height.
  21634. if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') {
  21635. // Use any aspectRatio that's been specifically set
  21636. aspectRatio = this.aspectRatio_;
  21637. } else if (this.videoWidth() > 0) {
  21638. // Otherwise try to get the aspect ratio from the video metadata
  21639. aspectRatio = this.videoWidth() + ':' + this.videoHeight();
  21640. } else {
  21641. // Or use a default. The video element's is 2:1, but 16:9 is more common.
  21642. aspectRatio = '16:9';
  21643. } // Get the ratio as a decimal we can use to calculate dimensions
  21644. var ratioParts = aspectRatio.split(':');
  21645. var ratioMultiplier = ratioParts[1] / ratioParts[0];
  21646. if (this.width_ !== undefined) {
  21647. // Use any width that's been specifically set
  21648. width = this.width_;
  21649. } else if (this.height_ !== undefined) {
  21650. // Or calulate the width from the aspect ratio if a height has been set
  21651. width = this.height_ / ratioMultiplier;
  21652. } else {
  21653. // Or use the video's metadata, or use the video el's default of 300
  21654. width = this.videoWidth() || 300;
  21655. }
  21656. if (this.height_ !== undefined) {
  21657. // Use any height that's been specifically set
  21658. height = this.height_;
  21659. } else {
  21660. // Otherwise calculate the height from the ratio and the width
  21661. height = width * ratioMultiplier;
  21662. } // Ensure the CSS class is valid by starting with an alpha character
  21663. if (/^[^a-zA-Z]/.test(this.id())) {
  21664. idClass = 'dimensions-' + this.id();
  21665. } else {
  21666. idClass = this.id() + '-dimensions';
  21667. } // Ensure the right class is still on the player for the style element
  21668. this.addClass(idClass);
  21669. setTextContent(this.styleEl_, "\n ." + idClass + " {\n width: " + width + "px;\n height: " + height + "px;\n }\n\n ." + idClass + ".vjs-fluid:not(.vjs-audio-only-mode) {\n padding-top: " + ratioMultiplier * 100 + "%;\n }\n ");
  21670. }
  21671. /**
  21672. * Load/Create an instance of playback {@link Tech} including element
  21673. * and API methods. Then append the `Tech` element in `Player` as a child.
  21674. *
  21675. * @param {string} techName
  21676. * name of the playback technology
  21677. *
  21678. * @param {string} source
  21679. * video source
  21680. *
  21681. * @private
  21682. */
  21683. ;
  21684. _proto.loadTech_ = function loadTech_(techName, source) {
  21685. var _this4 = this;
  21686. // Pause and remove current playback technology
  21687. if (this.tech_) {
  21688. this.unloadTech_();
  21689. }
  21690. var titleTechName = toTitleCase$1(techName);
  21691. var camelTechName = techName.charAt(0).toLowerCase() + techName.slice(1); // get rid of the HTML5 video tag as soon as we are using another tech
  21692. if (titleTechName !== 'Html5' && this.tag) {
  21693. Tech.getTech('Html5').disposeMediaElement(this.tag);
  21694. this.tag.player = null;
  21695. this.tag = null;
  21696. }
  21697. this.techName_ = titleTechName; // Turn off API access because we're loading a new tech that might load asynchronously
  21698. this.isReady_ = false;
  21699. var autoplay = this.autoplay(); // if autoplay is a string (or `true` with normalizeAutoplay: true) we pass false to the tech
  21700. // because the player is going to handle autoplay on `loadstart`
  21701. if (typeof this.autoplay() === 'string' || this.autoplay() === true && this.options_.normalizeAutoplay) {
  21702. autoplay = false;
  21703. } // Grab tech-specific options from player options and add source and parent element to use.
  21704. var techOptions = {
  21705. source: source,
  21706. autoplay: autoplay,
  21707. 'nativeControlsForTouch': this.options_.nativeControlsForTouch,
  21708. 'playerId': this.id(),
  21709. 'techId': this.id() + "_" + camelTechName + "_api",
  21710. 'playsinline': this.options_.playsinline,
  21711. 'preload': this.options_.preload,
  21712. 'loop': this.options_.loop,
  21713. 'disablePictureInPicture': this.options_.disablePictureInPicture,
  21714. 'muted': this.options_.muted,
  21715. 'poster': this.poster(),
  21716. 'language': this.language(),
  21717. 'playerElIngest': this.playerElIngest_ || false,
  21718. 'vtt.js': this.options_['vtt.js'],
  21719. 'canOverridePoster': !!this.options_.techCanOverridePoster,
  21720. 'enableSourceset': this.options_.enableSourceset,
  21721. 'Promise': this.options_.Promise
  21722. };
  21723. ALL.names.forEach(function (name) {
  21724. var props = ALL[name];
  21725. techOptions[props.getterName] = _this4[props.privateName];
  21726. });
  21727. assign$1(techOptions, this.options_[titleTechName]);
  21728. assign$1(techOptions, this.options_[camelTechName]);
  21729. assign$1(techOptions, this.options_[techName.toLowerCase()]);
  21730. if (this.tag) {
  21731. techOptions.tag = this.tag;
  21732. }
  21733. if (source && source.src === this.cache_.src && this.cache_.currentTime > 0) {
  21734. techOptions.startTime = this.cache_.currentTime;
  21735. } // Initialize tech instance
  21736. var TechClass = Tech.getTech(techName);
  21737. if (!TechClass) {
  21738. throw new Error("No Tech named '" + titleTechName + "' exists! '" + titleTechName + "' should be registered using videojs.registerTech()'");
  21739. }
  21740. this.tech_ = new TechClass(techOptions); // player.triggerReady is always async, so don't need this to be async
  21741. this.tech_.ready(bind(this, this.handleTechReady_), true);
  21742. textTrackConverter.jsonToTextTracks(this.textTracksJson_ || [], this.tech_); // Listen to all HTML5-defined events and trigger them on the player
  21743. TECH_EVENTS_RETRIGGER.forEach(function (event) {
  21744. _this4.on(_this4.tech_, event, function (e) {
  21745. return _this4["handleTech" + toTitleCase$1(event) + "_"](e);
  21746. });
  21747. });
  21748. Object.keys(TECH_EVENTS_QUEUE).forEach(function (event) {
  21749. _this4.on(_this4.tech_, event, function (eventObj) {
  21750. if (_this4.tech_.playbackRate() === 0 && _this4.tech_.seeking()) {
  21751. _this4.queuedCallbacks_.push({
  21752. callback: _this4["handleTech" + TECH_EVENTS_QUEUE[event] + "_"].bind(_this4),
  21753. event: eventObj
  21754. });
  21755. return;
  21756. }
  21757. _this4["handleTech" + TECH_EVENTS_QUEUE[event] + "_"](eventObj);
  21758. });
  21759. });
  21760. this.on(this.tech_, 'loadstart', function (e) {
  21761. return _this4.handleTechLoadStart_(e);
  21762. });
  21763. this.on(this.tech_, 'sourceset', function (e) {
  21764. return _this4.handleTechSourceset_(e);
  21765. });
  21766. this.on(this.tech_, 'waiting', function (e) {
  21767. return _this4.handleTechWaiting_(e);
  21768. });
  21769. this.on(this.tech_, 'ended', function (e) {
  21770. return _this4.handleTechEnded_(e);
  21771. });
  21772. this.on(this.tech_, 'seeking', function (e) {
  21773. return _this4.handleTechSeeking_(e);
  21774. });
  21775. this.on(this.tech_, 'play', function (e) {
  21776. return _this4.handleTechPlay_(e);
  21777. });
  21778. this.on(this.tech_, 'firstplay', function (e) {
  21779. return _this4.handleTechFirstPlay_(e);
  21780. });
  21781. this.on(this.tech_, 'pause', function (e) {
  21782. return _this4.handleTechPause_(e);
  21783. });
  21784. this.on(this.tech_, 'durationchange', function (e) {
  21785. return _this4.handleTechDurationChange_(e);
  21786. });
  21787. this.on(this.tech_, 'fullscreenchange', function (e, data) {
  21788. return _this4.handleTechFullscreenChange_(e, data);
  21789. });
  21790. this.on(this.tech_, 'fullscreenerror', function (e, err) {
  21791. return _this4.handleTechFullscreenError_(e, err);
  21792. });
  21793. this.on(this.tech_, 'enterpictureinpicture', function (e) {
  21794. return _this4.handleTechEnterPictureInPicture_(e);
  21795. });
  21796. this.on(this.tech_, 'leavepictureinpicture', function (e) {
  21797. return _this4.handleTechLeavePictureInPicture_(e);
  21798. });
  21799. this.on(this.tech_, 'error', function (e) {
  21800. return _this4.handleTechError_(e);
  21801. });
  21802. this.on(this.tech_, 'posterchange', function (e) {
  21803. return _this4.handleTechPosterChange_(e);
  21804. });
  21805. this.on(this.tech_, 'textdata', function (e) {
  21806. return _this4.handleTechTextData_(e);
  21807. });
  21808. this.on(this.tech_, 'ratechange', function (e) {
  21809. return _this4.handleTechRateChange_(e);
  21810. });
  21811. this.on(this.tech_, 'loadedmetadata', this.boundUpdateStyleEl_);
  21812. this.usingNativeControls(this.techGet_('controls'));
  21813. if (this.controls() && !this.usingNativeControls()) {
  21814. this.addTechControlsListeners_();
  21815. } // Add the tech element in the DOM if it was not already there
  21816. // Make sure to not insert the original video element if using Html5
  21817. if (this.tech_.el().parentNode !== this.el() && (titleTechName !== 'Html5' || !this.tag)) {
  21818. prependTo(this.tech_.el(), this.el());
  21819. } // Get rid of the original video tag reference after the first tech is loaded
  21820. if (this.tag) {
  21821. this.tag.player = null;
  21822. this.tag = null;
  21823. }
  21824. }
  21825. /**
  21826. * Unload and dispose of the current playback {@link Tech}.
  21827. *
  21828. * @private
  21829. */
  21830. ;
  21831. _proto.unloadTech_ = function unloadTech_() {
  21832. var _this5 = this;
  21833. // Save the current text tracks so that we can reuse the same text tracks with the next tech
  21834. ALL.names.forEach(function (name) {
  21835. var props = ALL[name];
  21836. _this5[props.privateName] = _this5[props.getterName]();
  21837. });
  21838. this.textTracksJson_ = textTrackConverter.textTracksToJson(this.tech_);
  21839. this.isReady_ = false;
  21840. this.tech_.dispose();
  21841. this.tech_ = false;
  21842. if (this.isPosterFromTech_) {
  21843. this.poster_ = '';
  21844. this.trigger('posterchange');
  21845. }
  21846. this.isPosterFromTech_ = false;
  21847. }
  21848. /**
  21849. * Return a reference to the current {@link Tech}.
  21850. * It will print a warning by default about the danger of using the tech directly
  21851. * but any argument that is passed in will silence the warning.
  21852. *
  21853. * @param {*} [safety]
  21854. * Anything passed in to silence the warning
  21855. *
  21856. * @return {Tech}
  21857. * The Tech
  21858. */
  21859. ;
  21860. _proto.tech = function tech(safety) {
  21861. if (safety === undefined) {
  21862. log$1.warn('Using the tech directly can be dangerous. I hope you know what you\'re doing.\n' + 'See https://github.com/videojs/video.js/issues/2617 for more info.\n');
  21863. }
  21864. return this.tech_;
  21865. }
  21866. /**
  21867. * Set up click and touch listeners for the playback element
  21868. *
  21869. * - On desktops: a click on the video itself will toggle playback
  21870. * - On mobile devices: a click on the video toggles controls
  21871. * which is done by toggling the user state between active and
  21872. * inactive
  21873. * - A tap can signal that a user has become active or has become inactive
  21874. * e.g. a quick tap on an iPhone movie should reveal the controls. Another
  21875. * quick tap should hide them again (signaling the user is in an inactive
  21876. * viewing state)
  21877. * - In addition to this, we still want the user to be considered inactive after
  21878. * a few seconds of inactivity.
  21879. *
  21880. * > Note: the only part of iOS interaction we can't mimic with this setup
  21881. * is a touch and hold on the video element counting as activity in order to
  21882. * keep the controls showing, but that shouldn't be an issue. A touch and hold
  21883. * on any controls will still keep the user active
  21884. *
  21885. * @private
  21886. */
  21887. ;
  21888. _proto.addTechControlsListeners_ = function addTechControlsListeners_() {
  21889. // Make sure to remove all the previous listeners in case we are called multiple times.
  21890. this.removeTechControlsListeners_();
  21891. this.on(this.tech_, 'click', this.boundHandleTechClick_);
  21892. this.on(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_); // If the controls were hidden we don't want that to change without a tap event
  21893. // so we'll check if the controls were already showing before reporting user
  21894. // activity
  21895. this.on(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);
  21896. this.on(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);
  21897. this.on(this.tech_, 'touchend', this.boundHandleTechTouchEnd_); // The tap listener needs to come after the touchend listener because the tap
  21898. // listener cancels out any reportedUserActivity when setting userActive(false)
  21899. this.on(this.tech_, 'tap', this.boundHandleTechTap_);
  21900. }
  21901. /**
  21902. * Remove the listeners used for click and tap controls. This is needed for
  21903. * toggling to controls disabled, where a tap/touch should do nothing.
  21904. *
  21905. * @private
  21906. */
  21907. ;
  21908. _proto.removeTechControlsListeners_ = function removeTechControlsListeners_() {
  21909. // We don't want to just use `this.off()` because there might be other needed
  21910. // listeners added by techs that extend this.
  21911. this.off(this.tech_, 'tap', this.boundHandleTechTap_);
  21912. this.off(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);
  21913. this.off(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);
  21914. this.off(this.tech_, 'touchend', this.boundHandleTechTouchEnd_);
  21915. this.off(this.tech_, 'click', this.boundHandleTechClick_);
  21916. this.off(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_);
  21917. }
  21918. /**
  21919. * Player waits for the tech to be ready
  21920. *
  21921. * @private
  21922. */
  21923. ;
  21924. _proto.handleTechReady_ = function handleTechReady_() {
  21925. this.triggerReady(); // Keep the same volume as before
  21926. if (this.cache_.volume) {
  21927. this.techCall_('setVolume', this.cache_.volume);
  21928. } // Look if the tech found a higher resolution poster while loading
  21929. this.handleTechPosterChange_(); // Update the duration if available
  21930. this.handleTechDurationChange_();
  21931. }
  21932. /**
  21933. * Retrigger the `loadstart` event that was triggered by the {@link Tech}. This
  21934. * function will also trigger {@link Player#firstplay} if it is the first loadstart
  21935. * for a video.
  21936. *
  21937. * @fires Player#loadstart
  21938. * @fires Player#firstplay
  21939. * @listens Tech#loadstart
  21940. * @private
  21941. */
  21942. ;
  21943. _proto.handleTechLoadStart_ = function handleTechLoadStart_() {
  21944. // TODO: Update to use `emptied` event instead. See #1277.
  21945. this.removeClass('vjs-ended');
  21946. this.removeClass('vjs-seeking'); // reset the error state
  21947. this.error(null); // Update the duration
  21948. this.handleTechDurationChange_(); // If it's already playing we want to trigger a firstplay event now.
  21949. // The firstplay event relies on both the play and loadstart events
  21950. // which can happen in any order for a new source
  21951. if (!this.paused()) {
  21952. /**
  21953. * Fired when the user agent begins looking for media data
  21954. *
  21955. * @event Player#loadstart
  21956. * @type {EventTarget~Event}
  21957. */
  21958. this.trigger('loadstart');
  21959. this.trigger('firstplay');
  21960. } else {
  21961. // reset the hasStarted state
  21962. this.hasStarted(false);
  21963. this.trigger('loadstart');
  21964. } // autoplay happens after loadstart for the browser,
  21965. // so we mimic that behavior
  21966. this.manualAutoplay_(this.autoplay() === true && this.options_.normalizeAutoplay ? 'play' : this.autoplay());
  21967. }
  21968. /**
  21969. * Handle autoplay string values, rather than the typical boolean
  21970. * values that should be handled by the tech. Note that this is not
  21971. * part of any specification. Valid values and what they do can be
  21972. * found on the autoplay getter at Player#autoplay()
  21973. */
  21974. ;
  21975. _proto.manualAutoplay_ = function manualAutoplay_(type) {
  21976. var _this6 = this;
  21977. if (!this.tech_ || typeof type !== 'string') {
  21978. return;
  21979. } // Save original muted() value, set muted to true, and attempt to play().
  21980. // On promise rejection, restore muted from saved value
  21981. var resolveMuted = function resolveMuted() {
  21982. var previouslyMuted = _this6.muted();
  21983. _this6.muted(true);
  21984. var restoreMuted = function restoreMuted() {
  21985. _this6.muted(previouslyMuted);
  21986. }; // restore muted on play terminatation
  21987. _this6.playTerminatedQueue_.push(restoreMuted);
  21988. var mutedPromise = _this6.play();
  21989. if (!isPromise(mutedPromise)) {
  21990. return;
  21991. }
  21992. return mutedPromise["catch"](function (err) {
  21993. restoreMuted();
  21994. throw new Error("Rejection at manualAutoplay. Restoring muted value. " + (err ? err : ''));
  21995. });
  21996. };
  21997. var promise; // if muted defaults to true
  21998. // the only thing we can do is call play
  21999. if (type === 'any' && !this.muted()) {
  22000. promise = this.play();
  22001. if (isPromise(promise)) {
  22002. promise = promise["catch"](resolveMuted);
  22003. }
  22004. } else if (type === 'muted' && !this.muted()) {
  22005. promise = resolveMuted();
  22006. } else {
  22007. promise = this.play();
  22008. }
  22009. if (!isPromise(promise)) {
  22010. return;
  22011. }
  22012. return promise.then(function () {
  22013. _this6.trigger({
  22014. type: 'autoplay-success',
  22015. autoplay: type
  22016. });
  22017. })["catch"](function () {
  22018. _this6.trigger({
  22019. type: 'autoplay-failure',
  22020. autoplay: type
  22021. });
  22022. });
  22023. }
  22024. /**
  22025. * Update the internal source caches so that we return the correct source from
  22026. * `src()`, `currentSource()`, and `currentSources()`.
  22027. *
  22028. * > Note: `currentSources` will not be updated if the source that is passed in exists
  22029. * in the current `currentSources` cache.
  22030. *
  22031. *
  22032. * @param {Tech~SourceObject} srcObj
  22033. * A string or object source to update our caches to.
  22034. */
  22035. ;
  22036. _proto.updateSourceCaches_ = function updateSourceCaches_(srcObj) {
  22037. if (srcObj === void 0) {
  22038. srcObj = '';
  22039. }
  22040. var src = srcObj;
  22041. var type = '';
  22042. if (typeof src !== 'string') {
  22043. src = srcObj.src;
  22044. type = srcObj.type;
  22045. } // make sure all the caches are set to default values
  22046. // to prevent null checking
  22047. this.cache_.source = this.cache_.source || {};
  22048. this.cache_.sources = this.cache_.sources || []; // try to get the type of the src that was passed in
  22049. if (src && !type) {
  22050. type = findMimetype(this, src);
  22051. } // update `currentSource` cache always
  22052. this.cache_.source = mergeOptions$3({}, srcObj, {
  22053. src: src,
  22054. type: type
  22055. });
  22056. var matchingSources = this.cache_.sources.filter(function (s) {
  22057. return s.src && s.src === src;
  22058. });
  22059. var sourceElSources = [];
  22060. var sourceEls = this.$$('source');
  22061. var matchingSourceEls = [];
  22062. for (var i = 0; i < sourceEls.length; i++) {
  22063. var sourceObj = getAttributes(sourceEls[i]);
  22064. sourceElSources.push(sourceObj);
  22065. if (sourceObj.src && sourceObj.src === src) {
  22066. matchingSourceEls.push(sourceObj.src);
  22067. }
  22068. } // if we have matching source els but not matching sources
  22069. // the current source cache is not up to date
  22070. if (matchingSourceEls.length && !matchingSources.length) {
  22071. this.cache_.sources = sourceElSources; // if we don't have matching source or source els set the
  22072. // sources cache to the `currentSource` cache
  22073. } else if (!matchingSources.length) {
  22074. this.cache_.sources = [this.cache_.source];
  22075. } // update the tech `src` cache
  22076. this.cache_.src = src;
  22077. }
  22078. /**
  22079. * *EXPERIMENTAL* Fired when the source is set or changed on the {@link Tech}
  22080. * causing the media element to reload.
  22081. *
  22082. * It will fire for the initial source and each subsequent source.
  22083. * This event is a custom event from Video.js and is triggered by the {@link Tech}.
  22084. *
  22085. * The event object for this event contains a `src` property that will contain the source
  22086. * that was available when the event was triggered. This is generally only necessary if Video.js
  22087. * is switching techs while the source was being changed.
  22088. *
  22089. * It is also fired when `load` is called on the player (or media element)
  22090. * because the {@link https://html.spec.whatwg.org/multipage/media.html#dom-media-load|specification for `load`}
  22091. * says that the resource selection algorithm needs to be aborted and restarted.
  22092. * In this case, it is very likely that the `src` property will be set to the
  22093. * empty string `""` to indicate we do not know what the source will be but
  22094. * that it is changing.
  22095. *
  22096. * *This event is currently still experimental and may change in minor releases.*
  22097. * __To use this, pass `enableSourceset` option to the player.__
  22098. *
  22099. * @event Player#sourceset
  22100. * @type {EventTarget~Event}
  22101. * @prop {string} src
  22102. * The source url available when the `sourceset` was triggered.
  22103. * It will be an empty string if we cannot know what the source is
  22104. * but know that the source will change.
  22105. */
  22106. /**
  22107. * Retrigger the `sourceset` event that was triggered by the {@link Tech}.
  22108. *
  22109. * @fires Player#sourceset
  22110. * @listens Tech#sourceset
  22111. * @private
  22112. */
  22113. ;
  22114. _proto.handleTechSourceset_ = function handleTechSourceset_(event) {
  22115. var _this7 = this;
  22116. // only update the source cache when the source
  22117. // was not updated using the player api
  22118. if (!this.changingSrc_) {
  22119. var updateSourceCaches = function updateSourceCaches(src) {
  22120. return _this7.updateSourceCaches_(src);
  22121. };
  22122. var playerSrc = this.currentSource().src;
  22123. var eventSrc = event.src; // if we have a playerSrc that is not a blob, and a tech src that is a blob
  22124. if (playerSrc && !/^blob:/.test(playerSrc) && /^blob:/.test(eventSrc)) {
  22125. // if both the tech source and the player source were updated we assume
  22126. // something like @videojs/http-streaming did the sourceset and skip updating the source cache.
  22127. if (!this.lastSource_ || this.lastSource_.tech !== eventSrc && this.lastSource_.player !== playerSrc) {
  22128. updateSourceCaches = function updateSourceCaches() {};
  22129. }
  22130. } // update the source to the initial source right away
  22131. // in some cases this will be empty string
  22132. updateSourceCaches(eventSrc); // if the `sourceset` `src` was an empty string
  22133. // wait for a `loadstart` to update the cache to `currentSrc`.
  22134. // If a sourceset happens before a `loadstart`, we reset the state
  22135. if (!event.src) {
  22136. this.tech_.any(['sourceset', 'loadstart'], function (e) {
  22137. // if a sourceset happens before a `loadstart` there
  22138. // is nothing to do as this `handleTechSourceset_`
  22139. // will be called again and this will be handled there.
  22140. if (e.type === 'sourceset') {
  22141. return;
  22142. }
  22143. var techSrc = _this7.techGet('currentSrc');
  22144. _this7.lastSource_.tech = techSrc;
  22145. _this7.updateSourceCaches_(techSrc);
  22146. });
  22147. }
  22148. }
  22149. this.lastSource_ = {
  22150. player: this.currentSource().src,
  22151. tech: event.src
  22152. };
  22153. this.trigger({
  22154. src: event.src,
  22155. type: 'sourceset'
  22156. });
  22157. }
  22158. /**
  22159. * Add/remove the vjs-has-started class
  22160. *
  22161. * @fires Player#firstplay
  22162. *
  22163. * @param {boolean} request
  22164. * - true: adds the class
  22165. * - false: remove the class
  22166. *
  22167. * @return {boolean}
  22168. * the boolean value of hasStarted_
  22169. */
  22170. ;
  22171. _proto.hasStarted = function hasStarted(request) {
  22172. if (request === undefined) {
  22173. // act as getter, if we have no request to change
  22174. return this.hasStarted_;
  22175. }
  22176. if (request === this.hasStarted_) {
  22177. return;
  22178. }
  22179. this.hasStarted_ = request;
  22180. if (this.hasStarted_) {
  22181. this.addClass('vjs-has-started');
  22182. this.trigger('firstplay');
  22183. } else {
  22184. this.removeClass('vjs-has-started');
  22185. }
  22186. }
  22187. /**
  22188. * Fired whenever the media begins or resumes playback
  22189. *
  22190. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play}
  22191. * @fires Player#play
  22192. * @listens Tech#play
  22193. * @private
  22194. */
  22195. ;
  22196. _proto.handleTechPlay_ = function handleTechPlay_() {
  22197. this.removeClass('vjs-ended');
  22198. this.removeClass('vjs-paused');
  22199. this.addClass('vjs-playing'); // hide the poster when the user hits play
  22200. this.hasStarted(true);
  22201. /**
  22202. * Triggered whenever an {@link Tech#play} event happens. Indicates that
  22203. * playback has started or resumed.
  22204. *
  22205. * @event Player#play
  22206. * @type {EventTarget~Event}
  22207. */
  22208. this.trigger('play');
  22209. }
  22210. /**
  22211. * Retrigger the `ratechange` event that was triggered by the {@link Tech}.
  22212. *
  22213. * If there were any events queued while the playback rate was zero, fire
  22214. * those events now.
  22215. *
  22216. * @private
  22217. * @method Player#handleTechRateChange_
  22218. * @fires Player#ratechange
  22219. * @listens Tech#ratechange
  22220. */
  22221. ;
  22222. _proto.handleTechRateChange_ = function handleTechRateChange_() {
  22223. if (this.tech_.playbackRate() > 0 && this.cache_.lastPlaybackRate === 0) {
  22224. this.queuedCallbacks_.forEach(function (queued) {
  22225. return queued.callback(queued.event);
  22226. });
  22227. this.queuedCallbacks_ = [];
  22228. }
  22229. this.cache_.lastPlaybackRate = this.tech_.playbackRate();
  22230. /**
  22231. * Fires when the playing speed of the audio/video is changed
  22232. *
  22233. * @event Player#ratechange
  22234. * @type {event}
  22235. */
  22236. this.trigger('ratechange');
  22237. }
  22238. /**
  22239. * Retrigger the `waiting` event that was triggered by the {@link Tech}.
  22240. *
  22241. * @fires Player#waiting
  22242. * @listens Tech#waiting
  22243. * @private
  22244. */
  22245. ;
  22246. _proto.handleTechWaiting_ = function handleTechWaiting_() {
  22247. var _this8 = this;
  22248. this.addClass('vjs-waiting');
  22249. /**
  22250. * A readyState change on the DOM element has caused playback to stop.
  22251. *
  22252. * @event Player#waiting
  22253. * @type {EventTarget~Event}
  22254. */
  22255. this.trigger('waiting'); // Browsers may emit a timeupdate event after a waiting event. In order to prevent
  22256. // premature removal of the waiting class, wait for the time to change.
  22257. var timeWhenWaiting = this.currentTime();
  22258. var timeUpdateListener = function timeUpdateListener() {
  22259. if (timeWhenWaiting !== _this8.currentTime()) {
  22260. _this8.removeClass('vjs-waiting');
  22261. _this8.off('timeupdate', timeUpdateListener);
  22262. }
  22263. };
  22264. this.on('timeupdate', timeUpdateListener);
  22265. }
  22266. /**
  22267. * Retrigger the `canplay` event that was triggered by the {@link Tech}.
  22268. * > Note: This is not consistent between browsers. See #1351
  22269. *
  22270. * @fires Player#canplay
  22271. * @listens Tech#canplay
  22272. * @private
  22273. */
  22274. ;
  22275. _proto.handleTechCanPlay_ = function handleTechCanPlay_() {
  22276. this.removeClass('vjs-waiting');
  22277. /**
  22278. * The media has a readyState of HAVE_FUTURE_DATA or greater.
  22279. *
  22280. * @event Player#canplay
  22281. * @type {EventTarget~Event}
  22282. */
  22283. this.trigger('canplay');
  22284. }
  22285. /**
  22286. * Retrigger the `canplaythrough` event that was triggered by the {@link Tech}.
  22287. *
  22288. * @fires Player#canplaythrough
  22289. * @listens Tech#canplaythrough
  22290. * @private
  22291. */
  22292. ;
  22293. _proto.handleTechCanPlayThrough_ = function handleTechCanPlayThrough_() {
  22294. this.removeClass('vjs-waiting');
  22295. /**
  22296. * The media has a readyState of HAVE_ENOUGH_DATA or greater. This means that the
  22297. * entire media file can be played without buffering.
  22298. *
  22299. * @event Player#canplaythrough
  22300. * @type {EventTarget~Event}
  22301. */
  22302. this.trigger('canplaythrough');
  22303. }
  22304. /**
  22305. * Retrigger the `playing` event that was triggered by the {@link Tech}.
  22306. *
  22307. * @fires Player#playing
  22308. * @listens Tech#playing
  22309. * @private
  22310. */
  22311. ;
  22312. _proto.handleTechPlaying_ = function handleTechPlaying_() {
  22313. this.removeClass('vjs-waiting');
  22314. /**
  22315. * The media is no longer blocked from playback, and has started playing.
  22316. *
  22317. * @event Player#playing
  22318. * @type {EventTarget~Event}
  22319. */
  22320. this.trigger('playing');
  22321. }
  22322. /**
  22323. * Retrigger the `seeking` event that was triggered by the {@link Tech}.
  22324. *
  22325. * @fires Player#seeking
  22326. * @listens Tech#seeking
  22327. * @private
  22328. */
  22329. ;
  22330. _proto.handleTechSeeking_ = function handleTechSeeking_() {
  22331. this.addClass('vjs-seeking');
  22332. /**
  22333. * Fired whenever the player is jumping to a new time
  22334. *
  22335. * @event Player#seeking
  22336. * @type {EventTarget~Event}
  22337. */
  22338. this.trigger('seeking');
  22339. }
  22340. /**
  22341. * Retrigger the `seeked` event that was triggered by the {@link Tech}.
  22342. *
  22343. * @fires Player#seeked
  22344. * @listens Tech#seeked
  22345. * @private
  22346. */
  22347. ;
  22348. _proto.handleTechSeeked_ = function handleTechSeeked_() {
  22349. this.removeClass('vjs-seeking');
  22350. this.removeClass('vjs-ended');
  22351. /**
  22352. * Fired when the player has finished jumping to a new time
  22353. *
  22354. * @event Player#seeked
  22355. * @type {EventTarget~Event}
  22356. */
  22357. this.trigger('seeked');
  22358. }
  22359. /**
  22360. * Retrigger the `firstplay` event that was triggered by the {@link Tech}.
  22361. *
  22362. * @fires Player#firstplay
  22363. * @listens Tech#firstplay
  22364. * @deprecated As of 6.0 firstplay event is deprecated.
  22365. * As of 6.0 passing the `starttime` option to the player and the firstplay event are deprecated.
  22366. * @private
  22367. */
  22368. ;
  22369. _proto.handleTechFirstPlay_ = function handleTechFirstPlay_() {
  22370. // If the first starttime attribute is specified
  22371. // then we will start at the given offset in seconds
  22372. if (this.options_.starttime) {
  22373. log$1.warn('Passing the `starttime` option to the player will be deprecated in 6.0');
  22374. this.currentTime(this.options_.starttime);
  22375. }
  22376. this.addClass('vjs-has-started');
  22377. /**
  22378. * Fired the first time a video is played. Not part of the HLS spec, and this is
  22379. * probably not the best implementation yet, so use sparingly. If you don't have a
  22380. * reason to prevent playback, use `myPlayer.one('play');` instead.
  22381. *
  22382. * @event Player#firstplay
  22383. * @deprecated As of 6.0 firstplay event is deprecated.
  22384. * @type {EventTarget~Event}
  22385. */
  22386. this.trigger('firstplay');
  22387. }
  22388. /**
  22389. * Retrigger the `pause` event that was triggered by the {@link Tech}.
  22390. *
  22391. * @fires Player#pause
  22392. * @listens Tech#pause
  22393. * @private
  22394. */
  22395. ;
  22396. _proto.handleTechPause_ = function handleTechPause_() {
  22397. this.removeClass('vjs-playing');
  22398. this.addClass('vjs-paused');
  22399. /**
  22400. * Fired whenever the media has been paused
  22401. *
  22402. * @event Player#pause
  22403. * @type {EventTarget~Event}
  22404. */
  22405. this.trigger('pause');
  22406. }
  22407. /**
  22408. * Retrigger the `ended` event that was triggered by the {@link Tech}.
  22409. *
  22410. * @fires Player#ended
  22411. * @listens Tech#ended
  22412. * @private
  22413. */
  22414. ;
  22415. _proto.handleTechEnded_ = function handleTechEnded_() {
  22416. this.addClass('vjs-ended');
  22417. this.removeClass('vjs-waiting');
  22418. if (this.options_.loop) {
  22419. this.currentTime(0);
  22420. this.play();
  22421. } else if (!this.paused()) {
  22422. this.pause();
  22423. }
  22424. /**
  22425. * Fired when the end of the media resource is reached (currentTime == duration)
  22426. *
  22427. * @event Player#ended
  22428. * @type {EventTarget~Event}
  22429. */
  22430. this.trigger('ended');
  22431. }
  22432. /**
  22433. * Fired when the duration of the media resource is first known or changed
  22434. *
  22435. * @listens Tech#durationchange
  22436. * @private
  22437. */
  22438. ;
  22439. _proto.handleTechDurationChange_ = function handleTechDurationChange_() {
  22440. this.duration(this.techGet_('duration'));
  22441. }
  22442. /**
  22443. * Handle a click on the media element to play/pause
  22444. *
  22445. * @param {EventTarget~Event} event
  22446. * the event that caused this function to trigger
  22447. *
  22448. * @listens Tech#click
  22449. * @private
  22450. */
  22451. ;
  22452. _proto.handleTechClick_ = function handleTechClick_(event) {
  22453. // When controls are disabled a click should not toggle playback because
  22454. // the click is considered a control
  22455. if (!this.controls_) {
  22456. return;
  22457. }
  22458. if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.click === undefined || this.options_.userActions.click !== false) {
  22459. if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.click === 'function') {
  22460. this.options_.userActions.click.call(this, event);
  22461. } else if (this.paused()) {
  22462. silencePromise(this.play());
  22463. } else {
  22464. this.pause();
  22465. }
  22466. }
  22467. }
  22468. /**
  22469. * Handle a double-click on the media element to enter/exit fullscreen
  22470. *
  22471. * @param {EventTarget~Event} event
  22472. * the event that caused this function to trigger
  22473. *
  22474. * @listens Tech#dblclick
  22475. * @private
  22476. */
  22477. ;
  22478. _proto.handleTechDoubleClick_ = function handleTechDoubleClick_(event) {
  22479. if (!this.controls_) {
  22480. return;
  22481. } // we do not want to toggle fullscreen state
  22482. // when double-clicking inside a control bar or a modal
  22483. var inAllowedEls = Array.prototype.some.call(this.$$('.vjs-control-bar, .vjs-modal-dialog'), function (el) {
  22484. return el.contains(event.target);
  22485. });
  22486. if (!inAllowedEls) {
  22487. /*
  22488. * options.userActions.doubleClick
  22489. *
  22490. * If `undefined` or `true`, double-click toggles fullscreen if controls are present
  22491. * Set to `false` to disable double-click handling
  22492. * Set to a function to substitute an external double-click handler
  22493. */
  22494. if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.doubleClick === undefined || this.options_.userActions.doubleClick !== false) {
  22495. if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.doubleClick === 'function') {
  22496. this.options_.userActions.doubleClick.call(this, event);
  22497. } else if (this.isFullscreen()) {
  22498. this.exitFullscreen();
  22499. } else {
  22500. this.requestFullscreen();
  22501. }
  22502. }
  22503. }
  22504. }
  22505. /**
  22506. * Handle a tap on the media element. It will toggle the user
  22507. * activity state, which hides and shows the controls.
  22508. *
  22509. * @listens Tech#tap
  22510. * @private
  22511. */
  22512. ;
  22513. _proto.handleTechTap_ = function handleTechTap_() {
  22514. this.userActive(!this.userActive());
  22515. }
  22516. /**
  22517. * Handle touch to start
  22518. *
  22519. * @listens Tech#touchstart
  22520. * @private
  22521. */
  22522. ;
  22523. _proto.handleTechTouchStart_ = function handleTechTouchStart_() {
  22524. this.userWasActive = this.userActive();
  22525. }
  22526. /**
  22527. * Handle touch to move
  22528. *
  22529. * @listens Tech#touchmove
  22530. * @private
  22531. */
  22532. ;
  22533. _proto.handleTechTouchMove_ = function handleTechTouchMove_() {
  22534. if (this.userWasActive) {
  22535. this.reportUserActivity();
  22536. }
  22537. }
  22538. /**
  22539. * Handle touch to end
  22540. *
  22541. * @param {EventTarget~Event} event
  22542. * the touchend event that triggered
  22543. * this function
  22544. *
  22545. * @listens Tech#touchend
  22546. * @private
  22547. */
  22548. ;
  22549. _proto.handleTechTouchEnd_ = function handleTechTouchEnd_(event) {
  22550. // Stop the mouse events from also happening
  22551. if (event.cancelable) {
  22552. event.preventDefault();
  22553. }
  22554. }
  22555. /**
  22556. * native click events on the SWF aren't triggered on IE11, Win8.1RT
  22557. * use stageclick events triggered from inside the SWF instead
  22558. *
  22559. * @private
  22560. * @listens stageclick
  22561. */
  22562. ;
  22563. _proto.handleStageClick_ = function handleStageClick_() {
  22564. this.reportUserActivity();
  22565. }
  22566. /**
  22567. * @private
  22568. */
  22569. ;
  22570. _proto.toggleFullscreenClass_ = function toggleFullscreenClass_() {
  22571. if (this.isFullscreen()) {
  22572. this.addClass('vjs-fullscreen');
  22573. } else {
  22574. this.removeClass('vjs-fullscreen');
  22575. }
  22576. }
  22577. /**
  22578. * when the document fschange event triggers it calls this
  22579. */
  22580. ;
  22581. _proto.documentFullscreenChange_ = function documentFullscreenChange_(e) {
  22582. var targetPlayer = e.target.player; // if another player was fullscreen
  22583. // do a null check for targetPlayer because older firefox's would put document as e.target
  22584. if (targetPlayer && targetPlayer !== this) {
  22585. return;
  22586. }
  22587. var el = this.el();
  22588. var isFs = document[this.fsApi_.fullscreenElement] === el;
  22589. if (!isFs && el.matches) {
  22590. isFs = el.matches(':' + this.fsApi_.fullscreen);
  22591. } else if (!isFs && el.msMatchesSelector) {
  22592. isFs = el.msMatchesSelector(':' + this.fsApi_.fullscreen);
  22593. }
  22594. this.isFullscreen(isFs);
  22595. }
  22596. /**
  22597. * Handle Tech Fullscreen Change
  22598. *
  22599. * @param {EventTarget~Event} event
  22600. * the fullscreenchange event that triggered this function
  22601. *
  22602. * @param {Object} data
  22603. * the data that was sent with the event
  22604. *
  22605. * @private
  22606. * @listens Tech#fullscreenchange
  22607. * @fires Player#fullscreenchange
  22608. */
  22609. ;
  22610. _proto.handleTechFullscreenChange_ = function handleTechFullscreenChange_(event, data) {
  22611. var _this9 = this;
  22612. if (data) {
  22613. if (data.nativeIOSFullscreen) {
  22614. this.addClass('vjs-ios-native-fs');
  22615. this.tech_.one('webkitendfullscreen', function () {
  22616. _this9.removeClass('vjs-ios-native-fs');
  22617. });
  22618. }
  22619. this.isFullscreen(data.isFullscreen);
  22620. }
  22621. };
  22622. _proto.handleTechFullscreenError_ = function handleTechFullscreenError_(event, err) {
  22623. this.trigger('fullscreenerror', err);
  22624. }
  22625. /**
  22626. * @private
  22627. */
  22628. ;
  22629. _proto.togglePictureInPictureClass_ = function togglePictureInPictureClass_() {
  22630. if (this.isInPictureInPicture()) {
  22631. this.addClass('vjs-picture-in-picture');
  22632. } else {
  22633. this.removeClass('vjs-picture-in-picture');
  22634. }
  22635. }
  22636. /**
  22637. * Handle Tech Enter Picture-in-Picture.
  22638. *
  22639. * @param {EventTarget~Event} event
  22640. * the enterpictureinpicture event that triggered this function
  22641. *
  22642. * @private
  22643. * @listens Tech#enterpictureinpicture
  22644. */
  22645. ;
  22646. _proto.handleTechEnterPictureInPicture_ = function handleTechEnterPictureInPicture_(event) {
  22647. this.isInPictureInPicture(true);
  22648. }
  22649. /**
  22650. * Handle Tech Leave Picture-in-Picture.
  22651. *
  22652. * @param {EventTarget~Event} event
  22653. * the leavepictureinpicture event that triggered this function
  22654. *
  22655. * @private
  22656. * @listens Tech#leavepictureinpicture
  22657. */
  22658. ;
  22659. _proto.handleTechLeavePictureInPicture_ = function handleTechLeavePictureInPicture_(event) {
  22660. this.isInPictureInPicture(false);
  22661. }
  22662. /**
  22663. * Fires when an error occurred during the loading of an audio/video.
  22664. *
  22665. * @private
  22666. * @listens Tech#error
  22667. */
  22668. ;
  22669. _proto.handleTechError_ = function handleTechError_() {
  22670. var error = this.tech_.error();
  22671. this.error(error);
  22672. }
  22673. /**
  22674. * Retrigger the `textdata` event that was triggered by the {@link Tech}.
  22675. *
  22676. * @fires Player#textdata
  22677. * @listens Tech#textdata
  22678. * @private
  22679. */
  22680. ;
  22681. _proto.handleTechTextData_ = function handleTechTextData_() {
  22682. var data = null;
  22683. if (arguments.length > 1) {
  22684. data = arguments[1];
  22685. }
  22686. /**
  22687. * Fires when we get a textdata event from tech
  22688. *
  22689. * @event Player#textdata
  22690. * @type {EventTarget~Event}
  22691. */
  22692. this.trigger('textdata', data);
  22693. }
  22694. /**
  22695. * Get object for cached values.
  22696. *
  22697. * @return {Object}
  22698. * get the current object cache
  22699. */
  22700. ;
  22701. _proto.getCache = function getCache() {
  22702. return this.cache_;
  22703. }
  22704. /**
  22705. * Resets the internal cache object.
  22706. *
  22707. * Using this function outside the player constructor or reset method may
  22708. * have unintended side-effects.
  22709. *
  22710. * @private
  22711. */
  22712. ;
  22713. _proto.resetCache_ = function resetCache_() {
  22714. this.cache_ = {
  22715. // Right now, the currentTime is not _really_ cached because it is always
  22716. // retrieved from the tech (see: currentTime). However, for completeness,
  22717. // we set it to zero here to ensure that if we do start actually caching
  22718. // it, we reset it along with everything else.
  22719. currentTime: 0,
  22720. initTime: 0,
  22721. inactivityTimeout: this.options_.inactivityTimeout,
  22722. duration: NaN,
  22723. lastVolume: 1,
  22724. lastPlaybackRate: this.defaultPlaybackRate(),
  22725. media: null,
  22726. src: '',
  22727. source: {},
  22728. sources: [],
  22729. playbackRates: [],
  22730. volume: 1
  22731. };
  22732. }
  22733. /**
  22734. * Pass values to the playback tech
  22735. *
  22736. * @param {string} [method]
  22737. * the method to call
  22738. *
  22739. * @param {Object} arg
  22740. * the argument to pass
  22741. *
  22742. * @private
  22743. */
  22744. ;
  22745. _proto.techCall_ = function techCall_(method, arg) {
  22746. // If it's not ready yet, call method when it is
  22747. this.ready(function () {
  22748. if (method in allowedSetters) {
  22749. return set(this.middleware_, this.tech_, method, arg);
  22750. } else if (method in allowedMediators) {
  22751. return mediate(this.middleware_, this.tech_, method, arg);
  22752. }
  22753. try {
  22754. if (this.tech_) {
  22755. this.tech_[method](arg);
  22756. }
  22757. } catch (e) {
  22758. log$1(e);
  22759. throw e;
  22760. }
  22761. }, true);
  22762. }
  22763. /**
  22764. * Get calls can't wait for the tech, and sometimes don't need to.
  22765. *
  22766. * @param {string} method
  22767. * Tech method
  22768. *
  22769. * @return {Function|undefined}
  22770. * the method or undefined
  22771. *
  22772. * @private
  22773. */
  22774. ;
  22775. _proto.techGet_ = function techGet_(method) {
  22776. if (!this.tech_ || !this.tech_.isReady_) {
  22777. return;
  22778. }
  22779. if (method in allowedGetters) {
  22780. return get(this.middleware_, this.tech_, method);
  22781. } else if (method in allowedMediators) {
  22782. return mediate(this.middleware_, this.tech_, method);
  22783. } // Flash likes to die and reload when you hide or reposition it.
  22784. // In these cases the object methods go away and we get errors.
  22785. // TODO: Is this needed for techs other than Flash?
  22786. // When that happens we'll catch the errors and inform tech that it's not ready any more.
  22787. try {
  22788. return this.tech_[method]();
  22789. } catch (e) {
  22790. // When building additional tech libs, an expected method may not be defined yet
  22791. if (this.tech_[method] === undefined) {
  22792. log$1("Video.js: " + method + " method not defined for " + this.techName_ + " playback technology.", e);
  22793. throw e;
  22794. } // When a method isn't available on the object it throws a TypeError
  22795. if (e.name === 'TypeError') {
  22796. log$1("Video.js: " + method + " unavailable on " + this.techName_ + " playback technology element.", e);
  22797. this.tech_.isReady_ = false;
  22798. throw e;
  22799. } // If error unknown, just log and throw
  22800. log$1(e);
  22801. throw e;
  22802. }
  22803. }
  22804. /**
  22805. * Attempt to begin playback at the first opportunity.
  22806. *
  22807. * @return {Promise|undefined}
  22808. * Returns a promise if the browser supports Promises (or one
  22809. * was passed in as an option). This promise will be resolved on
  22810. * the return value of play. If this is undefined it will fulfill the
  22811. * promise chain otherwise the promise chain will be fulfilled when
  22812. * the promise from play is fulfilled.
  22813. */
  22814. ;
  22815. _proto.play = function play() {
  22816. var _this10 = this;
  22817. var PromiseClass = this.options_.Promise || window.Promise;
  22818. if (PromiseClass) {
  22819. return new PromiseClass(function (resolve) {
  22820. _this10.play_(resolve);
  22821. });
  22822. }
  22823. return this.play_();
  22824. }
  22825. /**
  22826. * The actual logic for play, takes a callback that will be resolved on the
  22827. * return value of play. This allows us to resolve to the play promise if there
  22828. * is one on modern browsers.
  22829. *
  22830. * @private
  22831. * @param {Function} [callback]
  22832. * The callback that should be called when the techs play is actually called
  22833. */
  22834. ;
  22835. _proto.play_ = function play_(callback) {
  22836. var _this11 = this;
  22837. if (callback === void 0) {
  22838. callback = silencePromise;
  22839. }
  22840. this.playCallbacks_.push(callback);
  22841. var isSrcReady = Boolean(!this.changingSrc_ && (this.src() || this.currentSrc()));
  22842. var isSafariOrIOS = Boolean(IS_ANY_SAFARI || IS_IOS); // treat calls to play_ somewhat like the `one` event function
  22843. if (this.waitToPlay_) {
  22844. this.off(['ready', 'loadstart'], this.waitToPlay_);
  22845. this.waitToPlay_ = null;
  22846. } // if the player/tech is not ready or the src itself is not ready
  22847. // queue up a call to play on `ready` or `loadstart`
  22848. if (!this.isReady_ || !isSrcReady) {
  22849. this.waitToPlay_ = function (e) {
  22850. _this11.play_();
  22851. };
  22852. this.one(['ready', 'loadstart'], this.waitToPlay_); // if we are in Safari, there is a high chance that loadstart will trigger after the gesture timeperiod
  22853. // in that case, we need to prime the video element by calling load so it'll be ready in time
  22854. if (!isSrcReady && isSafariOrIOS) {
  22855. this.load();
  22856. }
  22857. return;
  22858. } // If the player/tech is ready and we have a source, we can attempt playback.
  22859. var val = this.techGet_('play'); // For native playback, reset the progress bar if we get a play call from a replay.
  22860. var isNativeReplay = isSafariOrIOS && this.hasClass('vjs-ended');
  22861. if (isNativeReplay) {
  22862. this.resetProgressBar_();
  22863. } // play was terminated if the returned value is null
  22864. if (val === null) {
  22865. this.runPlayTerminatedQueue_();
  22866. } else {
  22867. this.runPlayCallbacks_(val);
  22868. }
  22869. }
  22870. /**
  22871. * These functions will be run when if play is terminated. If play
  22872. * runPlayCallbacks_ is run these function will not be run. This allows us
  22873. * to differenciate between a terminated play and an actual call to play.
  22874. */
  22875. ;
  22876. _proto.runPlayTerminatedQueue_ = function runPlayTerminatedQueue_() {
  22877. var queue = this.playTerminatedQueue_.slice(0);
  22878. this.playTerminatedQueue_ = [];
  22879. queue.forEach(function (q) {
  22880. q();
  22881. });
  22882. }
  22883. /**
  22884. * When a callback to play is delayed we have to run these
  22885. * callbacks when play is actually called on the tech. This function
  22886. * runs the callbacks that were delayed and accepts the return value
  22887. * from the tech.
  22888. *
  22889. * @param {undefined|Promise} val
  22890. * The return value from the tech.
  22891. */
  22892. ;
  22893. _proto.runPlayCallbacks_ = function runPlayCallbacks_(val) {
  22894. var callbacks = this.playCallbacks_.slice(0);
  22895. this.playCallbacks_ = []; // clear play terminatedQueue since we finished a real play
  22896. this.playTerminatedQueue_ = [];
  22897. callbacks.forEach(function (cb) {
  22898. cb(val);
  22899. });
  22900. }
  22901. /**
  22902. * Pause the video playback
  22903. *
  22904. * @return {Player}
  22905. * A reference to the player object this function was called on
  22906. */
  22907. ;
  22908. _proto.pause = function pause() {
  22909. this.techCall_('pause');
  22910. }
  22911. /**
  22912. * Check if the player is paused or has yet to play
  22913. *
  22914. * @return {boolean}
  22915. * - false: if the media is currently playing
  22916. * - true: if media is not currently playing
  22917. */
  22918. ;
  22919. _proto.paused = function paused() {
  22920. // The initial state of paused should be true (in Safari it's actually false)
  22921. return this.techGet_('paused') === false ? false : true;
  22922. }
  22923. /**
  22924. * Get a TimeRange object representing the current ranges of time that the user
  22925. * has played.
  22926. *
  22927. * @return {TimeRange}
  22928. * A time range object that represents all the increments of time that have
  22929. * been played.
  22930. */
  22931. ;
  22932. _proto.played = function played() {
  22933. return this.techGet_('played') || createTimeRanges(0, 0);
  22934. }
  22935. /**
  22936. * Returns whether or not the user is "scrubbing". Scrubbing is
  22937. * when the user has clicked the progress bar handle and is
  22938. * dragging it along the progress bar.
  22939. *
  22940. * @param {boolean} [isScrubbing]
  22941. * whether the user is or is not scrubbing
  22942. *
  22943. * @return {boolean}
  22944. * The value of scrubbing when getting
  22945. */
  22946. ;
  22947. _proto.scrubbing = function scrubbing(isScrubbing) {
  22948. if (typeof isScrubbing === 'undefined') {
  22949. return this.scrubbing_;
  22950. }
  22951. this.scrubbing_ = !!isScrubbing;
  22952. this.techCall_('setScrubbing', this.scrubbing_);
  22953. if (isScrubbing) {
  22954. this.addClass('vjs-scrubbing');
  22955. } else {
  22956. this.removeClass('vjs-scrubbing');
  22957. }
  22958. }
  22959. /**
  22960. * Get or set the current time (in seconds)
  22961. *
  22962. * @param {number|string} [seconds]
  22963. * The time to seek to in seconds
  22964. *
  22965. * @return {number}
  22966. * - the current time in seconds when getting
  22967. */
  22968. ;
  22969. _proto.currentTime = function currentTime(seconds) {
  22970. if (typeof seconds !== 'undefined') {
  22971. if (seconds < 0) {
  22972. seconds = 0;
  22973. }
  22974. if (!this.isReady_ || this.changingSrc_ || !this.tech_ || !this.tech_.isReady_) {
  22975. this.cache_.initTime = seconds;
  22976. this.off('canplay', this.boundApplyInitTime_);
  22977. this.one('canplay', this.boundApplyInitTime_);
  22978. return;
  22979. }
  22980. this.techCall_('setCurrentTime', seconds);
  22981. this.cache_.initTime = 0;
  22982. return;
  22983. } // cache last currentTime and return. default to 0 seconds
  22984. //
  22985. // Caching the currentTime is meant to prevent a massive amount of reads on the tech's
  22986. // currentTime when scrubbing, but may not provide much performance benefit afterall.
  22987. // Should be tested. Also something has to read the actual current time or the cache will
  22988. // never get updated.
  22989. this.cache_.currentTime = this.techGet_('currentTime') || 0;
  22990. return this.cache_.currentTime;
  22991. }
  22992. /**
  22993. * Apply the value of initTime stored in cache as currentTime.
  22994. *
  22995. * @private
  22996. */
  22997. ;
  22998. _proto.applyInitTime_ = function applyInitTime_() {
  22999. this.currentTime(this.cache_.initTime);
  23000. }
  23001. /**
  23002. * Normally gets the length in time of the video in seconds;
  23003. * in all but the rarest use cases an argument will NOT be passed to the method
  23004. *
  23005. * > **NOTE**: The video must have started loading before the duration can be
  23006. * known, and depending on preload behaviour may not be known until the video starts
  23007. * playing.
  23008. *
  23009. * @fires Player#durationchange
  23010. *
  23011. * @param {number} [seconds]
  23012. * The duration of the video to set in seconds
  23013. *
  23014. * @return {number}
  23015. * - The duration of the video in seconds when getting
  23016. */
  23017. ;
  23018. _proto.duration = function duration(seconds) {
  23019. if (seconds === undefined) {
  23020. // return NaN if the duration is not known
  23021. return this.cache_.duration !== undefined ? this.cache_.duration : NaN;
  23022. }
  23023. seconds = parseFloat(seconds); // Standardize on Infinity for signaling video is live
  23024. if (seconds < 0) {
  23025. seconds = Infinity;
  23026. }
  23027. if (seconds !== this.cache_.duration) {
  23028. // Cache the last set value for optimized scrubbing (esp. Flash)
  23029. // TODO: Required for techs other than Flash?
  23030. this.cache_.duration = seconds;
  23031. if (seconds === Infinity) {
  23032. this.addClass('vjs-live');
  23033. } else {
  23034. this.removeClass('vjs-live');
  23035. }
  23036. if (!isNaN(seconds)) {
  23037. // Do not fire durationchange unless the duration value is known.
  23038. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}
  23039. /**
  23040. * @event Player#durationchange
  23041. * @type {EventTarget~Event}
  23042. */
  23043. this.trigger('durationchange');
  23044. }
  23045. }
  23046. }
  23047. /**
  23048. * Calculates how much time is left in the video. Not part
  23049. * of the native video API.
  23050. *
  23051. * @return {number}
  23052. * The time remaining in seconds
  23053. */
  23054. ;
  23055. _proto.remainingTime = function remainingTime() {
  23056. return this.duration() - this.currentTime();
  23057. }
  23058. /**
  23059. * A remaining time function that is intented to be used when
  23060. * the time is to be displayed directly to the user.
  23061. *
  23062. * @return {number}
  23063. * The rounded time remaining in seconds
  23064. */
  23065. ;
  23066. _proto.remainingTimeDisplay = function remainingTimeDisplay() {
  23067. return Math.floor(this.duration()) - Math.floor(this.currentTime());
  23068. } //
  23069. // Kind of like an array of portions of the video that have been downloaded.
  23070. /**
  23071. * Get a TimeRange object with an array of the times of the video
  23072. * that have been downloaded. If you just want the percent of the
  23073. * video that's been downloaded, use bufferedPercent.
  23074. *
  23075. * @see [Buffered Spec]{@link http://dev.w3.org/html5/spec/video.html#dom-media-buffered}
  23076. *
  23077. * @return {TimeRange}
  23078. * A mock TimeRange object (following HTML spec)
  23079. */
  23080. ;
  23081. _proto.buffered = function buffered() {
  23082. var buffered = this.techGet_('buffered');
  23083. if (!buffered || !buffered.length) {
  23084. buffered = createTimeRanges(0, 0);
  23085. }
  23086. return buffered;
  23087. }
  23088. /**
  23089. * Get the percent (as a decimal) of the video that's been downloaded.
  23090. * This method is not a part of the native HTML video API.
  23091. *
  23092. * @return {number}
  23093. * A decimal between 0 and 1 representing the percent
  23094. * that is buffered 0 being 0% and 1 being 100%
  23095. */
  23096. ;
  23097. _proto.bufferedPercent = function bufferedPercent$1() {
  23098. return bufferedPercent(this.buffered(), this.duration());
  23099. }
  23100. /**
  23101. * Get the ending time of the last buffered time range
  23102. * This is used in the progress bar to encapsulate all time ranges.
  23103. *
  23104. * @return {number}
  23105. * The end of the last buffered time range
  23106. */
  23107. ;
  23108. _proto.bufferedEnd = function bufferedEnd() {
  23109. var buffered = this.buffered();
  23110. var duration = this.duration();
  23111. var end = buffered.end(buffered.length - 1);
  23112. if (end > duration) {
  23113. end = duration;
  23114. }
  23115. return end;
  23116. }
  23117. /**
  23118. * Get or set the current volume of the media
  23119. *
  23120. * @param {number} [percentAsDecimal]
  23121. * The new volume as a decimal percent:
  23122. * - 0 is muted/0%/off
  23123. * - 1.0 is 100%/full
  23124. * - 0.5 is half volume or 50%
  23125. *
  23126. * @return {number}
  23127. * The current volume as a percent when getting
  23128. */
  23129. ;
  23130. _proto.volume = function volume(percentAsDecimal) {
  23131. var vol;
  23132. if (percentAsDecimal !== undefined) {
  23133. // Force value to between 0 and 1
  23134. vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal)));
  23135. this.cache_.volume = vol;
  23136. this.techCall_('setVolume', vol);
  23137. if (vol > 0) {
  23138. this.lastVolume_(vol);
  23139. }
  23140. return;
  23141. } // Default to 1 when returning current volume.
  23142. vol = parseFloat(this.techGet_('volume'));
  23143. return isNaN(vol) ? 1 : vol;
  23144. }
  23145. /**
  23146. * Get the current muted state, or turn mute on or off
  23147. *
  23148. * @param {boolean} [muted]
  23149. * - true to mute
  23150. * - false to unmute
  23151. *
  23152. * @return {boolean}
  23153. * - true if mute is on and getting
  23154. * - false if mute is off and getting
  23155. */
  23156. ;
  23157. _proto.muted = function muted(_muted) {
  23158. if (_muted !== undefined) {
  23159. this.techCall_('setMuted', _muted);
  23160. return;
  23161. }
  23162. return this.techGet_('muted') || false;
  23163. }
  23164. /**
  23165. * Get the current defaultMuted state, or turn defaultMuted on or off. defaultMuted
  23166. * indicates the state of muted on initial playback.
  23167. *
  23168. * ```js
  23169. * var myPlayer = videojs('some-player-id');
  23170. *
  23171. * myPlayer.src("http://www.example.com/path/to/video.mp4");
  23172. *
  23173. * // get, should be false
  23174. * console.log(myPlayer.defaultMuted());
  23175. * // set to true
  23176. * myPlayer.defaultMuted(true);
  23177. * // get should be true
  23178. * console.log(myPlayer.defaultMuted());
  23179. * ```
  23180. *
  23181. * @param {boolean} [defaultMuted]
  23182. * - true to mute
  23183. * - false to unmute
  23184. *
  23185. * @return {boolean|Player}
  23186. * - true if defaultMuted is on and getting
  23187. * - false if defaultMuted is off and getting
  23188. * - A reference to the current player when setting
  23189. */
  23190. ;
  23191. _proto.defaultMuted = function defaultMuted(_defaultMuted) {
  23192. if (_defaultMuted !== undefined) {
  23193. return this.techCall_('setDefaultMuted', _defaultMuted);
  23194. }
  23195. return this.techGet_('defaultMuted') || false;
  23196. }
  23197. /**
  23198. * Get the last volume, or set it
  23199. *
  23200. * @param {number} [percentAsDecimal]
  23201. * The new last volume as a decimal percent:
  23202. * - 0 is muted/0%/off
  23203. * - 1.0 is 100%/full
  23204. * - 0.5 is half volume or 50%
  23205. *
  23206. * @return {number}
  23207. * the current value of lastVolume as a percent when getting
  23208. *
  23209. * @private
  23210. */
  23211. ;
  23212. _proto.lastVolume_ = function lastVolume_(percentAsDecimal) {
  23213. if (percentAsDecimal !== undefined && percentAsDecimal !== 0) {
  23214. this.cache_.lastVolume = percentAsDecimal;
  23215. return;
  23216. }
  23217. return this.cache_.lastVolume;
  23218. }
  23219. /**
  23220. * Check if current tech can support native fullscreen
  23221. * (e.g. with built in controls like iOS)
  23222. *
  23223. * @return {boolean}
  23224. * if native fullscreen is supported
  23225. */
  23226. ;
  23227. _proto.supportsFullScreen = function supportsFullScreen() {
  23228. return this.techGet_('supportsFullScreen') || false;
  23229. }
  23230. /**
  23231. * Check if the player is in fullscreen mode or tell the player that it
  23232. * is or is not in fullscreen mode.
  23233. *
  23234. * > NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official
  23235. * property and instead document.fullscreenElement is used. But isFullscreen is
  23236. * still a valuable property for internal player workings.
  23237. *
  23238. * @param {boolean} [isFS]
  23239. * Set the players current fullscreen state
  23240. *
  23241. * @return {boolean}
  23242. * - true if fullscreen is on and getting
  23243. * - false if fullscreen is off and getting
  23244. */
  23245. ;
  23246. _proto.isFullscreen = function isFullscreen(isFS) {
  23247. if (isFS !== undefined) {
  23248. var oldValue = this.isFullscreen_;
  23249. this.isFullscreen_ = Boolean(isFS); // if we changed fullscreen state and we're in prefixed mode, trigger fullscreenchange
  23250. // this is the only place where we trigger fullscreenchange events for older browsers
  23251. // fullWindow mode is treated as a prefixed event and will get a fullscreenchange event as well
  23252. if (this.isFullscreen_ !== oldValue && this.fsApi_.prefixed) {
  23253. /**
  23254. * @event Player#fullscreenchange
  23255. * @type {EventTarget~Event}
  23256. */
  23257. this.trigger('fullscreenchange');
  23258. }
  23259. this.toggleFullscreenClass_();
  23260. return;
  23261. }
  23262. return this.isFullscreen_;
  23263. }
  23264. /**
  23265. * Increase the size of the video to full screen
  23266. * In some browsers, full screen is not supported natively, so it enters
  23267. * "full window mode", where the video fills the browser window.
  23268. * In browsers and devices that support native full screen, sometimes the
  23269. * browser's default controls will be shown, and not the Video.js custom skin.
  23270. * This includes most mobile devices (iOS, Android) and older versions of
  23271. * Safari.
  23272. *
  23273. * @param {Object} [fullscreenOptions]
  23274. * Override the player fullscreen options
  23275. *
  23276. * @fires Player#fullscreenchange
  23277. */
  23278. ;
  23279. _proto.requestFullscreen = function requestFullscreen(fullscreenOptions) {
  23280. var PromiseClass = this.options_.Promise || window.Promise;
  23281. if (PromiseClass) {
  23282. var self = this;
  23283. return new PromiseClass(function (resolve, reject) {
  23284. function offHandler() {
  23285. self.off('fullscreenerror', errorHandler);
  23286. self.off('fullscreenchange', changeHandler);
  23287. }
  23288. function changeHandler() {
  23289. offHandler();
  23290. resolve();
  23291. }
  23292. function errorHandler(e, err) {
  23293. offHandler();
  23294. reject(err);
  23295. }
  23296. self.one('fullscreenchange', changeHandler);
  23297. self.one('fullscreenerror', errorHandler);
  23298. var promise = self.requestFullscreenHelper_(fullscreenOptions);
  23299. if (promise) {
  23300. promise.then(offHandler, offHandler);
  23301. promise.then(resolve, reject);
  23302. }
  23303. });
  23304. }
  23305. return this.requestFullscreenHelper_();
  23306. };
  23307. _proto.requestFullscreenHelper_ = function requestFullscreenHelper_(fullscreenOptions) {
  23308. var _this12 = this;
  23309. var fsOptions; // Only pass fullscreen options to requestFullscreen in spec-compliant browsers.
  23310. // Use defaults or player configured option unless passed directly to this method.
  23311. if (!this.fsApi_.prefixed) {
  23312. fsOptions = this.options_.fullscreen && this.options_.fullscreen.options || {};
  23313. if (fullscreenOptions !== undefined) {
  23314. fsOptions = fullscreenOptions;
  23315. }
  23316. } // This method works as follows:
  23317. // 1. if a fullscreen api is available, use it
  23318. // 1. call requestFullscreen with potential options
  23319. // 2. if we got a promise from above, use it to update isFullscreen()
  23320. // 2. otherwise, if the tech supports fullscreen, call `enterFullScreen` on it.
  23321. // This is particularly used for iPhone, older iPads, and non-safari browser on iOS.
  23322. // 3. otherwise, use "fullWindow" mode
  23323. if (this.fsApi_.requestFullscreen) {
  23324. var promise = this.el_[this.fsApi_.requestFullscreen](fsOptions);
  23325. if (promise) {
  23326. promise.then(function () {
  23327. return _this12.isFullscreen(true);
  23328. }, function () {
  23329. return _this12.isFullscreen(false);
  23330. });
  23331. }
  23332. return promise;
  23333. } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
  23334. // we can't take the video.js controls fullscreen but we can go fullscreen
  23335. // with native controls
  23336. this.techCall_('enterFullScreen');
  23337. } else {
  23338. // fullscreen isn't supported so we'll just stretch the video element to
  23339. // fill the viewport
  23340. this.enterFullWindow();
  23341. }
  23342. }
  23343. /**
  23344. * Return the video to its normal size after having been in full screen mode
  23345. *
  23346. * @fires Player#fullscreenchange
  23347. */
  23348. ;
  23349. _proto.exitFullscreen = function exitFullscreen() {
  23350. var PromiseClass = this.options_.Promise || window.Promise;
  23351. if (PromiseClass) {
  23352. var self = this;
  23353. return new PromiseClass(function (resolve, reject) {
  23354. function offHandler() {
  23355. self.off('fullscreenerror', errorHandler);
  23356. self.off('fullscreenchange', changeHandler);
  23357. }
  23358. function changeHandler() {
  23359. offHandler();
  23360. resolve();
  23361. }
  23362. function errorHandler(e, err) {
  23363. offHandler();
  23364. reject(err);
  23365. }
  23366. self.one('fullscreenchange', changeHandler);
  23367. self.one('fullscreenerror', errorHandler);
  23368. var promise = self.exitFullscreenHelper_();
  23369. if (promise) {
  23370. promise.then(offHandler, offHandler); // map the promise to our resolve/reject methods
  23371. promise.then(resolve, reject);
  23372. }
  23373. });
  23374. }
  23375. return this.exitFullscreenHelper_();
  23376. };
  23377. _proto.exitFullscreenHelper_ = function exitFullscreenHelper_() {
  23378. var _this13 = this;
  23379. if (this.fsApi_.requestFullscreen) {
  23380. var promise = document[this.fsApi_.exitFullscreen]();
  23381. if (promise) {
  23382. // we're splitting the promise here, so, we want to catch the
  23383. // potential error so that this chain doesn't have unhandled errors
  23384. silencePromise(promise.then(function () {
  23385. return _this13.isFullscreen(false);
  23386. }));
  23387. }
  23388. return promise;
  23389. } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
  23390. this.techCall_('exitFullScreen');
  23391. } else {
  23392. this.exitFullWindow();
  23393. }
  23394. }
  23395. /**
  23396. * When fullscreen isn't supported we can stretch the
  23397. * video container to as wide as the browser will let us.
  23398. *
  23399. * @fires Player#enterFullWindow
  23400. */
  23401. ;
  23402. _proto.enterFullWindow = function enterFullWindow() {
  23403. this.isFullscreen(true);
  23404. this.isFullWindow = true; // Storing original doc overflow value to return to when fullscreen is off
  23405. this.docOrigOverflow = document.documentElement.style.overflow; // Add listener for esc key to exit fullscreen
  23406. on(document, 'keydown', this.boundFullWindowOnEscKey_); // Hide any scroll bars
  23407. document.documentElement.style.overflow = 'hidden'; // Apply fullscreen styles
  23408. addClass(document.body, 'vjs-full-window');
  23409. /**
  23410. * @event Player#enterFullWindow
  23411. * @type {EventTarget~Event}
  23412. */
  23413. this.trigger('enterFullWindow');
  23414. }
  23415. /**
  23416. * Check for call to either exit full window or
  23417. * full screen on ESC key
  23418. *
  23419. * @param {string} event
  23420. * Event to check for key press
  23421. */
  23422. ;
  23423. _proto.fullWindowOnEscKey = function fullWindowOnEscKey(event) {
  23424. if (keycode.isEventKey(event, 'Esc')) {
  23425. if (this.isFullscreen() === true) {
  23426. if (!this.isFullWindow) {
  23427. this.exitFullscreen();
  23428. } else {
  23429. this.exitFullWindow();
  23430. }
  23431. }
  23432. }
  23433. }
  23434. /**
  23435. * Exit full window
  23436. *
  23437. * @fires Player#exitFullWindow
  23438. */
  23439. ;
  23440. _proto.exitFullWindow = function exitFullWindow() {
  23441. this.isFullscreen(false);
  23442. this.isFullWindow = false;
  23443. off(document, 'keydown', this.boundFullWindowOnEscKey_); // Unhide scroll bars.
  23444. document.documentElement.style.overflow = this.docOrigOverflow; // Remove fullscreen styles
  23445. removeClass(document.body, 'vjs-full-window'); // Resize the box, controller, and poster to original sizes
  23446. // this.positionAll();
  23447. /**
  23448. * @event Player#exitFullWindow
  23449. * @type {EventTarget~Event}
  23450. */
  23451. this.trigger('exitFullWindow');
  23452. }
  23453. /**
  23454. * Disable Picture-in-Picture mode.
  23455. *
  23456. * @param {boolean} value
  23457. * - true will disable Picture-in-Picture mode
  23458. * - false will enable Picture-in-Picture mode
  23459. */
  23460. ;
  23461. _proto.disablePictureInPicture = function disablePictureInPicture(value) {
  23462. if (value === undefined) {
  23463. return this.techGet_('disablePictureInPicture');
  23464. }
  23465. this.techCall_('setDisablePictureInPicture', value);
  23466. this.options_.disablePictureInPicture = value;
  23467. this.trigger('disablepictureinpicturechanged');
  23468. }
  23469. /**
  23470. * Check if the player is in Picture-in-Picture mode or tell the player that it
  23471. * is or is not in Picture-in-Picture mode.
  23472. *
  23473. * @param {boolean} [isPiP]
  23474. * Set the players current Picture-in-Picture state
  23475. *
  23476. * @return {boolean}
  23477. * - true if Picture-in-Picture is on and getting
  23478. * - false if Picture-in-Picture is off and getting
  23479. */
  23480. ;
  23481. _proto.isInPictureInPicture = function isInPictureInPicture(isPiP) {
  23482. if (isPiP !== undefined) {
  23483. this.isInPictureInPicture_ = !!isPiP;
  23484. this.togglePictureInPictureClass_();
  23485. return;
  23486. }
  23487. return !!this.isInPictureInPicture_;
  23488. }
  23489. /**
  23490. * Create a floating video window always on top of other windows so that users may
  23491. * continue consuming media while they interact with other content sites, or
  23492. * applications on their device.
  23493. *
  23494. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  23495. *
  23496. * @fires Player#enterpictureinpicture
  23497. *
  23498. * @return {Promise}
  23499. * A promise with a Picture-in-Picture window.
  23500. */
  23501. ;
  23502. _proto.requestPictureInPicture = function requestPictureInPicture() {
  23503. if ('pictureInPictureEnabled' in document && this.disablePictureInPicture() === false) {
  23504. /**
  23505. * This event fires when the player enters picture in picture mode
  23506. *
  23507. * @event Player#enterpictureinpicture
  23508. * @type {EventTarget~Event}
  23509. */
  23510. return this.techGet_('requestPictureInPicture');
  23511. }
  23512. }
  23513. /**
  23514. * Exit Picture-in-Picture mode.
  23515. *
  23516. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  23517. *
  23518. * @fires Player#leavepictureinpicture
  23519. *
  23520. * @return {Promise}
  23521. * A promise.
  23522. */
  23523. ;
  23524. _proto.exitPictureInPicture = function exitPictureInPicture() {
  23525. if ('pictureInPictureEnabled' in document) {
  23526. /**
  23527. * This event fires when the player leaves picture in picture mode
  23528. *
  23529. * @event Player#leavepictureinpicture
  23530. * @type {EventTarget~Event}
  23531. */
  23532. return document.exitPictureInPicture();
  23533. }
  23534. }
  23535. /**
  23536. * Called when this Player has focus and a key gets pressed down, or when
  23537. * any Component of this player receives a key press that it doesn't handle.
  23538. * This allows player-wide hotkeys (either as defined below, or optionally
  23539. * by an external function).
  23540. *
  23541. * @param {EventTarget~Event} event
  23542. * The `keydown` event that caused this function to be called.
  23543. *
  23544. * @listens keydown
  23545. */
  23546. ;
  23547. _proto.handleKeyDown = function handleKeyDown(event) {
  23548. var userActions = this.options_.userActions; // Bail out if hotkeys are not configured.
  23549. if (!userActions || !userActions.hotkeys) {
  23550. return;
  23551. } // Function that determines whether or not to exclude an element from
  23552. // hotkeys handling.
  23553. var excludeElement = function excludeElement(el) {
  23554. var tagName = el.tagName.toLowerCase(); // The first and easiest test is for `contenteditable` elements.
  23555. if (el.isContentEditable) {
  23556. return true;
  23557. } // Inputs matching these types will still trigger hotkey handling as
  23558. // they are not text inputs.
  23559. var allowedInputTypes = ['button', 'checkbox', 'hidden', 'radio', 'reset', 'submit'];
  23560. if (tagName === 'input') {
  23561. return allowedInputTypes.indexOf(el.type) === -1;
  23562. } // The final test is by tag name. These tags will be excluded entirely.
  23563. var excludedTags = ['textarea'];
  23564. return excludedTags.indexOf(tagName) !== -1;
  23565. }; // Bail out if the user is focused on an interactive form element.
  23566. if (excludeElement(this.el_.ownerDocument.activeElement)) {
  23567. return;
  23568. }
  23569. if (typeof userActions.hotkeys === 'function') {
  23570. userActions.hotkeys.call(this, event);
  23571. } else {
  23572. this.handleHotkeys(event);
  23573. }
  23574. }
  23575. /**
  23576. * Called when this Player receives a hotkey keydown event.
  23577. * Supported player-wide hotkeys are:
  23578. *
  23579. * f - toggle fullscreen
  23580. * m - toggle mute
  23581. * k or Space - toggle play/pause
  23582. *
  23583. * @param {EventTarget~Event} event
  23584. * The `keydown` event that caused this function to be called.
  23585. */
  23586. ;
  23587. _proto.handleHotkeys = function handleHotkeys(event) {
  23588. var hotkeys = this.options_.userActions ? this.options_.userActions.hotkeys : {}; // set fullscreenKey, muteKey, playPauseKey from `hotkeys`, use defaults if not set
  23589. var _hotkeys$fullscreenKe = hotkeys.fullscreenKey,
  23590. fullscreenKey = _hotkeys$fullscreenKe === void 0 ? function (keydownEvent) {
  23591. return keycode.isEventKey(keydownEvent, 'f');
  23592. } : _hotkeys$fullscreenKe,
  23593. _hotkeys$muteKey = hotkeys.muteKey,
  23594. muteKey = _hotkeys$muteKey === void 0 ? function (keydownEvent) {
  23595. return keycode.isEventKey(keydownEvent, 'm');
  23596. } : _hotkeys$muteKey,
  23597. _hotkeys$playPauseKey = hotkeys.playPauseKey,
  23598. playPauseKey = _hotkeys$playPauseKey === void 0 ? function (keydownEvent) {
  23599. return keycode.isEventKey(keydownEvent, 'k') || keycode.isEventKey(keydownEvent, 'Space');
  23600. } : _hotkeys$playPauseKey;
  23601. if (fullscreenKey.call(this, event)) {
  23602. event.preventDefault();
  23603. event.stopPropagation();
  23604. var FSToggle = Component$1.getComponent('FullscreenToggle');
  23605. if (document[this.fsApi_.fullscreenEnabled] !== false) {
  23606. FSToggle.prototype.handleClick.call(this, event);
  23607. }
  23608. } else if (muteKey.call(this, event)) {
  23609. event.preventDefault();
  23610. event.stopPropagation();
  23611. var MuteToggle = Component$1.getComponent('MuteToggle');
  23612. MuteToggle.prototype.handleClick.call(this, event);
  23613. } else if (playPauseKey.call(this, event)) {
  23614. event.preventDefault();
  23615. event.stopPropagation();
  23616. var PlayToggle = Component$1.getComponent('PlayToggle');
  23617. PlayToggle.prototype.handleClick.call(this, event);
  23618. }
  23619. }
  23620. /**
  23621. * Check whether the player can play a given mimetype
  23622. *
  23623. * @see https://www.w3.org/TR/2011/WD-html5-20110113/video.html#dom-navigator-canplaytype
  23624. *
  23625. * @param {string} type
  23626. * The mimetype to check
  23627. *
  23628. * @return {string}
  23629. * 'probably', 'maybe', or '' (empty string)
  23630. */
  23631. ;
  23632. _proto.canPlayType = function canPlayType(type) {
  23633. var can; // Loop through each playback technology in the options order
  23634. for (var i = 0, j = this.options_.techOrder; i < j.length; i++) {
  23635. var techName = j[i];
  23636. var tech = Tech.getTech(techName); // Support old behavior of techs being registered as components.
  23637. // Remove once that deprecated behavior is removed.
  23638. if (!tech) {
  23639. tech = Component$1.getComponent(techName);
  23640. } // Check if the current tech is defined before continuing
  23641. if (!tech) {
  23642. log$1.error("The \"" + techName + "\" tech is undefined. Skipped browser support check for that tech.");
  23643. continue;
  23644. } // Check if the browser supports this technology
  23645. if (tech.isSupported()) {
  23646. can = tech.canPlayType(type);
  23647. if (can) {
  23648. return can;
  23649. }
  23650. }
  23651. }
  23652. return '';
  23653. }
  23654. /**
  23655. * Select source based on tech-order or source-order
  23656. * Uses source-order selection if `options.sourceOrder` is truthy. Otherwise,
  23657. * defaults to tech-order selection
  23658. *
  23659. * @param {Array} sources
  23660. * The sources for a media asset
  23661. *
  23662. * @return {Object|boolean}
  23663. * Object of source and tech order or false
  23664. */
  23665. ;
  23666. _proto.selectSource = function selectSource(sources) {
  23667. var _this14 = this;
  23668. // Get only the techs specified in `techOrder` that exist and are supported by the
  23669. // current platform
  23670. var techs = this.options_.techOrder.map(function (techName) {
  23671. return [techName, Tech.getTech(techName)];
  23672. }).filter(function (_ref) {
  23673. var techName = _ref[0],
  23674. tech = _ref[1];
  23675. // Check if the current tech is defined before continuing
  23676. if (tech) {
  23677. // Check if the browser supports this technology
  23678. return tech.isSupported();
  23679. }
  23680. log$1.error("The \"" + techName + "\" tech is undefined. Skipped browser support check for that tech.");
  23681. return false;
  23682. }); // Iterate over each `innerArray` element once per `outerArray` element and execute
  23683. // `tester` with both. If `tester` returns a non-falsy value, exit early and return
  23684. // that value.
  23685. var findFirstPassingTechSourcePair = function findFirstPassingTechSourcePair(outerArray, innerArray, tester) {
  23686. var found;
  23687. outerArray.some(function (outerChoice) {
  23688. return innerArray.some(function (innerChoice) {
  23689. found = tester(outerChoice, innerChoice);
  23690. if (found) {
  23691. return true;
  23692. }
  23693. });
  23694. });
  23695. return found;
  23696. };
  23697. var foundSourceAndTech;
  23698. var flip = function flip(fn) {
  23699. return function (a, b) {
  23700. return fn(b, a);
  23701. };
  23702. };
  23703. var finder = function finder(_ref2, source) {
  23704. var techName = _ref2[0],
  23705. tech = _ref2[1];
  23706. if (tech.canPlaySource(source, _this14.options_[techName.toLowerCase()])) {
  23707. return {
  23708. source: source,
  23709. tech: techName
  23710. };
  23711. }
  23712. }; // Depending on the truthiness of `options.sourceOrder`, we swap the order of techs and sources
  23713. // to select from them based on their priority.
  23714. if (this.options_.sourceOrder) {
  23715. // Source-first ordering
  23716. foundSourceAndTech = findFirstPassingTechSourcePair(sources, techs, flip(finder));
  23717. } else {
  23718. // Tech-first ordering
  23719. foundSourceAndTech = findFirstPassingTechSourcePair(techs, sources, finder);
  23720. }
  23721. return foundSourceAndTech || false;
  23722. }
  23723. /**
  23724. * Executes source setting and getting logic
  23725. *
  23726. * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
  23727. * A SourceObject, an array of SourceObjects, or a string referencing
  23728. * a URL to a media source. It is _highly recommended_ that an object
  23729. * or array of objects is used here, so that source selection
  23730. * algorithms can take the `type` into account.
  23731. *
  23732. * If not provided, this method acts as a getter.
  23733. * @param {boolean} isRetry
  23734. * Indicates whether this is being called internally as a result of a retry
  23735. *
  23736. * @return {string|undefined}
  23737. * If the `source` argument is missing, returns the current source
  23738. * URL. Otherwise, returns nothing/undefined.
  23739. */
  23740. ;
  23741. _proto.handleSrc_ = function handleSrc_(source, isRetry) {
  23742. var _this15 = this;
  23743. // getter usage
  23744. if (typeof source === 'undefined') {
  23745. return this.cache_.src || '';
  23746. } // Reset retry behavior for new source
  23747. if (this.resetRetryOnError_) {
  23748. this.resetRetryOnError_();
  23749. } // filter out invalid sources and turn our source into
  23750. // an array of source objects
  23751. var sources = filterSource(source); // if a source was passed in then it is invalid because
  23752. // it was filtered to a zero length Array. So we have to
  23753. // show an error
  23754. if (!sources.length) {
  23755. this.setTimeout(function () {
  23756. this.error({
  23757. code: 4,
  23758. message: this.options_.notSupportedMessage
  23759. });
  23760. }, 0);
  23761. return;
  23762. } // initial sources
  23763. this.changingSrc_ = true; // Only update the cached source list if we are not retrying a new source after error,
  23764. // since in that case we want to include the failed source(s) in the cache
  23765. if (!isRetry) {
  23766. this.cache_.sources = sources;
  23767. }
  23768. this.updateSourceCaches_(sources[0]); // middlewareSource is the source after it has been changed by middleware
  23769. setSource(this, sources[0], function (middlewareSource, mws) {
  23770. _this15.middleware_ = mws; // since sourceSet is async we have to update the cache again after we select a source since
  23771. // the source that is selected could be out of order from the cache update above this callback.
  23772. if (!isRetry) {
  23773. _this15.cache_.sources = sources;
  23774. }
  23775. _this15.updateSourceCaches_(middlewareSource);
  23776. var err = _this15.src_(middlewareSource);
  23777. if (err) {
  23778. if (sources.length > 1) {
  23779. return _this15.handleSrc_(sources.slice(1));
  23780. }
  23781. _this15.changingSrc_ = false; // We need to wrap this in a timeout to give folks a chance to add error event handlers
  23782. _this15.setTimeout(function () {
  23783. this.error({
  23784. code: 4,
  23785. message: this.options_.notSupportedMessage
  23786. });
  23787. }, 0); // we could not find an appropriate tech, but let's still notify the delegate that this is it
  23788. // this needs a better comment about why this is needed
  23789. _this15.triggerReady();
  23790. return;
  23791. }
  23792. setTech(mws, _this15.tech_);
  23793. }); // Try another available source if this one fails before playback.
  23794. if (this.options_.retryOnError && sources.length > 1) {
  23795. var retry = function retry() {
  23796. // Remove the error modal
  23797. _this15.error(null);
  23798. _this15.handleSrc_(sources.slice(1), true);
  23799. };
  23800. var stopListeningForErrors = function stopListeningForErrors() {
  23801. _this15.off('error', retry);
  23802. };
  23803. this.one('error', retry);
  23804. this.one('playing', stopListeningForErrors);
  23805. this.resetRetryOnError_ = function () {
  23806. _this15.off('error', retry);
  23807. _this15.off('playing', stopListeningForErrors);
  23808. };
  23809. }
  23810. }
  23811. /**
  23812. * Get or set the video source.
  23813. *
  23814. * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
  23815. * A SourceObject, an array of SourceObjects, or a string referencing
  23816. * a URL to a media source. It is _highly recommended_ that an object
  23817. * or array of objects is used here, so that source selection
  23818. * algorithms can take the `type` into account.
  23819. *
  23820. * If not provided, this method acts as a getter.
  23821. *
  23822. * @return {string|undefined}
  23823. * If the `source` argument is missing, returns the current source
  23824. * URL. Otherwise, returns nothing/undefined.
  23825. */
  23826. ;
  23827. _proto.src = function src(source) {
  23828. return this.handleSrc_(source, false);
  23829. }
  23830. /**
  23831. * Set the source object on the tech, returns a boolean that indicates whether
  23832. * there is a tech that can play the source or not
  23833. *
  23834. * @param {Tech~SourceObject} source
  23835. * The source object to set on the Tech
  23836. *
  23837. * @return {boolean}
  23838. * - True if there is no Tech to playback this source
  23839. * - False otherwise
  23840. *
  23841. * @private
  23842. */
  23843. ;
  23844. _proto.src_ = function src_(source) {
  23845. var _this16 = this;
  23846. var sourceTech = this.selectSource([source]);
  23847. if (!sourceTech) {
  23848. return true;
  23849. }
  23850. if (!titleCaseEquals(sourceTech.tech, this.techName_)) {
  23851. this.changingSrc_ = true; // load this technology with the chosen source
  23852. this.loadTech_(sourceTech.tech, sourceTech.source);
  23853. this.tech_.ready(function () {
  23854. _this16.changingSrc_ = false;
  23855. });
  23856. return false;
  23857. } // wait until the tech is ready to set the source
  23858. // and set it synchronously if possible (#2326)
  23859. this.ready(function () {
  23860. // The setSource tech method was added with source handlers
  23861. // so older techs won't support it
  23862. // We need to check the direct prototype for the case where subclasses
  23863. // of the tech do not support source handlers
  23864. if (this.tech_.constructor.prototype.hasOwnProperty('setSource')) {
  23865. this.techCall_('setSource', source);
  23866. } else {
  23867. this.techCall_('src', source.src);
  23868. }
  23869. this.changingSrc_ = false;
  23870. }, true);
  23871. return false;
  23872. }
  23873. /**
  23874. * Begin loading the src data.
  23875. */
  23876. ;
  23877. _proto.load = function load() {
  23878. this.techCall_('load');
  23879. }
  23880. /**
  23881. * Reset the player. Loads the first tech in the techOrder,
  23882. * removes all the text tracks in the existing `tech`,
  23883. * and calls `reset` on the `tech`.
  23884. */
  23885. ;
  23886. _proto.reset = function reset() {
  23887. var _this17 = this;
  23888. var PromiseClass = this.options_.Promise || window.Promise;
  23889. if (this.paused() || !PromiseClass) {
  23890. this.doReset_();
  23891. } else {
  23892. var playPromise = this.play();
  23893. silencePromise(playPromise.then(function () {
  23894. return _this17.doReset_();
  23895. }));
  23896. }
  23897. };
  23898. _proto.doReset_ = function doReset_() {
  23899. if (this.tech_) {
  23900. this.tech_.clearTracks('text');
  23901. }
  23902. this.resetCache_();
  23903. this.poster('');
  23904. this.loadTech_(this.options_.techOrder[0], null);
  23905. this.techCall_('reset');
  23906. this.resetControlBarUI_();
  23907. if (isEvented(this)) {
  23908. this.trigger('playerreset');
  23909. }
  23910. }
  23911. /**
  23912. * Reset Control Bar's UI by calling sub-methods that reset
  23913. * all of Control Bar's components
  23914. */
  23915. ;
  23916. _proto.resetControlBarUI_ = function resetControlBarUI_() {
  23917. this.resetProgressBar_();
  23918. this.resetPlaybackRate_();
  23919. this.resetVolumeBar_();
  23920. }
  23921. /**
  23922. * Reset tech's progress so progress bar is reset in the UI
  23923. */
  23924. ;
  23925. _proto.resetProgressBar_ = function resetProgressBar_() {
  23926. this.currentTime(0);
  23927. var _ref3 = this.controlBar || {},
  23928. durationDisplay = _ref3.durationDisplay,
  23929. remainingTimeDisplay = _ref3.remainingTimeDisplay;
  23930. if (durationDisplay) {
  23931. durationDisplay.updateContent();
  23932. }
  23933. if (remainingTimeDisplay) {
  23934. remainingTimeDisplay.updateContent();
  23935. }
  23936. }
  23937. /**
  23938. * Reset Playback ratio
  23939. */
  23940. ;
  23941. _proto.resetPlaybackRate_ = function resetPlaybackRate_() {
  23942. this.playbackRate(this.defaultPlaybackRate());
  23943. this.handleTechRateChange_();
  23944. }
  23945. /**
  23946. * Reset Volume bar
  23947. */
  23948. ;
  23949. _proto.resetVolumeBar_ = function resetVolumeBar_() {
  23950. this.volume(1.0);
  23951. this.trigger('volumechange');
  23952. }
  23953. /**
  23954. * Returns all of the current source objects.
  23955. *
  23956. * @return {Tech~SourceObject[]}
  23957. * The current source objects
  23958. */
  23959. ;
  23960. _proto.currentSources = function currentSources() {
  23961. var source = this.currentSource();
  23962. var sources = []; // assume `{}` or `{ src }`
  23963. if (Object.keys(source).length !== 0) {
  23964. sources.push(source);
  23965. }
  23966. return this.cache_.sources || sources;
  23967. }
  23968. /**
  23969. * Returns the current source object.
  23970. *
  23971. * @return {Tech~SourceObject}
  23972. * The current source object
  23973. */
  23974. ;
  23975. _proto.currentSource = function currentSource() {
  23976. return this.cache_.source || {};
  23977. }
  23978. /**
  23979. * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4
  23980. * Can be used in conjunction with `currentType` to assist in rebuilding the current source object.
  23981. *
  23982. * @return {string}
  23983. * The current source
  23984. */
  23985. ;
  23986. _proto.currentSrc = function currentSrc() {
  23987. return this.currentSource() && this.currentSource().src || '';
  23988. }
  23989. /**
  23990. * Get the current source type e.g. video/mp4
  23991. * This can allow you rebuild the current source object so that you could load the same
  23992. * source and tech later
  23993. *
  23994. * @return {string}
  23995. * The source MIME type
  23996. */
  23997. ;
  23998. _proto.currentType = function currentType() {
  23999. return this.currentSource() && this.currentSource().type || '';
  24000. }
  24001. /**
  24002. * Get or set the preload attribute
  24003. *
  24004. * @param {boolean} [value]
  24005. * - true means that we should preload
  24006. * - false means that we should not preload
  24007. *
  24008. * @return {string}
  24009. * The preload attribute value when getting
  24010. */
  24011. ;
  24012. _proto.preload = function preload(value) {
  24013. if (value !== undefined) {
  24014. this.techCall_('setPreload', value);
  24015. this.options_.preload = value;
  24016. return;
  24017. }
  24018. return this.techGet_('preload');
  24019. }
  24020. /**
  24021. * Get or set the autoplay option. When this is a boolean it will
  24022. * modify the attribute on the tech. When this is a string the attribute on
  24023. * the tech will be removed and `Player` will handle autoplay on loadstarts.
  24024. *
  24025. * @param {boolean|string} [value]
  24026. * - true: autoplay using the browser behavior
  24027. * - false: do not autoplay
  24028. * - 'play': call play() on every loadstart
  24029. * - 'muted': call muted() then play() on every loadstart
  24030. * - 'any': call play() on every loadstart. if that fails call muted() then play().
  24031. * - *: values other than those listed here will be set `autoplay` to true
  24032. *
  24033. * @return {boolean|string}
  24034. * The current value of autoplay when getting
  24035. */
  24036. ;
  24037. _proto.autoplay = function autoplay(value) {
  24038. // getter usage
  24039. if (value === undefined) {
  24040. return this.options_.autoplay || false;
  24041. }
  24042. var techAutoplay; // if the value is a valid string set it to that, or normalize `true` to 'play', if need be
  24043. if (typeof value === 'string' && /(any|play|muted)/.test(value) || value === true && this.options_.normalizeAutoplay) {
  24044. this.options_.autoplay = value;
  24045. this.manualAutoplay_(typeof value === 'string' ? value : 'play');
  24046. techAutoplay = false; // any falsy value sets autoplay to false in the browser,
  24047. // lets do the same
  24048. } else if (!value) {
  24049. this.options_.autoplay = false; // any other value (ie truthy) sets autoplay to true
  24050. } else {
  24051. this.options_.autoplay = true;
  24052. }
  24053. techAutoplay = typeof techAutoplay === 'undefined' ? this.options_.autoplay : techAutoplay; // if we don't have a tech then we do not queue up
  24054. // a setAutoplay call on tech ready. We do this because the
  24055. // autoplay option will be passed in the constructor and we
  24056. // do not need to set it twice
  24057. if (this.tech_) {
  24058. this.techCall_('setAutoplay', techAutoplay);
  24059. }
  24060. }
  24061. /**
  24062. * Set or unset the playsinline attribute.
  24063. * Playsinline tells the browser that non-fullscreen playback is preferred.
  24064. *
  24065. * @param {boolean} [value]
  24066. * - true means that we should try to play inline by default
  24067. * - false means that we should use the browser's default playback mode,
  24068. * which in most cases is inline. iOS Safari is a notable exception
  24069. * and plays fullscreen by default.
  24070. *
  24071. * @return {string|Player}
  24072. * - the current value of playsinline
  24073. * - the player when setting
  24074. *
  24075. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  24076. */
  24077. ;
  24078. _proto.playsinline = function playsinline(value) {
  24079. if (value !== undefined) {
  24080. this.techCall_('setPlaysinline', value);
  24081. this.options_.playsinline = value;
  24082. return this;
  24083. }
  24084. return this.techGet_('playsinline');
  24085. }
  24086. /**
  24087. * Get or set the loop attribute on the video element.
  24088. *
  24089. * @param {boolean} [value]
  24090. * - true means that we should loop the video
  24091. * - false means that we should not loop the video
  24092. *
  24093. * @return {boolean}
  24094. * The current value of loop when getting
  24095. */
  24096. ;
  24097. _proto.loop = function loop(value) {
  24098. if (value !== undefined) {
  24099. this.techCall_('setLoop', value);
  24100. this.options_.loop = value;
  24101. return;
  24102. }
  24103. return this.techGet_('loop');
  24104. }
  24105. /**
  24106. * Get or set the poster image source url
  24107. *
  24108. * @fires Player#posterchange
  24109. *
  24110. * @param {string} [src]
  24111. * Poster image source URL
  24112. *
  24113. * @return {string}
  24114. * The current value of poster when getting
  24115. */
  24116. ;
  24117. _proto.poster = function poster(src) {
  24118. if (src === undefined) {
  24119. return this.poster_;
  24120. } // The correct way to remove a poster is to set as an empty string
  24121. // other falsey values will throw errors
  24122. if (!src) {
  24123. src = '';
  24124. }
  24125. if (src === this.poster_) {
  24126. return;
  24127. } // update the internal poster variable
  24128. this.poster_ = src; // update the tech's poster
  24129. this.techCall_('setPoster', src);
  24130. this.isPosterFromTech_ = false; // alert components that the poster has been set
  24131. /**
  24132. * This event fires when the poster image is changed on the player.
  24133. *
  24134. * @event Player#posterchange
  24135. * @type {EventTarget~Event}
  24136. */
  24137. this.trigger('posterchange');
  24138. }
  24139. /**
  24140. * Some techs (e.g. YouTube) can provide a poster source in an
  24141. * asynchronous way. We want the poster component to use this
  24142. * poster source so that it covers up the tech's controls.
  24143. * (YouTube's play button). However we only want to use this
  24144. * source if the player user hasn't set a poster through
  24145. * the normal APIs.
  24146. *
  24147. * @fires Player#posterchange
  24148. * @listens Tech#posterchange
  24149. * @private
  24150. */
  24151. ;
  24152. _proto.handleTechPosterChange_ = function handleTechPosterChange_() {
  24153. if ((!this.poster_ || this.options_.techCanOverridePoster) && this.tech_ && this.tech_.poster) {
  24154. var newPoster = this.tech_.poster() || '';
  24155. if (newPoster !== this.poster_) {
  24156. this.poster_ = newPoster;
  24157. this.isPosterFromTech_ = true; // Let components know the poster has changed
  24158. this.trigger('posterchange');
  24159. }
  24160. }
  24161. }
  24162. /**
  24163. * Get or set whether or not the controls are showing.
  24164. *
  24165. * @fires Player#controlsenabled
  24166. *
  24167. * @param {boolean} [bool]
  24168. * - true to turn controls on
  24169. * - false to turn controls off
  24170. *
  24171. * @return {boolean}
  24172. * The current value of controls when getting
  24173. */
  24174. ;
  24175. _proto.controls = function controls(bool) {
  24176. if (bool === undefined) {
  24177. return !!this.controls_;
  24178. }
  24179. bool = !!bool; // Don't trigger a change event unless it actually changed
  24180. if (this.controls_ === bool) {
  24181. return;
  24182. }
  24183. this.controls_ = bool;
  24184. if (this.usingNativeControls()) {
  24185. this.techCall_('setControls', bool);
  24186. }
  24187. if (this.controls_) {
  24188. this.removeClass('vjs-controls-disabled');
  24189. this.addClass('vjs-controls-enabled');
  24190. /**
  24191. * @event Player#controlsenabled
  24192. * @type {EventTarget~Event}
  24193. */
  24194. this.trigger('controlsenabled');
  24195. if (!this.usingNativeControls()) {
  24196. this.addTechControlsListeners_();
  24197. }
  24198. } else {
  24199. this.removeClass('vjs-controls-enabled');
  24200. this.addClass('vjs-controls-disabled');
  24201. /**
  24202. * @event Player#controlsdisabled
  24203. * @type {EventTarget~Event}
  24204. */
  24205. this.trigger('controlsdisabled');
  24206. if (!this.usingNativeControls()) {
  24207. this.removeTechControlsListeners_();
  24208. }
  24209. }
  24210. }
  24211. /**
  24212. * Toggle native controls on/off. Native controls are the controls built into
  24213. * devices (e.g. default iPhone controls) or other techs
  24214. * (e.g. Vimeo Controls)
  24215. * **This should only be set by the current tech, because only the tech knows
  24216. * if it can support native controls**
  24217. *
  24218. * @fires Player#usingnativecontrols
  24219. * @fires Player#usingcustomcontrols
  24220. *
  24221. * @param {boolean} [bool]
  24222. * - true to turn native controls on
  24223. * - false to turn native controls off
  24224. *
  24225. * @return {boolean}
  24226. * The current value of native controls when getting
  24227. */
  24228. ;
  24229. _proto.usingNativeControls = function usingNativeControls(bool) {
  24230. if (bool === undefined) {
  24231. return !!this.usingNativeControls_;
  24232. }
  24233. bool = !!bool; // Don't trigger a change event unless it actually changed
  24234. if (this.usingNativeControls_ === bool) {
  24235. return;
  24236. }
  24237. this.usingNativeControls_ = bool;
  24238. if (this.usingNativeControls_) {
  24239. this.addClass('vjs-using-native-controls');
  24240. /**
  24241. * player is using the native device controls
  24242. *
  24243. * @event Player#usingnativecontrols
  24244. * @type {EventTarget~Event}
  24245. */
  24246. this.trigger('usingnativecontrols');
  24247. } else {
  24248. this.removeClass('vjs-using-native-controls');
  24249. /**
  24250. * player is using the custom HTML controls
  24251. *
  24252. * @event Player#usingcustomcontrols
  24253. * @type {EventTarget~Event}
  24254. */
  24255. this.trigger('usingcustomcontrols');
  24256. }
  24257. }
  24258. /**
  24259. * Set or get the current MediaError
  24260. *
  24261. * @fires Player#error
  24262. *
  24263. * @param {MediaError|string|number} [err]
  24264. * A MediaError or a string/number to be turned
  24265. * into a MediaError
  24266. *
  24267. * @return {MediaError|null}
  24268. * The current MediaError when getting (or null)
  24269. */
  24270. ;
  24271. _proto.error = function error(err) {
  24272. var _this18 = this;
  24273. if (err === undefined) {
  24274. return this.error_ || null;
  24275. } // allow hooks to modify error object
  24276. hooks('beforeerror').forEach(function (hookFunction) {
  24277. var newErr = hookFunction(_this18, err);
  24278. if (!(isObject$1(newErr) && !Array.isArray(newErr) || typeof newErr === 'string' || typeof newErr === 'number' || newErr === null)) {
  24279. _this18.log.error('please return a value that MediaError expects in beforeerror hooks');
  24280. return;
  24281. }
  24282. err = newErr;
  24283. }); // Suppress the first error message for no compatible source until
  24284. // user interaction
  24285. if (this.options_.suppressNotSupportedError && err && err.code === 4) {
  24286. var triggerSuppressedError = function triggerSuppressedError() {
  24287. this.error(err);
  24288. };
  24289. this.options_.suppressNotSupportedError = false;
  24290. this.any(['click', 'touchstart'], triggerSuppressedError);
  24291. this.one('loadstart', function () {
  24292. this.off(['click', 'touchstart'], triggerSuppressedError);
  24293. });
  24294. return;
  24295. } // restoring to default
  24296. if (err === null) {
  24297. this.error_ = err;
  24298. this.removeClass('vjs-error');
  24299. if (this.errorDisplay) {
  24300. this.errorDisplay.close();
  24301. }
  24302. return;
  24303. }
  24304. this.error_ = new MediaError(err); // add the vjs-error classname to the player
  24305. this.addClass('vjs-error'); // log the name of the error type and any message
  24306. // IE11 logs "[object object]" and required you to expand message to see error object
  24307. log$1.error("(CODE:" + this.error_.code + " " + MediaError.errorTypes[this.error_.code] + ")", this.error_.message, this.error_);
  24308. /**
  24309. * @event Player#error
  24310. * @type {EventTarget~Event}
  24311. */
  24312. this.trigger('error'); // notify hooks of the per player error
  24313. hooks('error').forEach(function (hookFunction) {
  24314. return hookFunction(_this18, _this18.error_);
  24315. });
  24316. return;
  24317. }
  24318. /**
  24319. * Report user activity
  24320. *
  24321. * @param {Object} event
  24322. * Event object
  24323. */
  24324. ;
  24325. _proto.reportUserActivity = function reportUserActivity(event) {
  24326. this.userActivity_ = true;
  24327. }
  24328. /**
  24329. * Get/set if user is active
  24330. *
  24331. * @fires Player#useractive
  24332. * @fires Player#userinactive
  24333. *
  24334. * @param {boolean} [bool]
  24335. * - true if the user is active
  24336. * - false if the user is inactive
  24337. *
  24338. * @return {boolean}
  24339. * The current value of userActive when getting
  24340. */
  24341. ;
  24342. _proto.userActive = function userActive(bool) {
  24343. if (bool === undefined) {
  24344. return this.userActive_;
  24345. }
  24346. bool = !!bool;
  24347. if (bool === this.userActive_) {
  24348. return;
  24349. }
  24350. this.userActive_ = bool;
  24351. if (this.userActive_) {
  24352. this.userActivity_ = true;
  24353. this.removeClass('vjs-user-inactive');
  24354. this.addClass('vjs-user-active');
  24355. /**
  24356. * @event Player#useractive
  24357. * @type {EventTarget~Event}
  24358. */
  24359. this.trigger('useractive');
  24360. return;
  24361. } // Chrome/Safari/IE have bugs where when you change the cursor it can
  24362. // trigger a mousemove event. This causes an issue when you're hiding
  24363. // the cursor when the user is inactive, and a mousemove signals user
  24364. // activity. Making it impossible to go into inactive mode. Specifically
  24365. // this happens in fullscreen when we really need to hide the cursor.
  24366. //
  24367. // When this gets resolved in ALL browsers it can be removed
  24368. // https://code.google.com/p/chromium/issues/detail?id=103041
  24369. if (this.tech_) {
  24370. this.tech_.one('mousemove', function (e) {
  24371. e.stopPropagation();
  24372. e.preventDefault();
  24373. });
  24374. }
  24375. this.userActivity_ = false;
  24376. this.removeClass('vjs-user-active');
  24377. this.addClass('vjs-user-inactive');
  24378. /**
  24379. * @event Player#userinactive
  24380. * @type {EventTarget~Event}
  24381. */
  24382. this.trigger('userinactive');
  24383. }
  24384. /**
  24385. * Listen for user activity based on timeout value
  24386. *
  24387. * @private
  24388. */
  24389. ;
  24390. _proto.listenForUserActivity_ = function listenForUserActivity_() {
  24391. var mouseInProgress;
  24392. var lastMoveX;
  24393. var lastMoveY;
  24394. var handleActivity = bind(this, this.reportUserActivity);
  24395. var handleMouseMove = function handleMouseMove(e) {
  24396. // #1068 - Prevent mousemove spamming
  24397. // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970
  24398. if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) {
  24399. lastMoveX = e.screenX;
  24400. lastMoveY = e.screenY;
  24401. handleActivity();
  24402. }
  24403. };
  24404. var handleMouseDown = function handleMouseDown() {
  24405. handleActivity(); // For as long as the they are touching the device or have their mouse down,
  24406. // we consider them active even if they're not moving their finger or mouse.
  24407. // So we want to continue to update that they are active
  24408. this.clearInterval(mouseInProgress); // Setting userActivity=true now and setting the interval to the same time
  24409. // as the activityCheck interval (250) should ensure we never miss the
  24410. // next activityCheck
  24411. mouseInProgress = this.setInterval(handleActivity, 250);
  24412. };
  24413. var handleMouseUpAndMouseLeave = function handleMouseUpAndMouseLeave(event) {
  24414. handleActivity(); // Stop the interval that maintains activity if the mouse/touch is down
  24415. this.clearInterval(mouseInProgress);
  24416. }; // Any mouse movement will be considered user activity
  24417. this.on('mousedown', handleMouseDown);
  24418. this.on('mousemove', handleMouseMove);
  24419. this.on('mouseup', handleMouseUpAndMouseLeave);
  24420. this.on('mouseleave', handleMouseUpAndMouseLeave);
  24421. var controlBar = this.getChild('controlBar'); // Fixes bug on Android & iOS where when tapping progressBar (when control bar is displayed)
  24422. // controlBar would no longer be hidden by default timeout.
  24423. if (controlBar && !IS_IOS && !IS_ANDROID) {
  24424. controlBar.on('mouseenter', function (event) {
  24425. if (this.player().options_.inactivityTimeout !== 0) {
  24426. this.player().cache_.inactivityTimeout = this.player().options_.inactivityTimeout;
  24427. }
  24428. this.player().options_.inactivityTimeout = 0;
  24429. });
  24430. controlBar.on('mouseleave', function (event) {
  24431. this.player().options_.inactivityTimeout = this.player().cache_.inactivityTimeout;
  24432. });
  24433. } // Listen for keyboard navigation
  24434. // Shouldn't need to use inProgress interval because of key repeat
  24435. this.on('keydown', handleActivity);
  24436. this.on('keyup', handleActivity); // Run an interval every 250 milliseconds instead of stuffing everything into
  24437. // the mousemove/touchmove function itself, to prevent performance degradation.
  24438. // `this.reportUserActivity` simply sets this.userActivity_ to true, which
  24439. // then gets picked up by this loop
  24440. // http://ejohn.org/blog/learning-from-twitter/
  24441. var inactivityTimeout;
  24442. this.setInterval(function () {
  24443. // Check to see if mouse/touch activity has happened
  24444. if (!this.userActivity_) {
  24445. return;
  24446. } // Reset the activity tracker
  24447. this.userActivity_ = false; // If the user state was inactive, set the state to active
  24448. this.userActive(true); // Clear any existing inactivity timeout to start the timer over
  24449. this.clearTimeout(inactivityTimeout);
  24450. var timeout = this.options_.inactivityTimeout;
  24451. if (timeout <= 0) {
  24452. return;
  24453. } // In <timeout> milliseconds, if no more activity has occurred the
  24454. // user will be considered inactive
  24455. inactivityTimeout = this.setTimeout(function () {
  24456. // Protect against the case where the inactivityTimeout can trigger just
  24457. // before the next user activity is picked up by the activity check loop
  24458. // causing a flicker
  24459. if (!this.userActivity_) {
  24460. this.userActive(false);
  24461. }
  24462. }, timeout);
  24463. }, 250);
  24464. }
  24465. /**
  24466. * Gets or sets the current playback rate. A playback rate of
  24467. * 1.0 represents normal speed and 0.5 would indicate half-speed
  24468. * playback, for instance.
  24469. *
  24470. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate
  24471. *
  24472. * @param {number} [rate]
  24473. * New playback rate to set.
  24474. *
  24475. * @return {number}
  24476. * The current playback rate when getting or 1.0
  24477. */
  24478. ;
  24479. _proto.playbackRate = function playbackRate(rate) {
  24480. if (rate !== undefined) {
  24481. // NOTE: this.cache_.lastPlaybackRate is set from the tech handler
  24482. // that is registered above
  24483. this.techCall_('setPlaybackRate', rate);
  24484. return;
  24485. }
  24486. if (this.tech_ && this.tech_.featuresPlaybackRate) {
  24487. return this.cache_.lastPlaybackRate || this.techGet_('playbackRate');
  24488. }
  24489. return 1.0;
  24490. }
  24491. /**
  24492. * Gets or sets the current default playback rate. A default playback rate of
  24493. * 1.0 represents normal speed and 0.5 would indicate half-speed playback, for instance.
  24494. * defaultPlaybackRate will only represent what the initial playbackRate of a video was, not
  24495. * not the current playbackRate.
  24496. *
  24497. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-defaultplaybackrate
  24498. *
  24499. * @param {number} [rate]
  24500. * New default playback rate to set.
  24501. *
  24502. * @return {number|Player}
  24503. * - The default playback rate when getting or 1.0
  24504. * - the player when setting
  24505. */
  24506. ;
  24507. _proto.defaultPlaybackRate = function defaultPlaybackRate(rate) {
  24508. if (rate !== undefined) {
  24509. return this.techCall_('setDefaultPlaybackRate', rate);
  24510. }
  24511. if (this.tech_ && this.tech_.featuresPlaybackRate) {
  24512. return this.techGet_('defaultPlaybackRate');
  24513. }
  24514. return 1.0;
  24515. }
  24516. /**
  24517. * Gets or sets the audio flag
  24518. *
  24519. * @param {boolean} bool
  24520. * - true signals that this is an audio player
  24521. * - false signals that this is not an audio player
  24522. *
  24523. * @return {boolean}
  24524. * The current value of isAudio when getting
  24525. */
  24526. ;
  24527. _proto.isAudio = function isAudio(bool) {
  24528. if (bool !== undefined) {
  24529. this.isAudio_ = !!bool;
  24530. return;
  24531. }
  24532. return !!this.isAudio_;
  24533. };
  24534. _proto.enableAudioOnlyUI_ = function enableAudioOnlyUI_() {
  24535. var _this19 = this;
  24536. // Update styling immediately to show the control bar so we can get its height
  24537. this.addClass('vjs-audio-only-mode');
  24538. var playerChildren = this.children();
  24539. var controlBar = this.getChild('ControlBar');
  24540. var controlBarHeight = controlBar && controlBar.currentHeight(); // Hide all player components except the control bar. Control bar components
  24541. // needed only for video are hidden with CSS
  24542. playerChildren.forEach(function (child) {
  24543. if (child === controlBar) {
  24544. return;
  24545. }
  24546. if (child.el_ && !child.hasClass('vjs-hidden')) {
  24547. child.hide();
  24548. _this19.audioOnlyCache_.hiddenChildren.push(child);
  24549. }
  24550. });
  24551. this.audioOnlyCache_.playerHeight = this.currentHeight(); // Set the player height the same as the control bar
  24552. this.height(controlBarHeight);
  24553. this.trigger('audioonlymodechange');
  24554. };
  24555. _proto.disableAudioOnlyUI_ = function disableAudioOnlyUI_() {
  24556. this.removeClass('vjs-audio-only-mode'); // Show player components that were previously hidden
  24557. this.audioOnlyCache_.hiddenChildren.forEach(function (child) {
  24558. return child.show();
  24559. }); // Reset player height
  24560. this.height(this.audioOnlyCache_.playerHeight);
  24561. this.trigger('audioonlymodechange');
  24562. }
  24563. /**
  24564. * Get the current audioOnlyMode state or set audioOnlyMode to true or false.
  24565. *
  24566. * Setting this to `true` will hide all player components except the control bar,
  24567. * as well as control bar components needed only for video.
  24568. *
  24569. * @param {boolean} [value]
  24570. * The value to set audioOnlyMode to.
  24571. *
  24572. * @return {Promise|boolean}
  24573. * A Promise is returned when setting the state, and a boolean when getting
  24574. * the present state
  24575. */
  24576. ;
  24577. _proto.audioOnlyMode = function audioOnlyMode(value) {
  24578. var _this20 = this;
  24579. if (typeof value !== 'boolean' || value === this.audioOnlyMode_) {
  24580. return this.audioOnlyMode_;
  24581. }
  24582. this.audioOnlyMode_ = value;
  24583. var PromiseClass = this.options_.Promise || window.Promise;
  24584. if (PromiseClass) {
  24585. // Enable Audio Only Mode
  24586. if (value) {
  24587. var exitPromises = []; // Fullscreen and PiP are not supported in audioOnlyMode, so exit if we need to.
  24588. if (this.isInPictureInPicture()) {
  24589. exitPromises.push(this.exitPictureInPicture());
  24590. }
  24591. if (this.isFullscreen()) {
  24592. exitPromises.push(this.exitFullscreen());
  24593. }
  24594. if (this.audioPosterMode()) {
  24595. exitPromises.push(this.audioPosterMode(false));
  24596. }
  24597. return PromiseClass.all(exitPromises).then(function () {
  24598. return _this20.enableAudioOnlyUI_();
  24599. });
  24600. } // Disable Audio Only Mode
  24601. return PromiseClass.resolve().then(function () {
  24602. return _this20.disableAudioOnlyUI_();
  24603. });
  24604. }
  24605. if (value) {
  24606. if (this.isInPictureInPicture()) {
  24607. this.exitPictureInPicture();
  24608. }
  24609. if (this.isFullscreen()) {
  24610. this.exitFullscreen();
  24611. }
  24612. this.enableAudioOnlyUI_();
  24613. } else {
  24614. this.disableAudioOnlyUI_();
  24615. }
  24616. };
  24617. _proto.enablePosterModeUI_ = function enablePosterModeUI_() {
  24618. // Hide the video element and show the poster image to enable posterModeUI
  24619. var tech = this.tech_ && this.tech_;
  24620. tech.hide();
  24621. this.addClass('vjs-audio-poster-mode');
  24622. this.trigger('audiopostermodechange');
  24623. };
  24624. _proto.disablePosterModeUI_ = function disablePosterModeUI_() {
  24625. // Show the video element and hide the poster image to disable posterModeUI
  24626. var tech = this.tech_ && this.tech_;
  24627. tech.show();
  24628. this.removeClass('vjs-audio-poster-mode');
  24629. this.trigger('audiopostermodechange');
  24630. }
  24631. /**
  24632. * Get the current audioPosterMode state or set audioPosterMode to true or false
  24633. *
  24634. * @param {boolean} [value]
  24635. * The value to set audioPosterMode to.
  24636. *
  24637. * @return {Promise|boolean}
  24638. * A Promise is returned when setting the state, and a boolean when getting
  24639. * the present state
  24640. */
  24641. ;
  24642. _proto.audioPosterMode = function audioPosterMode(value) {
  24643. var _this21 = this;
  24644. if (typeof value !== 'boolean' || value === this.audioPosterMode_) {
  24645. return this.audioPosterMode_;
  24646. }
  24647. this.audioPosterMode_ = value;
  24648. var PromiseClass = this.options_.Promise || window.Promise;
  24649. if (PromiseClass) {
  24650. if (value) {
  24651. if (this.audioOnlyMode()) {
  24652. var audioOnlyModePromise = this.audioOnlyMode(false);
  24653. return audioOnlyModePromise.then(function () {
  24654. // enable audio poster mode after audio only mode is disabled
  24655. _this21.enablePosterModeUI_();
  24656. });
  24657. }
  24658. return PromiseClass.resolve().then(function () {
  24659. // enable audio poster mode
  24660. _this21.enablePosterModeUI_();
  24661. });
  24662. }
  24663. return PromiseClass.resolve().then(function () {
  24664. // disable audio poster mode
  24665. _this21.disablePosterModeUI_();
  24666. });
  24667. }
  24668. if (value) {
  24669. if (this.audioOnlyMode()) {
  24670. this.audioOnlyMode(false);
  24671. }
  24672. this.enablePosterModeUI_();
  24673. return;
  24674. }
  24675. this.disablePosterModeUI_();
  24676. }
  24677. /**
  24678. * A helper method for adding a {@link TextTrack} to our
  24679. * {@link TextTrackList}.
  24680. *
  24681. * In addition to the W3C settings we allow adding additional info through options.
  24682. *
  24683. * @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack
  24684. *
  24685. * @param {string} [kind]
  24686. * the kind of TextTrack you are adding
  24687. *
  24688. * @param {string} [label]
  24689. * the label to give the TextTrack label
  24690. *
  24691. * @param {string} [language]
  24692. * the language to set on the TextTrack
  24693. *
  24694. * @return {TextTrack|undefined}
  24695. * the TextTrack that was added or undefined
  24696. * if there is no tech
  24697. */
  24698. ;
  24699. _proto.addTextTrack = function addTextTrack(kind, label, language) {
  24700. if (this.tech_) {
  24701. return this.tech_.addTextTrack(kind, label, language);
  24702. }
  24703. }
  24704. /**
  24705. * Create a remote {@link TextTrack} and an {@link HTMLTrackElement}.
  24706. * When manualCleanup is set to false, the track will be automatically removed
  24707. * on source changes.
  24708. *
  24709. * @param {Object} options
  24710. * Options to pass to {@link HTMLTrackElement} during creation. See
  24711. * {@link HTMLTrackElement} for object properties that you should use.
  24712. *
  24713. * @param {boolean} [manualCleanup=true] if set to false, the TextTrack will be
  24714. * removed on a source change
  24715. *
  24716. * @return {HtmlTrackElement}
  24717. * the HTMLTrackElement that was created and added
  24718. * to the HtmlTrackElementList and the remote
  24719. * TextTrackList
  24720. *
  24721. * @deprecated The default value of the "manualCleanup" parameter will default
  24722. * to "false" in upcoming versions of Video.js
  24723. */
  24724. ;
  24725. _proto.addRemoteTextTrack = function addRemoteTextTrack(options, manualCleanup) {
  24726. if (this.tech_) {
  24727. return this.tech_.addRemoteTextTrack(options, manualCleanup);
  24728. }
  24729. }
  24730. /**
  24731. * Remove a remote {@link TextTrack} from the respective
  24732. * {@link TextTrackList} and {@link HtmlTrackElementList}.
  24733. *
  24734. * @param {Object} track
  24735. * Remote {@link TextTrack} to remove
  24736. *
  24737. * @return {undefined}
  24738. * does not return anything
  24739. */
  24740. ;
  24741. _proto.removeRemoteTextTrack = function removeRemoteTextTrack(obj) {
  24742. if (obj === void 0) {
  24743. obj = {};
  24744. }
  24745. var _obj = obj,
  24746. track = _obj.track;
  24747. if (!track) {
  24748. track = obj;
  24749. } // destructure the input into an object with a track argument, defaulting to arguments[0]
  24750. // default the whole argument to an empty object if nothing was passed in
  24751. if (this.tech_) {
  24752. return this.tech_.removeRemoteTextTrack(track);
  24753. }
  24754. }
  24755. /**
  24756. * Gets available media playback quality metrics as specified by the W3C's Media
  24757. * Playback Quality API.
  24758. *
  24759. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  24760. *
  24761. * @return {Object|undefined}
  24762. * An object with supported media playback quality metrics or undefined if there
  24763. * is no tech or the tech does not support it.
  24764. */
  24765. ;
  24766. _proto.getVideoPlaybackQuality = function getVideoPlaybackQuality() {
  24767. return this.techGet_('getVideoPlaybackQuality');
  24768. }
  24769. /**
  24770. * Get video width
  24771. *
  24772. * @return {number}
  24773. * current video width
  24774. */
  24775. ;
  24776. _proto.videoWidth = function videoWidth() {
  24777. return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0;
  24778. }
  24779. /**
  24780. * Get video height
  24781. *
  24782. * @return {number}
  24783. * current video height
  24784. */
  24785. ;
  24786. _proto.videoHeight = function videoHeight() {
  24787. return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0;
  24788. }
  24789. /**
  24790. * The player's language code.
  24791. *
  24792. * Changing the language will trigger
  24793. * [languagechange]{@link Player#event:languagechange}
  24794. * which Components can use to update control text.
  24795. * ClickableComponent will update its control text by default on
  24796. * [languagechange]{@link Player#event:languagechange}.
  24797. *
  24798. * @fires Player#languagechange
  24799. *
  24800. * @param {string} [code]
  24801. * the language code to set the player to
  24802. *
  24803. * @return {string}
  24804. * The current language code when getting
  24805. */
  24806. ;
  24807. _proto.language = function language(code) {
  24808. if (code === undefined) {
  24809. return this.language_;
  24810. }
  24811. if (this.language_ !== String(code).toLowerCase()) {
  24812. this.language_ = String(code).toLowerCase(); // during first init, it's possible some things won't be evented
  24813. if (isEvented(this)) {
  24814. /**
  24815. * fires when the player language change
  24816. *
  24817. * @event Player#languagechange
  24818. * @type {EventTarget~Event}
  24819. */
  24820. this.trigger('languagechange');
  24821. }
  24822. }
  24823. }
  24824. /**
  24825. * Get the player's language dictionary
  24826. * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time
  24827. * Languages specified directly in the player options have precedence
  24828. *
  24829. * @return {Array}
  24830. * An array of of supported languages
  24831. */
  24832. ;
  24833. _proto.languages = function languages() {
  24834. return mergeOptions$3(Player.prototype.options_.languages, this.languages_);
  24835. }
  24836. /**
  24837. * returns a JavaScript object reperesenting the current track
  24838. * information. **DOES not return it as JSON**
  24839. *
  24840. * @return {Object}
  24841. * Object representing the current of track info
  24842. */
  24843. ;
  24844. _proto.toJSON = function toJSON() {
  24845. var options = mergeOptions$3(this.options_);
  24846. var tracks = options.tracks;
  24847. options.tracks = [];
  24848. for (var i = 0; i < tracks.length; i++) {
  24849. var track = tracks[i]; // deep merge tracks and null out player so no circular references
  24850. track = mergeOptions$3(track);
  24851. track.player = undefined;
  24852. options.tracks[i] = track;
  24853. }
  24854. return options;
  24855. }
  24856. /**
  24857. * Creates a simple modal dialog (an instance of the {@link ModalDialog}
  24858. * component) that immediately overlays the player with arbitrary
  24859. * content and removes itself when closed.
  24860. *
  24861. * @param {string|Function|Element|Array|null} content
  24862. * Same as {@link ModalDialog#content}'s param of the same name.
  24863. * The most straight-forward usage is to provide a string or DOM
  24864. * element.
  24865. *
  24866. * @param {Object} [options]
  24867. * Extra options which will be passed on to the {@link ModalDialog}.
  24868. *
  24869. * @return {ModalDialog}
  24870. * the {@link ModalDialog} that was created
  24871. */
  24872. ;
  24873. _proto.createModal = function createModal(content, options) {
  24874. var _this22 = this;
  24875. options = options || {};
  24876. options.content = content || '';
  24877. var modal = new ModalDialog(this, options);
  24878. this.addChild(modal);
  24879. modal.on('dispose', function () {
  24880. _this22.removeChild(modal);
  24881. });
  24882. modal.open();
  24883. return modal;
  24884. }
  24885. /**
  24886. * Change breakpoint classes when the player resizes.
  24887. *
  24888. * @private
  24889. */
  24890. ;
  24891. _proto.updateCurrentBreakpoint_ = function updateCurrentBreakpoint_() {
  24892. if (!this.responsive()) {
  24893. return;
  24894. }
  24895. var currentBreakpoint = this.currentBreakpoint();
  24896. var currentWidth = this.currentWidth();
  24897. for (var i = 0; i < BREAKPOINT_ORDER.length; i++) {
  24898. var candidateBreakpoint = BREAKPOINT_ORDER[i];
  24899. var maxWidth = this.breakpoints_[candidateBreakpoint];
  24900. if (currentWidth <= maxWidth) {
  24901. // The current breakpoint did not change, nothing to do.
  24902. if (currentBreakpoint === candidateBreakpoint) {
  24903. return;
  24904. } // Only remove a class if there is a current breakpoint.
  24905. if (currentBreakpoint) {
  24906. this.removeClass(BREAKPOINT_CLASSES[currentBreakpoint]);
  24907. }
  24908. this.addClass(BREAKPOINT_CLASSES[candidateBreakpoint]);
  24909. this.breakpoint_ = candidateBreakpoint;
  24910. break;
  24911. }
  24912. }
  24913. }
  24914. /**
  24915. * Removes the current breakpoint.
  24916. *
  24917. * @private
  24918. */
  24919. ;
  24920. _proto.removeCurrentBreakpoint_ = function removeCurrentBreakpoint_() {
  24921. var className = this.currentBreakpointClass();
  24922. this.breakpoint_ = '';
  24923. if (className) {
  24924. this.removeClass(className);
  24925. }
  24926. }
  24927. /**
  24928. * Get or set breakpoints on the player.
  24929. *
  24930. * Calling this method with an object or `true` will remove any previous
  24931. * custom breakpoints and start from the defaults again.
  24932. *
  24933. * @param {Object|boolean} [breakpoints]
  24934. * If an object is given, it can be used to provide custom
  24935. * breakpoints. If `true` is given, will set default breakpoints.
  24936. * If this argument is not given, will simply return the current
  24937. * breakpoints.
  24938. *
  24939. * @param {number} [breakpoints.tiny]
  24940. * The maximum width for the "vjs-layout-tiny" class.
  24941. *
  24942. * @param {number} [breakpoints.xsmall]
  24943. * The maximum width for the "vjs-layout-x-small" class.
  24944. *
  24945. * @param {number} [breakpoints.small]
  24946. * The maximum width for the "vjs-layout-small" class.
  24947. *
  24948. * @param {number} [breakpoints.medium]
  24949. * The maximum width for the "vjs-layout-medium" class.
  24950. *
  24951. * @param {number} [breakpoints.large]
  24952. * The maximum width for the "vjs-layout-large" class.
  24953. *
  24954. * @param {number} [breakpoints.xlarge]
  24955. * The maximum width for the "vjs-layout-x-large" class.
  24956. *
  24957. * @param {number} [breakpoints.huge]
  24958. * The maximum width for the "vjs-layout-huge" class.
  24959. *
  24960. * @return {Object}
  24961. * An object mapping breakpoint names to maximum width values.
  24962. */
  24963. ;
  24964. _proto.breakpoints = function breakpoints(_breakpoints) {
  24965. // Used as a getter.
  24966. if (_breakpoints === undefined) {
  24967. return assign$1(this.breakpoints_);
  24968. }
  24969. this.breakpoint_ = '';
  24970. this.breakpoints_ = assign$1({}, DEFAULT_BREAKPOINTS, _breakpoints); // When breakpoint definitions change, we need to update the currently
  24971. // selected breakpoint.
  24972. this.updateCurrentBreakpoint_(); // Clone the breakpoints before returning.
  24973. return assign$1(this.breakpoints_);
  24974. }
  24975. /**
  24976. * Get or set a flag indicating whether or not this player should adjust
  24977. * its UI based on its dimensions.
  24978. *
  24979. * @param {boolean} value
  24980. * Should be `true` if the player should adjust its UI based on its
  24981. * dimensions; otherwise, should be `false`.
  24982. *
  24983. * @return {boolean}
  24984. * Will be `true` if this player should adjust its UI based on its
  24985. * dimensions; otherwise, will be `false`.
  24986. */
  24987. ;
  24988. _proto.responsive = function responsive(value) {
  24989. // Used as a getter.
  24990. if (value === undefined) {
  24991. return this.responsive_;
  24992. }
  24993. value = Boolean(value);
  24994. var current = this.responsive_; // Nothing changed.
  24995. if (value === current) {
  24996. return;
  24997. } // The value actually changed, set it.
  24998. this.responsive_ = value; // Start listening for breakpoints and set the initial breakpoint if the
  24999. // player is now responsive.
  25000. if (value) {
  25001. this.on('playerresize', this.boundUpdateCurrentBreakpoint_);
  25002. this.updateCurrentBreakpoint_(); // Stop listening for breakpoints if the player is no longer responsive.
  25003. } else {
  25004. this.off('playerresize', this.boundUpdateCurrentBreakpoint_);
  25005. this.removeCurrentBreakpoint_();
  25006. }
  25007. return value;
  25008. }
  25009. /**
  25010. * Get current breakpoint name, if any.
  25011. *
  25012. * @return {string}
  25013. * If there is currently a breakpoint set, returns a the key from the
  25014. * breakpoints object matching it. Otherwise, returns an empty string.
  25015. */
  25016. ;
  25017. _proto.currentBreakpoint = function currentBreakpoint() {
  25018. return this.breakpoint_;
  25019. }
  25020. /**
  25021. * Get the current breakpoint class name.
  25022. *
  25023. * @return {string}
  25024. * The matching class name (e.g. `"vjs-layout-tiny"` or
  25025. * `"vjs-layout-large"`) for the current breakpoint. Empty string if
  25026. * there is no current breakpoint.
  25027. */
  25028. ;
  25029. _proto.currentBreakpointClass = function currentBreakpointClass() {
  25030. return BREAKPOINT_CLASSES[this.breakpoint_] || '';
  25031. }
  25032. /**
  25033. * An object that describes a single piece of media.
  25034. *
  25035. * Properties that are not part of this type description will be retained; so,
  25036. * this can be viewed as a generic metadata storage mechanism as well.
  25037. *
  25038. * @see {@link https://wicg.github.io/mediasession/#the-mediametadata-interface}
  25039. * @typedef {Object} Player~MediaObject
  25040. *
  25041. * @property {string} [album]
  25042. * Unused, except if this object is passed to the `MediaSession`
  25043. * API.
  25044. *
  25045. * @property {string} [artist]
  25046. * Unused, except if this object is passed to the `MediaSession`
  25047. * API.
  25048. *
  25049. * @property {Object[]} [artwork]
  25050. * Unused, except if this object is passed to the `MediaSession`
  25051. * API. If not specified, will be populated via the `poster`, if
  25052. * available.
  25053. *
  25054. * @property {string} [poster]
  25055. * URL to an image that will display before playback.
  25056. *
  25057. * @property {Tech~SourceObject|Tech~SourceObject[]|string} [src]
  25058. * A single source object, an array of source objects, or a string
  25059. * referencing a URL to a media source. It is _highly recommended_
  25060. * that an object or array of objects is used here, so that source
  25061. * selection algorithms can take the `type` into account.
  25062. *
  25063. * @property {string} [title]
  25064. * Unused, except if this object is passed to the `MediaSession`
  25065. * API.
  25066. *
  25067. * @property {Object[]} [textTracks]
  25068. * An array of objects to be used to create text tracks, following
  25069. * the {@link https://www.w3.org/TR/html50/embedded-content-0.html#the-track-element|native track element format}.
  25070. * For ease of removal, these will be created as "remote" text
  25071. * tracks and set to automatically clean up on source changes.
  25072. *
  25073. * These objects may have properties like `src`, `kind`, `label`,
  25074. * and `language`, see {@link Tech#createRemoteTextTrack}.
  25075. */
  25076. /**
  25077. * Populate the player using a {@link Player~MediaObject|MediaObject}.
  25078. *
  25079. * @param {Player~MediaObject} media
  25080. * A media object.
  25081. *
  25082. * @param {Function} ready
  25083. * A callback to be called when the player is ready.
  25084. */
  25085. ;
  25086. _proto.loadMedia = function loadMedia(media, ready) {
  25087. var _this23 = this;
  25088. if (!media || typeof media !== 'object') {
  25089. return;
  25090. }
  25091. this.reset(); // Clone the media object so it cannot be mutated from outside.
  25092. this.cache_.media = mergeOptions$3(media);
  25093. var _this$cache_$media = this.cache_.media,
  25094. artwork = _this$cache_$media.artwork,
  25095. poster = _this$cache_$media.poster,
  25096. src = _this$cache_$media.src,
  25097. textTracks = _this$cache_$media.textTracks; // If `artwork` is not given, create it using `poster`.
  25098. if (!artwork && poster) {
  25099. this.cache_.media.artwork = [{
  25100. src: poster,
  25101. type: getMimetype(poster)
  25102. }];
  25103. }
  25104. if (src) {
  25105. this.src(src);
  25106. }
  25107. if (poster) {
  25108. this.poster(poster);
  25109. }
  25110. if (Array.isArray(textTracks)) {
  25111. textTracks.forEach(function (tt) {
  25112. return _this23.addRemoteTextTrack(tt, false);
  25113. });
  25114. }
  25115. this.ready(ready);
  25116. }
  25117. /**
  25118. * Get a clone of the current {@link Player~MediaObject} for this player.
  25119. *
  25120. * If the `loadMedia` method has not been used, will attempt to return a
  25121. * {@link Player~MediaObject} based on the current state of the player.
  25122. *
  25123. * @return {Player~MediaObject}
  25124. */
  25125. ;
  25126. _proto.getMedia = function getMedia() {
  25127. if (!this.cache_.media) {
  25128. var poster = this.poster();
  25129. var src = this.currentSources();
  25130. var textTracks = Array.prototype.map.call(this.remoteTextTracks(), function (tt) {
  25131. return {
  25132. kind: tt.kind,
  25133. label: tt.label,
  25134. language: tt.language,
  25135. src: tt.src
  25136. };
  25137. });
  25138. var media = {
  25139. src: src,
  25140. textTracks: textTracks
  25141. };
  25142. if (poster) {
  25143. media.poster = poster;
  25144. media.artwork = [{
  25145. src: media.poster,
  25146. type: getMimetype(media.poster)
  25147. }];
  25148. }
  25149. return media;
  25150. }
  25151. return mergeOptions$3(this.cache_.media);
  25152. }
  25153. /**
  25154. * Gets tag settings
  25155. *
  25156. * @param {Element} tag
  25157. * The player tag
  25158. *
  25159. * @return {Object}
  25160. * An object containing all of the settings
  25161. * for a player tag
  25162. */
  25163. ;
  25164. Player.getTagSettings = function getTagSettings(tag) {
  25165. var baseOptions = {
  25166. sources: [],
  25167. tracks: []
  25168. };
  25169. var tagOptions = getAttributes(tag);
  25170. var dataSetup = tagOptions['data-setup'];
  25171. if (hasClass(tag, 'vjs-fill')) {
  25172. tagOptions.fill = true;
  25173. }
  25174. if (hasClass(tag, 'vjs-fluid')) {
  25175. tagOptions.fluid = true;
  25176. } // Check if data-setup attr exists.
  25177. if (dataSetup !== null) {
  25178. // Parse options JSON
  25179. // If empty string, make it a parsable json object.
  25180. var _safeParseTuple = tuple(dataSetup || '{}'),
  25181. err = _safeParseTuple[0],
  25182. data = _safeParseTuple[1];
  25183. if (err) {
  25184. log$1.error(err);
  25185. }
  25186. assign$1(tagOptions, data);
  25187. }
  25188. assign$1(baseOptions, tagOptions); // Get tag children settings
  25189. if (tag.hasChildNodes()) {
  25190. var children = tag.childNodes;
  25191. for (var i = 0, j = children.length; i < j; i++) {
  25192. var child = children[i]; // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/
  25193. var childName = child.nodeName.toLowerCase();
  25194. if (childName === 'source') {
  25195. baseOptions.sources.push(getAttributes(child));
  25196. } else if (childName === 'track') {
  25197. baseOptions.tracks.push(getAttributes(child));
  25198. }
  25199. }
  25200. }
  25201. return baseOptions;
  25202. }
  25203. /**
  25204. * Determine whether or not flexbox is supported
  25205. *
  25206. * @return {boolean}
  25207. * - true if flexbox is supported
  25208. * - false if flexbox is not supported
  25209. */
  25210. ;
  25211. _proto.flexNotSupported_ = function flexNotSupported_() {
  25212. var elem = document.createElement('i'); // Note: We don't actually use flexBasis (or flexOrder), but it's one of the more
  25213. // common flex features that we can rely on when checking for flex support.
  25214. return !('flexBasis' in elem.style || 'webkitFlexBasis' in elem.style || 'mozFlexBasis' in elem.style || 'msFlexBasis' in elem.style || // IE10-specific (2012 flex spec), available for completeness
  25215. 'msFlexOrder' in elem.style);
  25216. }
  25217. /**
  25218. * Set debug mode to enable/disable logs at info level.
  25219. *
  25220. * @param {boolean} enabled
  25221. * @fires Player#debugon
  25222. * @fires Player#debugoff
  25223. */
  25224. ;
  25225. _proto.debug = function debug(enabled) {
  25226. if (enabled === undefined) {
  25227. return this.debugEnabled_;
  25228. }
  25229. if (enabled) {
  25230. this.trigger('debugon');
  25231. this.previousLogLevel_ = this.log.level;
  25232. this.log.level('debug');
  25233. this.debugEnabled_ = true;
  25234. } else {
  25235. this.trigger('debugoff');
  25236. this.log.level(this.previousLogLevel_);
  25237. this.previousLogLevel_ = undefined;
  25238. this.debugEnabled_ = false;
  25239. }
  25240. }
  25241. /**
  25242. * Set or get current playback rates.
  25243. * Takes an array and updates the playback rates menu with the new items.
  25244. * Pass in an empty array to hide the menu.
  25245. * Values other than arrays are ignored.
  25246. *
  25247. * @fires Player#playbackrateschange
  25248. * @param {number[]} newRates
  25249. * The new rates that the playback rates menu should update to.
  25250. * An empty array will hide the menu
  25251. * @return {number[]} When used as a getter will return the current playback rates
  25252. */
  25253. ;
  25254. _proto.playbackRates = function playbackRates(newRates) {
  25255. if (newRates === undefined) {
  25256. return this.cache_.playbackRates;
  25257. } // ignore any value that isn't an array
  25258. if (!Array.isArray(newRates)) {
  25259. return;
  25260. } // ignore any arrays that don't only contain numbers
  25261. if (!newRates.every(function (rate) {
  25262. return typeof rate === 'number';
  25263. })) {
  25264. return;
  25265. }
  25266. this.cache_.playbackRates = newRates;
  25267. /**
  25268. * fires when the playback rates in a player are changed
  25269. *
  25270. * @event Player#playbackrateschange
  25271. * @type {EventTarget~Event}
  25272. */
  25273. this.trigger('playbackrateschange');
  25274. };
  25275. return Player;
  25276. }(Component$1);
  25277. /**
  25278. * Get the {@link VideoTrackList}
  25279. * @link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist
  25280. *
  25281. * @return {VideoTrackList}
  25282. * the current video track list
  25283. *
  25284. * @method Player.prototype.videoTracks
  25285. */
  25286. /**
  25287. * Get the {@link AudioTrackList}
  25288. * @link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist
  25289. *
  25290. * @return {AudioTrackList}
  25291. * the current audio track list
  25292. *
  25293. * @method Player.prototype.audioTracks
  25294. */
  25295. /**
  25296. * Get the {@link TextTrackList}
  25297. *
  25298. * @link http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks
  25299. *
  25300. * @return {TextTrackList}
  25301. * the current text track list
  25302. *
  25303. * @method Player.prototype.textTracks
  25304. */
  25305. /**
  25306. * Get the remote {@link TextTrackList}
  25307. *
  25308. * @return {TextTrackList}
  25309. * The current remote text track list
  25310. *
  25311. * @method Player.prototype.remoteTextTracks
  25312. */
  25313. /**
  25314. * Get the remote {@link HtmlTrackElementList} tracks.
  25315. *
  25316. * @return {HtmlTrackElementList}
  25317. * The current remote text track element list
  25318. *
  25319. * @method Player.prototype.remoteTextTrackEls
  25320. */
  25321. ALL.names.forEach(function (name) {
  25322. var props = ALL[name];
  25323. Player.prototype[props.getterName] = function () {
  25324. if (this.tech_) {
  25325. return this.tech_[props.getterName]();
  25326. } // if we have not yet loadTech_, we create {video,audio,text}Tracks_
  25327. // these will be passed to the tech during loading
  25328. this[props.privateName] = this[props.privateName] || new props.ListClass();
  25329. return this[props.privateName];
  25330. };
  25331. });
  25332. /**
  25333. * Get or set the `Player`'s crossorigin option. For the HTML5 player, this
  25334. * sets the `crossOrigin` property on the `<video>` tag to control the CORS
  25335. * behavior.
  25336. *
  25337. * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
  25338. *
  25339. * @param {string} [value]
  25340. * The value to set the `Player`'s crossorigin to. If an argument is
  25341. * given, must be one of `anonymous` or `use-credentials`.
  25342. *
  25343. * @return {string|undefined}
  25344. * - The current crossorigin value of the `Player` when getting.
  25345. * - undefined when setting
  25346. */
  25347. Player.prototype.crossorigin = Player.prototype.crossOrigin;
  25348. /**
  25349. * Global enumeration of players.
  25350. *
  25351. * The keys are the player IDs and the values are either the {@link Player}
  25352. * instance or `null` for disposed players.
  25353. *
  25354. * @type {Object}
  25355. */
  25356. Player.players = {};
  25357. var navigator = window.navigator;
  25358. /*
  25359. * Player instance options, surfaced using options
  25360. * options = Player.prototype.options_
  25361. * Make changes in options, not here.
  25362. *
  25363. * @type {Object}
  25364. * @private
  25365. */
  25366. Player.prototype.options_ = {
  25367. // Default order of fallback technology
  25368. techOrder: Tech.defaultTechOrder_,
  25369. html5: {},
  25370. // default inactivity timeout
  25371. inactivityTimeout: 2000,
  25372. // default playback rates
  25373. playbackRates: [],
  25374. // Add playback rate selection by adding rates
  25375. // 'playbackRates': [0.5, 1, 1.5, 2],
  25376. liveui: false,
  25377. // Included control sets
  25378. children: ['mediaLoader', 'posterImage', 'textTrackDisplay', 'loadingSpinner', 'bigPlayButton', 'liveTracker', 'controlBar', 'errorDisplay', 'textTrackSettings', 'resizeManager'],
  25379. language: navigator && (navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language) || 'en',
  25380. // locales and their language translations
  25381. languages: {},
  25382. // Default message to show when a video cannot be played.
  25383. notSupportedMessage: 'No compatible source was found for this media.',
  25384. normalizeAutoplay: false,
  25385. fullscreen: {
  25386. options: {
  25387. navigationUI: 'hide'
  25388. }
  25389. },
  25390. breakpoints: {},
  25391. responsive: false,
  25392. audioOnlyMode: false,
  25393. audioPosterMode: false
  25394. };
  25395. [
  25396. /**
  25397. * Returns whether or not the player is in the "ended" state.
  25398. *
  25399. * @return {Boolean} True if the player is in the ended state, false if not.
  25400. * @method Player#ended
  25401. */
  25402. 'ended',
  25403. /**
  25404. * Returns whether or not the player is in the "seeking" state.
  25405. *
  25406. * @return {Boolean} True if the player is in the seeking state, false if not.
  25407. * @method Player#seeking
  25408. */
  25409. 'seeking',
  25410. /**
  25411. * Returns the TimeRanges of the media that are currently available
  25412. * for seeking to.
  25413. *
  25414. * @return {TimeRanges} the seekable intervals of the media timeline
  25415. * @method Player#seekable
  25416. */
  25417. 'seekable',
  25418. /**
  25419. * Returns the current state of network activity for the element, from
  25420. * the codes in the list below.
  25421. * - NETWORK_EMPTY (numeric value 0)
  25422. * The element has not yet been initialised. All attributes are in
  25423. * their initial states.
  25424. * - NETWORK_IDLE (numeric value 1)
  25425. * The element's resource selection algorithm is active and has
  25426. * selected a resource, but it is not actually using the network at
  25427. * this time.
  25428. * - NETWORK_LOADING (numeric value 2)
  25429. * The user agent is actively trying to download data.
  25430. * - NETWORK_NO_SOURCE (numeric value 3)
  25431. * The element's resource selection algorithm is active, but it has
  25432. * not yet found a resource to use.
  25433. *
  25434. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states
  25435. * @return {number} the current network activity state
  25436. * @method Player#networkState
  25437. */
  25438. 'networkState',
  25439. /**
  25440. * Returns a value that expresses the current state of the element
  25441. * with respect to rendering the current playback position, from the
  25442. * codes in the list below.
  25443. * - HAVE_NOTHING (numeric value 0)
  25444. * No information regarding the media resource is available.
  25445. * - HAVE_METADATA (numeric value 1)
  25446. * Enough of the resource has been obtained that the duration of the
  25447. * resource is available.
  25448. * - HAVE_CURRENT_DATA (numeric value 2)
  25449. * Data for the immediate current playback position is available.
  25450. * - HAVE_FUTURE_DATA (numeric value 3)
  25451. * Data for the immediate current playback position is available, as
  25452. * well as enough data for the user agent to advance the current
  25453. * playback position in the direction of playback.
  25454. * - HAVE_ENOUGH_DATA (numeric value 4)
  25455. * The user agent estimates that enough data is available for
  25456. * playback to proceed uninterrupted.
  25457. *
  25458. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate
  25459. * @return {number} the current playback rendering state
  25460. * @method Player#readyState
  25461. */
  25462. 'readyState'].forEach(function (fn) {
  25463. Player.prototype[fn] = function () {
  25464. return this.techGet_(fn);
  25465. };
  25466. });
  25467. TECH_EVENTS_RETRIGGER.forEach(function (event) {
  25468. Player.prototype["handleTech" + toTitleCase$1(event) + "_"] = function () {
  25469. return this.trigger(event);
  25470. };
  25471. });
  25472. /**
  25473. * Fired when the player has initial duration and dimension information
  25474. *
  25475. * @event Player#loadedmetadata
  25476. * @type {EventTarget~Event}
  25477. */
  25478. /**
  25479. * Fired when the player has downloaded data at the current playback position
  25480. *
  25481. * @event Player#loadeddata
  25482. * @type {EventTarget~Event}
  25483. */
  25484. /**
  25485. * Fired when the current playback position has changed *
  25486. * During playback this is fired every 15-250 milliseconds, depending on the
  25487. * playback technology in use.
  25488. *
  25489. * @event Player#timeupdate
  25490. * @type {EventTarget~Event}
  25491. */
  25492. /**
  25493. * Fired when the volume changes
  25494. *
  25495. * @event Player#volumechange
  25496. * @type {EventTarget~Event}
  25497. */
  25498. /**
  25499. * Reports whether or not a player has a plugin available.
  25500. *
  25501. * This does not report whether or not the plugin has ever been initialized
  25502. * on this player. For that, [usingPlugin]{@link Player#usingPlugin}.
  25503. *
  25504. * @method Player#hasPlugin
  25505. * @param {string} name
  25506. * The name of a plugin.
  25507. *
  25508. * @return {boolean}
  25509. * Whether or not this player has the requested plugin available.
  25510. */
  25511. /**
  25512. * Reports whether or not a player is using a plugin by name.
  25513. *
  25514. * For basic plugins, this only reports whether the plugin has _ever_ been
  25515. * initialized on this player.
  25516. *
  25517. * @method Player#usingPlugin
  25518. * @param {string} name
  25519. * The name of a plugin.
  25520. *
  25521. * @return {boolean}
  25522. * Whether or not this player is using the requested plugin.
  25523. */
  25524. Component$1.registerComponent('Player', Player);
  25525. var setPrototypeOf = createCommonjsModule(function (module) {
  25526. function _setPrototypeOf(o, p) {
  25527. module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  25528. o.__proto__ = p;
  25529. return o;
  25530. };
  25531. return _setPrototypeOf(o, p);
  25532. }
  25533. module.exports = _setPrototypeOf;
  25534. });
  25535. function _isNativeReflectConstruct() {
  25536. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  25537. if (Reflect.construct.sham) return false;
  25538. if (typeof Proxy === "function") return true;
  25539. try {
  25540. Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
  25541. return true;
  25542. } catch (e) {
  25543. return false;
  25544. }
  25545. }
  25546. var isNativeReflectConstruct = _isNativeReflectConstruct;
  25547. var construct = createCommonjsModule(function (module) {
  25548. function _construct(Parent, args, Class) {
  25549. if (isNativeReflectConstruct()) {
  25550. module.exports = _construct = Reflect.construct;
  25551. } else {
  25552. module.exports = _construct = function _construct(Parent, args, Class) {
  25553. var a = [null];
  25554. a.push.apply(a, args);
  25555. var Constructor = Function.bind.apply(Parent, a);
  25556. var instance = new Constructor();
  25557. if (Class) setPrototypeOf(instance, Class.prototype);
  25558. return instance;
  25559. };
  25560. }
  25561. return _construct.apply(null, arguments);
  25562. }
  25563. module.exports = _construct;
  25564. });
  25565. /**
  25566. * The base plugin name.
  25567. *
  25568. * @private
  25569. * @constant
  25570. * @type {string}
  25571. */
  25572. var BASE_PLUGIN_NAME = 'plugin';
  25573. /**
  25574. * The key on which a player's active plugins cache is stored.
  25575. *
  25576. * @private
  25577. * @constant
  25578. * @type {string}
  25579. */
  25580. var PLUGIN_CACHE_KEY = 'activePlugins_';
  25581. /**
  25582. * Stores registered plugins in a private space.
  25583. *
  25584. * @private
  25585. * @type {Object}
  25586. */
  25587. var pluginStorage = {};
  25588. /**
  25589. * Reports whether or not a plugin has been registered.
  25590. *
  25591. * @private
  25592. * @param {string} name
  25593. * The name of a plugin.
  25594. *
  25595. * @return {boolean}
  25596. * Whether or not the plugin has been registered.
  25597. */
  25598. var pluginExists = function pluginExists(name) {
  25599. return pluginStorage.hasOwnProperty(name);
  25600. };
  25601. /**
  25602. * Get a single registered plugin by name.
  25603. *
  25604. * @private
  25605. * @param {string} name
  25606. * The name of a plugin.
  25607. *
  25608. * @return {Function|undefined}
  25609. * The plugin (or undefined).
  25610. */
  25611. var getPlugin = function getPlugin(name) {
  25612. return pluginExists(name) ? pluginStorage[name] : undefined;
  25613. };
  25614. /**
  25615. * Marks a plugin as "active" on a player.
  25616. *
  25617. * Also, ensures that the player has an object for tracking active plugins.
  25618. *
  25619. * @private
  25620. * @param {Player} player
  25621. * A Video.js player instance.
  25622. *
  25623. * @param {string} name
  25624. * The name of a plugin.
  25625. */
  25626. var markPluginAsActive = function markPluginAsActive(player, name) {
  25627. player[PLUGIN_CACHE_KEY] = player[PLUGIN_CACHE_KEY] || {};
  25628. player[PLUGIN_CACHE_KEY][name] = true;
  25629. };
  25630. /**
  25631. * Triggers a pair of plugin setup events.
  25632. *
  25633. * @private
  25634. * @param {Player} player
  25635. * A Video.js player instance.
  25636. *
  25637. * @param {Plugin~PluginEventHash} hash
  25638. * A plugin event hash.
  25639. *
  25640. * @param {boolean} [before]
  25641. * If true, prefixes the event name with "before". In other words,
  25642. * use this to trigger "beforepluginsetup" instead of "pluginsetup".
  25643. */
  25644. var triggerSetupEvent = function triggerSetupEvent(player, hash, before) {
  25645. var eventName = (before ? 'before' : '') + 'pluginsetup';
  25646. player.trigger(eventName, hash);
  25647. player.trigger(eventName + ':' + hash.name, hash);
  25648. };
  25649. /**
  25650. * Takes a basic plugin function and returns a wrapper function which marks
  25651. * on the player that the plugin has been activated.
  25652. *
  25653. * @private
  25654. * @param {string} name
  25655. * The name of the plugin.
  25656. *
  25657. * @param {Function} plugin
  25658. * The basic plugin.
  25659. *
  25660. * @return {Function}
  25661. * A wrapper function for the given plugin.
  25662. */
  25663. var createBasicPlugin = function createBasicPlugin(name, plugin) {
  25664. var basicPluginWrapper = function basicPluginWrapper() {
  25665. // We trigger the "beforepluginsetup" and "pluginsetup" events on the player
  25666. // regardless, but we want the hash to be consistent with the hash provided
  25667. // for advanced plugins.
  25668. //
  25669. // The only potentially counter-intuitive thing here is the `instance` in
  25670. // the "pluginsetup" event is the value returned by the `plugin` function.
  25671. triggerSetupEvent(this, {
  25672. name: name,
  25673. plugin: plugin,
  25674. instance: null
  25675. }, true);
  25676. var instance = plugin.apply(this, arguments);
  25677. markPluginAsActive(this, name);
  25678. triggerSetupEvent(this, {
  25679. name: name,
  25680. plugin: plugin,
  25681. instance: instance
  25682. });
  25683. return instance;
  25684. };
  25685. Object.keys(plugin).forEach(function (prop) {
  25686. basicPluginWrapper[prop] = plugin[prop];
  25687. });
  25688. return basicPluginWrapper;
  25689. };
  25690. /**
  25691. * Takes a plugin sub-class and returns a factory function for generating
  25692. * instances of it.
  25693. *
  25694. * This factory function will replace itself with an instance of the requested
  25695. * sub-class of Plugin.
  25696. *
  25697. * @private
  25698. * @param {string} name
  25699. * The name of the plugin.
  25700. *
  25701. * @param {Plugin} PluginSubClass
  25702. * The advanced plugin.
  25703. *
  25704. * @return {Function}
  25705. */
  25706. var createPluginFactory = function createPluginFactory(name, PluginSubClass) {
  25707. // Add a `name` property to the plugin prototype so that each plugin can
  25708. // refer to itself by name.
  25709. PluginSubClass.prototype.name = name;
  25710. return function () {
  25711. triggerSetupEvent(this, {
  25712. name: name,
  25713. plugin: PluginSubClass,
  25714. instance: null
  25715. }, true);
  25716. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  25717. args[_key] = arguments[_key];
  25718. }
  25719. var instance = construct(PluginSubClass, [this].concat(args)); // The plugin is replaced by a function that returns the current instance.
  25720. this[name] = function () {
  25721. return instance;
  25722. };
  25723. triggerSetupEvent(this, instance.getEventHash());
  25724. return instance;
  25725. };
  25726. };
  25727. /**
  25728. * Parent class for all advanced plugins.
  25729. *
  25730. * @mixes module:evented~EventedMixin
  25731. * @mixes module:stateful~StatefulMixin
  25732. * @fires Player#beforepluginsetup
  25733. * @fires Player#beforepluginsetup:$name
  25734. * @fires Player#pluginsetup
  25735. * @fires Player#pluginsetup:$name
  25736. * @listens Player#dispose
  25737. * @throws {Error}
  25738. * If attempting to instantiate the base {@link Plugin} class
  25739. * directly instead of via a sub-class.
  25740. */
  25741. var Plugin = /*#__PURE__*/function () {
  25742. /**
  25743. * Creates an instance of this class.
  25744. *
  25745. * Sub-classes should call `super` to ensure plugins are properly initialized.
  25746. *
  25747. * @param {Player} player
  25748. * A Video.js player instance.
  25749. */
  25750. function Plugin(player) {
  25751. if (this.constructor === Plugin) {
  25752. throw new Error('Plugin must be sub-classed; not directly instantiated.');
  25753. }
  25754. this.player = player;
  25755. if (!this.log) {
  25756. this.log = this.player.log.createLogger(this.name);
  25757. } // Make this object evented, but remove the added `trigger` method so we
  25758. // use the prototype version instead.
  25759. evented(this);
  25760. delete this.trigger;
  25761. stateful(this, this.constructor.defaultState);
  25762. markPluginAsActive(player, this.name); // Auto-bind the dispose method so we can use it as a listener and unbind
  25763. // it later easily.
  25764. this.dispose = this.dispose.bind(this); // If the player is disposed, dispose the plugin.
  25765. player.on('dispose', this.dispose);
  25766. }
  25767. /**
  25768. * Get the version of the plugin that was set on <pluginName>.VERSION
  25769. */
  25770. var _proto = Plugin.prototype;
  25771. _proto.version = function version() {
  25772. return this.constructor.VERSION;
  25773. }
  25774. /**
  25775. * Each event triggered by plugins includes a hash of additional data with
  25776. * conventional properties.
  25777. *
  25778. * This returns that object or mutates an existing hash.
  25779. *
  25780. * @param {Object} [hash={}]
  25781. * An object to be used as event an event hash.
  25782. *
  25783. * @return {Plugin~PluginEventHash}
  25784. * An event hash object with provided properties mixed-in.
  25785. */
  25786. ;
  25787. _proto.getEventHash = function getEventHash(hash) {
  25788. if (hash === void 0) {
  25789. hash = {};
  25790. }
  25791. hash.name = this.name;
  25792. hash.plugin = this.constructor;
  25793. hash.instance = this;
  25794. return hash;
  25795. }
  25796. /**
  25797. * Triggers an event on the plugin object and overrides
  25798. * {@link module:evented~EventedMixin.trigger|EventedMixin.trigger}.
  25799. *
  25800. * @param {string|Object} event
  25801. * An event type or an object with a type property.
  25802. *
  25803. * @param {Object} [hash={}]
  25804. * Additional data hash to merge with a
  25805. * {@link Plugin~PluginEventHash|PluginEventHash}.
  25806. *
  25807. * @return {boolean}
  25808. * Whether or not default was prevented.
  25809. */
  25810. ;
  25811. _proto.trigger = function trigger$1(event, hash) {
  25812. if (hash === void 0) {
  25813. hash = {};
  25814. }
  25815. return trigger(this.eventBusEl_, event, this.getEventHash(hash));
  25816. }
  25817. /**
  25818. * Handles "statechanged" events on the plugin. No-op by default, override by
  25819. * subclassing.
  25820. *
  25821. * @abstract
  25822. * @param {Event} e
  25823. * An event object provided by a "statechanged" event.
  25824. *
  25825. * @param {Object} e.changes
  25826. * An object describing changes that occurred with the "statechanged"
  25827. * event.
  25828. */
  25829. ;
  25830. _proto.handleStateChanged = function handleStateChanged(e) {}
  25831. /**
  25832. * Disposes a plugin.
  25833. *
  25834. * Subclasses can override this if they want, but for the sake of safety,
  25835. * it's probably best to subscribe the "dispose" event.
  25836. *
  25837. * @fires Plugin#dispose
  25838. */
  25839. ;
  25840. _proto.dispose = function dispose() {
  25841. var name = this.name,
  25842. player = this.player;
  25843. /**
  25844. * Signals that a advanced plugin is about to be disposed.
  25845. *
  25846. * @event Plugin#dispose
  25847. * @type {EventTarget~Event}
  25848. */
  25849. this.trigger('dispose');
  25850. this.off();
  25851. player.off('dispose', this.dispose); // Eliminate any possible sources of leaking memory by clearing up
  25852. // references between the player and the plugin instance and nulling out
  25853. // the plugin's state and replacing methods with a function that throws.
  25854. player[PLUGIN_CACHE_KEY][name] = false;
  25855. this.player = this.state = null; // Finally, replace the plugin name on the player with a new factory
  25856. // function, so that the plugin is ready to be set up again.
  25857. player[name] = createPluginFactory(name, pluginStorage[name]);
  25858. }
  25859. /**
  25860. * Determines if a plugin is a basic plugin (i.e. not a sub-class of `Plugin`).
  25861. *
  25862. * @param {string|Function} plugin
  25863. * If a string, matches the name of a plugin. If a function, will be
  25864. * tested directly.
  25865. *
  25866. * @return {boolean}
  25867. * Whether or not a plugin is a basic plugin.
  25868. */
  25869. ;
  25870. Plugin.isBasic = function isBasic(plugin) {
  25871. var p = typeof plugin === 'string' ? getPlugin(plugin) : plugin;
  25872. return typeof p === 'function' && !Plugin.prototype.isPrototypeOf(p.prototype);
  25873. }
  25874. /**
  25875. * Register a Video.js plugin.
  25876. *
  25877. * @param {string} name
  25878. * The name of the plugin to be registered. Must be a string and
  25879. * must not match an existing plugin or a method on the `Player`
  25880. * prototype.
  25881. *
  25882. * @param {Function} plugin
  25883. * A sub-class of `Plugin` or a function for basic plugins.
  25884. *
  25885. * @return {Function}
  25886. * For advanced plugins, a factory function for that plugin. For
  25887. * basic plugins, a wrapper function that initializes the plugin.
  25888. */
  25889. ;
  25890. Plugin.registerPlugin = function registerPlugin(name, plugin) {
  25891. if (typeof name !== 'string') {
  25892. throw new Error("Illegal plugin name, \"" + name + "\", must be a string, was " + typeof name + ".");
  25893. }
  25894. if (pluginExists(name)) {
  25895. log$1.warn("A plugin named \"" + name + "\" already exists. You may want to avoid re-registering plugins!");
  25896. } else if (Player.prototype.hasOwnProperty(name)) {
  25897. throw new Error("Illegal plugin name, \"" + name + "\", cannot share a name with an existing player method!");
  25898. }
  25899. if (typeof plugin !== 'function') {
  25900. throw new Error("Illegal plugin for \"" + name + "\", must be a function, was " + typeof plugin + ".");
  25901. }
  25902. pluginStorage[name] = plugin; // Add a player prototype method for all sub-classed plugins (but not for
  25903. // the base Plugin class).
  25904. if (name !== BASE_PLUGIN_NAME) {
  25905. if (Plugin.isBasic(plugin)) {
  25906. Player.prototype[name] = createBasicPlugin(name, plugin);
  25907. } else {
  25908. Player.prototype[name] = createPluginFactory(name, plugin);
  25909. }
  25910. }
  25911. return plugin;
  25912. }
  25913. /**
  25914. * De-register a Video.js plugin.
  25915. *
  25916. * @param {string} name
  25917. * The name of the plugin to be de-registered. Must be a string that
  25918. * matches an existing plugin.
  25919. *
  25920. * @throws {Error}
  25921. * If an attempt is made to de-register the base plugin.
  25922. */
  25923. ;
  25924. Plugin.deregisterPlugin = function deregisterPlugin(name) {
  25925. if (name === BASE_PLUGIN_NAME) {
  25926. throw new Error('Cannot de-register base plugin.');
  25927. }
  25928. if (pluginExists(name)) {
  25929. delete pluginStorage[name];
  25930. delete Player.prototype[name];
  25931. }
  25932. }
  25933. /**
  25934. * Gets an object containing multiple Video.js plugins.
  25935. *
  25936. * @param {Array} [names]
  25937. * If provided, should be an array of plugin names. Defaults to _all_
  25938. * plugin names.
  25939. *
  25940. * @return {Object|undefined}
  25941. * An object containing plugin(s) associated with their name(s) or
  25942. * `undefined` if no matching plugins exist).
  25943. */
  25944. ;
  25945. Plugin.getPlugins = function getPlugins(names) {
  25946. if (names === void 0) {
  25947. names = Object.keys(pluginStorage);
  25948. }
  25949. var result;
  25950. names.forEach(function (name) {
  25951. var plugin = getPlugin(name);
  25952. if (plugin) {
  25953. result = result || {};
  25954. result[name] = plugin;
  25955. }
  25956. });
  25957. return result;
  25958. }
  25959. /**
  25960. * Gets a plugin's version, if available
  25961. *
  25962. * @param {string} name
  25963. * The name of a plugin.
  25964. *
  25965. * @return {string}
  25966. * The plugin's version or an empty string.
  25967. */
  25968. ;
  25969. Plugin.getPluginVersion = function getPluginVersion(name) {
  25970. var plugin = getPlugin(name);
  25971. return plugin && plugin.VERSION || '';
  25972. };
  25973. return Plugin;
  25974. }();
  25975. /**
  25976. * Gets a plugin by name if it exists.
  25977. *
  25978. * @static
  25979. * @method getPlugin
  25980. * @memberOf Plugin
  25981. * @param {string} name
  25982. * The name of a plugin.
  25983. *
  25984. * @returns {Function|undefined}
  25985. * The plugin (or `undefined`).
  25986. */
  25987. Plugin.getPlugin = getPlugin;
  25988. /**
  25989. * The name of the base plugin class as it is registered.
  25990. *
  25991. * @type {string}
  25992. */
  25993. Plugin.BASE_PLUGIN_NAME = BASE_PLUGIN_NAME;
  25994. Plugin.registerPlugin(BASE_PLUGIN_NAME, Plugin);
  25995. /**
  25996. * Documented in player.js
  25997. *
  25998. * @ignore
  25999. */
  26000. Player.prototype.usingPlugin = function (name) {
  26001. return !!this[PLUGIN_CACHE_KEY] && this[PLUGIN_CACHE_KEY][name] === true;
  26002. };
  26003. /**
  26004. * Documented in player.js
  26005. *
  26006. * @ignore
  26007. */
  26008. Player.prototype.hasPlugin = function (name) {
  26009. return !!pluginExists(name);
  26010. };
  26011. /**
  26012. * Signals that a plugin is about to be set up on a player.
  26013. *
  26014. * @event Player#beforepluginsetup
  26015. * @type {Plugin~PluginEventHash}
  26016. */
  26017. /**
  26018. * Signals that a plugin is about to be set up on a player - by name. The name
  26019. * is the name of the plugin.
  26020. *
  26021. * @event Player#beforepluginsetup:$name
  26022. * @type {Plugin~PluginEventHash}
  26023. */
  26024. /**
  26025. * Signals that a plugin has just been set up on a player.
  26026. *
  26027. * @event Player#pluginsetup
  26028. * @type {Plugin~PluginEventHash}
  26029. */
  26030. /**
  26031. * Signals that a plugin has just been set up on a player - by name. The name
  26032. * is the name of the plugin.
  26033. *
  26034. * @event Player#pluginsetup:$name
  26035. * @type {Plugin~PluginEventHash}
  26036. */
  26037. /**
  26038. * @typedef {Object} Plugin~PluginEventHash
  26039. *
  26040. * @property {string} instance
  26041. * For basic plugins, the return value of the plugin function. For
  26042. * advanced plugins, the plugin instance on which the event is fired.
  26043. *
  26044. * @property {string} name
  26045. * The name of the plugin.
  26046. *
  26047. * @property {string} plugin
  26048. * For basic plugins, the plugin function. For advanced plugins, the
  26049. * plugin class/constructor.
  26050. */
  26051. function _inherits(subClass, superClass) {
  26052. if (typeof superClass !== "function" && superClass !== null) {
  26053. throw new TypeError("Super expression must either be null or a function");
  26054. }
  26055. subClass.prototype = Object.create(superClass && superClass.prototype, {
  26056. constructor: {
  26057. value: subClass,
  26058. writable: true,
  26059. configurable: true
  26060. }
  26061. });
  26062. if (superClass) setPrototypeOf(subClass, superClass);
  26063. }
  26064. var inherits = _inherits;
  26065. /**
  26066. * @file extend.js
  26067. * @module extend
  26068. */
  26069. var hasLogged = false;
  26070. /**
  26071. * Used to subclass an existing class by emulating ES subclassing using the
  26072. * `extends` keyword.
  26073. *
  26074. * @function
  26075. * @deprecated
  26076. * @example
  26077. * var MyComponent = videojs.extend(videojs.getComponent('Component'), {
  26078. * myCustomMethod: function() {
  26079. * // Do things in my method.
  26080. * }
  26081. * });
  26082. *
  26083. * @param {Function} superClass
  26084. * The class to inherit from
  26085. *
  26086. * @param {Object} [subClassMethods={}]
  26087. * Methods of the new class
  26088. *
  26089. * @return {Function}
  26090. * The new class with subClassMethods that inherited superClass.
  26091. */
  26092. var extend = function extend(superClass, subClassMethods) {
  26093. if (subClassMethods === void 0) {
  26094. subClassMethods = {};
  26095. }
  26096. // Log a warning the first time extend is called to note that it is deprecated
  26097. // It was previously deprecated in our documentation (guides, specifically),
  26098. // but was never formally deprecated in code.
  26099. if (!hasLogged) {
  26100. log$1.warn('videojs.extend is deprecated as of Video.js 7.22.0 and will be removed in Video.js 8.0.0');
  26101. hasLogged = true;
  26102. }
  26103. var subClass = function subClass() {
  26104. superClass.apply(this, arguments);
  26105. };
  26106. var methods = {};
  26107. if (typeof subClassMethods === 'object') {
  26108. if (subClassMethods.constructor !== Object.prototype.constructor) {
  26109. subClass = subClassMethods.constructor;
  26110. }
  26111. methods = subClassMethods;
  26112. } else if (typeof subClassMethods === 'function') {
  26113. subClass = subClassMethods;
  26114. }
  26115. inherits(subClass, superClass); // this is needed for backward-compatibility and node compatibility.
  26116. if (superClass) {
  26117. subClass.super_ = superClass;
  26118. } // Extend subObj's prototype with functions and other properties from props
  26119. for (var name in methods) {
  26120. if (methods.hasOwnProperty(name)) {
  26121. subClass.prototype[name] = methods[name];
  26122. }
  26123. }
  26124. return subClass;
  26125. };
  26126. /**
  26127. * @file video.js
  26128. * @module videojs
  26129. */
  26130. /**
  26131. * Normalize an `id` value by trimming off a leading `#`
  26132. *
  26133. * @private
  26134. * @param {string} id
  26135. * A string, maybe with a leading `#`.
  26136. *
  26137. * @return {string}
  26138. * The string, without any leading `#`.
  26139. */
  26140. var normalizeId = function normalizeId(id) {
  26141. return id.indexOf('#') === 0 ? id.slice(1) : id;
  26142. };
  26143. /**
  26144. * The `videojs()` function doubles as the main function for users to create a
  26145. * {@link Player} instance as well as the main library namespace.
  26146. *
  26147. * It can also be used as a getter for a pre-existing {@link Player} instance.
  26148. * However, we _strongly_ recommend using `videojs.getPlayer()` for this
  26149. * purpose because it avoids any potential for unintended initialization.
  26150. *
  26151. * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
  26152. * of our JSDoc template, we cannot properly document this as both a function
  26153. * and a namespace, so its function signature is documented here.
  26154. *
  26155. * #### Arguments
  26156. * ##### id
  26157. * string|Element, **required**
  26158. *
  26159. * Video element or video element ID.
  26160. *
  26161. * ##### options
  26162. * Object, optional
  26163. *
  26164. * Options object for providing settings.
  26165. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).
  26166. *
  26167. * ##### ready
  26168. * {@link Component~ReadyCallback}, optional
  26169. *
  26170. * A function to be called when the {@link Player} and {@link Tech} are ready.
  26171. *
  26172. * #### Return Value
  26173. *
  26174. * The `videojs()` function returns a {@link Player} instance.
  26175. *
  26176. * @namespace
  26177. *
  26178. * @borrows AudioTrack as AudioTrack
  26179. * @borrows Component.getComponent as getComponent
  26180. * @borrows module:computed-style~computedStyle as computedStyle
  26181. * @borrows module:events.on as on
  26182. * @borrows module:events.one as one
  26183. * @borrows module:events.off as off
  26184. * @borrows module:events.trigger as trigger
  26185. * @borrows EventTarget as EventTarget
  26186. * @borrows module:extend~extend as extend
  26187. * @borrows module:fn.bind as bind
  26188. * @borrows module:format-time.formatTime as formatTime
  26189. * @borrows module:format-time.resetFormatTime as resetFormatTime
  26190. * @borrows module:format-time.setFormatTime as setFormatTime
  26191. * @borrows module:merge-options.mergeOptions as mergeOptions
  26192. * @borrows module:middleware.use as use
  26193. * @borrows Player.players as players
  26194. * @borrows Plugin.registerPlugin as registerPlugin
  26195. * @borrows Plugin.deregisterPlugin as deregisterPlugin
  26196. * @borrows Plugin.getPlugins as getPlugins
  26197. * @borrows Plugin.getPlugin as getPlugin
  26198. * @borrows Plugin.getPluginVersion as getPluginVersion
  26199. * @borrows Tech.getTech as getTech
  26200. * @borrows Tech.registerTech as registerTech
  26201. * @borrows TextTrack as TextTrack
  26202. * @borrows module:time-ranges.createTimeRanges as createTimeRange
  26203. * @borrows module:time-ranges.createTimeRanges as createTimeRanges
  26204. * @borrows module:url.isCrossOrigin as isCrossOrigin
  26205. * @borrows module:url.parseUrl as parseUrl
  26206. * @borrows VideoTrack as VideoTrack
  26207. *
  26208. * @param {string|Element} id
  26209. * Video element or video element ID.
  26210. *
  26211. * @param {Object} [options]
  26212. * Options object for providing settings.
  26213. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).
  26214. *
  26215. * @param {Component~ReadyCallback} [ready]
  26216. * A function to be called when the {@link Player} and {@link Tech} are
  26217. * ready.
  26218. *
  26219. * @return {Player}
  26220. * The `videojs()` function returns a {@link Player|Player} instance.
  26221. */
  26222. function videojs(id, options, ready) {
  26223. var player = videojs.getPlayer(id);
  26224. if (player) {
  26225. if (options) {
  26226. log$1.warn("Player \"" + id + "\" is already initialised. Options will not be applied.");
  26227. }
  26228. if (ready) {
  26229. player.ready(ready);
  26230. }
  26231. return player;
  26232. }
  26233. var el = typeof id === 'string' ? $('#' + normalizeId(id)) : id;
  26234. if (!isEl(el)) {
  26235. throw new TypeError('The element or ID supplied is not valid. (videojs)');
  26236. } // document.body.contains(el) will only check if el is contained within that one document.
  26237. // This causes problems for elements in iframes.
  26238. // Instead, use the element's ownerDocument instead of the global document.
  26239. // This will make sure that the element is indeed in the dom of that document.
  26240. // Additionally, check that the document in question has a default view.
  26241. // If the document is no longer attached to the dom, the defaultView of the document will be null.
  26242. if (!el.ownerDocument.defaultView || !el.ownerDocument.body.contains(el)) {
  26243. log$1.warn('The element supplied is not included in the DOM');
  26244. }
  26245. options = options || {}; // Store a copy of the el before modification, if it is to be restored in destroy()
  26246. // If div ingest, store the parent div
  26247. if (options.restoreEl === true) {
  26248. options.restoreEl = (el.parentNode && el.parentNode.hasAttribute('data-vjs-player') ? el.parentNode : el).cloneNode(true);
  26249. }
  26250. hooks('beforesetup').forEach(function (hookFunction) {
  26251. var opts = hookFunction(el, mergeOptions$3(options));
  26252. if (!isObject$1(opts) || Array.isArray(opts)) {
  26253. log$1.error('please return an object in beforesetup hooks');
  26254. return;
  26255. }
  26256. options = mergeOptions$3(options, opts);
  26257. }); // We get the current "Player" component here in case an integration has
  26258. // replaced it with a custom player.
  26259. var PlayerComponent = Component$1.getComponent('Player');
  26260. player = new PlayerComponent(el, options, ready);
  26261. hooks('setup').forEach(function (hookFunction) {
  26262. return hookFunction(player);
  26263. });
  26264. return player;
  26265. }
  26266. videojs.hooks_ = hooks_;
  26267. videojs.hooks = hooks;
  26268. videojs.hook = hook;
  26269. videojs.hookOnce = hookOnce;
  26270. videojs.removeHook = removeHook; // Add default styles
  26271. if (window.VIDEOJS_NO_DYNAMIC_STYLE !== true && isReal()) {
  26272. var style = $('.vjs-styles-defaults');
  26273. if (!style) {
  26274. style = createStyleElement('vjs-styles-defaults');
  26275. var head = $('head');
  26276. if (head) {
  26277. head.insertBefore(style, head.firstChild);
  26278. }
  26279. setTextContent(style, "\n .video-js {\n width: 300px;\n height: 150px;\n }\n\n .vjs-fluid:not(.vjs-audio-only-mode) {\n padding-top: 56.25%\n }\n ");
  26280. }
  26281. } // Run Auto-load players
  26282. // You have to wait at least once in case this script is loaded after your
  26283. // video in the DOM (weird behavior only with minified version)
  26284. autoSetupTimeout(1, videojs);
  26285. /**
  26286. * Current Video.js version. Follows [semantic versioning](https://semver.org/).
  26287. *
  26288. * @type {string}
  26289. */
  26290. videojs.VERSION = version$5;
  26291. /**
  26292. * The global options object. These are the settings that take effect
  26293. * if no overrides are specified when the player is created.
  26294. *
  26295. * @type {Object}
  26296. */
  26297. videojs.options = Player.prototype.options_;
  26298. /**
  26299. * Get an object with the currently created players, keyed by player ID
  26300. *
  26301. * @return {Object}
  26302. * The created players
  26303. */
  26304. videojs.getPlayers = function () {
  26305. return Player.players;
  26306. };
  26307. /**
  26308. * Get a single player based on an ID or DOM element.
  26309. *
  26310. * This is useful if you want to check if an element or ID has an associated
  26311. * Video.js player, but not create one if it doesn't.
  26312. *
  26313. * @param {string|Element} id
  26314. * An HTML element - `<video>`, `<audio>`, or `<video-js>` -
  26315. * or a string matching the `id` of such an element.
  26316. *
  26317. * @return {Player|undefined}
  26318. * A player instance or `undefined` if there is no player instance
  26319. * matching the argument.
  26320. */
  26321. videojs.getPlayer = function (id) {
  26322. var players = Player.players;
  26323. var tag;
  26324. if (typeof id === 'string') {
  26325. var nId = normalizeId(id);
  26326. var player = players[nId];
  26327. if (player) {
  26328. return player;
  26329. }
  26330. tag = $('#' + nId);
  26331. } else {
  26332. tag = id;
  26333. }
  26334. if (isEl(tag)) {
  26335. var _tag = tag,
  26336. _player = _tag.player,
  26337. playerId = _tag.playerId; // Element may have a `player` property referring to an already created
  26338. // player instance. If so, return that.
  26339. if (_player || players[playerId]) {
  26340. return _player || players[playerId];
  26341. }
  26342. }
  26343. };
  26344. /**
  26345. * Returns an array of all current players.
  26346. *
  26347. * @return {Array}
  26348. * An array of all players. The array will be in the order that
  26349. * `Object.keys` provides, which could potentially vary between
  26350. * JavaScript engines.
  26351. *
  26352. */
  26353. videojs.getAllPlayers = function () {
  26354. return (// Disposed players leave a key with a `null` value, so we need to make sure
  26355. // we filter those out.
  26356. Object.keys(Player.players).map(function (k) {
  26357. return Player.players[k];
  26358. }).filter(Boolean)
  26359. );
  26360. };
  26361. videojs.players = Player.players;
  26362. videojs.getComponent = Component$1.getComponent;
  26363. /**
  26364. * Register a component so it can referred to by name. Used when adding to other
  26365. * components, either through addChild `component.addChild('myComponent')` or through
  26366. * default children options `{ children: ['myComponent'] }`.
  26367. *
  26368. * > NOTE: You could also just initialize the component before adding.
  26369. * `component.addChild(new MyComponent());`
  26370. *
  26371. * @param {string} name
  26372. * The class name of the component
  26373. *
  26374. * @param {Component} comp
  26375. * The component class
  26376. *
  26377. * @return {Component}
  26378. * The newly registered component
  26379. */
  26380. videojs.registerComponent = function (name, comp) {
  26381. if (Tech.isTech(comp)) {
  26382. log$1.warn("The " + name + " tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)");
  26383. }
  26384. Component$1.registerComponent.call(Component$1, name, comp);
  26385. };
  26386. videojs.getTech = Tech.getTech;
  26387. videojs.registerTech = Tech.registerTech;
  26388. videojs.use = use;
  26389. /**
  26390. * An object that can be returned by a middleware to signify
  26391. * that the middleware is being terminated.
  26392. *
  26393. * @type {object}
  26394. * @property {object} middleware.TERMINATOR
  26395. */
  26396. Object.defineProperty(videojs, 'middleware', {
  26397. value: {},
  26398. writeable: false,
  26399. enumerable: true
  26400. });
  26401. Object.defineProperty(videojs.middleware, 'TERMINATOR', {
  26402. value: TERMINATOR,
  26403. writeable: false,
  26404. enumerable: true
  26405. });
  26406. /**
  26407. * A reference to the {@link module:browser|browser utility module} as an object.
  26408. *
  26409. * @type {Object}
  26410. * @see {@link module:browser|browser}
  26411. */
  26412. videojs.browser = browser;
  26413. /**
  26414. * Use {@link module:browser.TOUCH_ENABLED|browser.TOUCH_ENABLED} instead; only
  26415. * included for backward-compatibility with 4.x.
  26416. *
  26417. * @deprecated Since version 5.0, use {@link module:browser.TOUCH_ENABLED|browser.TOUCH_ENABLED instead.
  26418. * @type {boolean}
  26419. */
  26420. videojs.TOUCH_ENABLED = TOUCH_ENABLED;
  26421. videojs.extend = extend;
  26422. videojs.mergeOptions = mergeOptions$3;
  26423. videojs.bind = bind;
  26424. videojs.registerPlugin = Plugin.registerPlugin;
  26425. videojs.deregisterPlugin = Plugin.deregisterPlugin;
  26426. /**
  26427. * Deprecated method to register a plugin with Video.js
  26428. *
  26429. * @deprecated videojs.plugin() is deprecated; use videojs.registerPlugin() instead
  26430. *
  26431. * @param {string} name
  26432. * The plugin name
  26433. *
  26434. * @param {Plugin|Function} plugin
  26435. * The plugin sub-class or function
  26436. */
  26437. videojs.plugin = function (name, plugin) {
  26438. log$1.warn('videojs.plugin() is deprecated; use videojs.registerPlugin() instead');
  26439. return Plugin.registerPlugin(name, plugin);
  26440. };
  26441. videojs.getPlugins = Plugin.getPlugins;
  26442. videojs.getPlugin = Plugin.getPlugin;
  26443. videojs.getPluginVersion = Plugin.getPluginVersion;
  26444. /**
  26445. * Adding languages so that they're available to all players.
  26446. * Example: `videojs.addLanguage('es', { 'Hello': 'Hola' });`
  26447. *
  26448. * @param {string} code
  26449. * The language code or dictionary property
  26450. *
  26451. * @param {Object} data
  26452. * The data values to be translated
  26453. *
  26454. * @return {Object}
  26455. * The resulting language dictionary object
  26456. */
  26457. videojs.addLanguage = function (code, data) {
  26458. var _mergeOptions;
  26459. code = ('' + code).toLowerCase();
  26460. videojs.options.languages = mergeOptions$3(videojs.options.languages, (_mergeOptions = {}, _mergeOptions[code] = data, _mergeOptions));
  26461. return videojs.options.languages[code];
  26462. };
  26463. /**
  26464. * A reference to the {@link module:log|log utility module} as an object.
  26465. *
  26466. * @type {Function}
  26467. * @see {@link module:log|log}
  26468. */
  26469. videojs.log = log$1;
  26470. videojs.createLogger = createLogger;
  26471. videojs.createTimeRange = videojs.createTimeRanges = createTimeRanges;
  26472. videojs.formatTime = formatTime;
  26473. videojs.setFormatTime = setFormatTime;
  26474. videojs.resetFormatTime = resetFormatTime;
  26475. videojs.parseUrl = parseUrl;
  26476. videojs.isCrossOrigin = isCrossOrigin;
  26477. videojs.EventTarget = EventTarget$2;
  26478. videojs.on = on;
  26479. videojs.one = one;
  26480. videojs.off = off;
  26481. videojs.trigger = trigger;
  26482. /**
  26483. * A cross-browser XMLHttpRequest wrapper.
  26484. *
  26485. * @function
  26486. * @param {Object} options
  26487. * Settings for the request.
  26488. *
  26489. * @return {XMLHttpRequest|XDomainRequest}
  26490. * The request object.
  26491. *
  26492. * @see https://github.com/Raynos/xhr
  26493. */
  26494. videojs.xhr = lib;
  26495. videojs.TextTrack = TextTrack;
  26496. videojs.AudioTrack = AudioTrack;
  26497. videojs.VideoTrack = VideoTrack;
  26498. ['isEl', 'isTextNode', 'createEl', 'hasClass', 'addClass', 'removeClass', 'toggleClass', 'setAttributes', 'getAttributes', 'emptyEl', 'appendContent', 'insertContent'].forEach(function (k) {
  26499. videojs[k] = function () {
  26500. log$1.warn("videojs." + k + "() is deprecated; use videojs.dom." + k + "() instead");
  26501. return Dom[k].apply(null, arguments);
  26502. };
  26503. });
  26504. videojs.computedStyle = computedStyle;
  26505. /**
  26506. * A reference to the {@link module:dom|DOM utility module} as an object.
  26507. *
  26508. * @type {Object}
  26509. * @see {@link module:dom|dom}
  26510. */
  26511. videojs.dom = Dom;
  26512. /**
  26513. * A reference to the {@link module:url|URL utility module} as an object.
  26514. *
  26515. * @type {Object}
  26516. * @see {@link module:url|url}
  26517. */
  26518. videojs.url = Url;
  26519. videojs.defineLazyProperty = defineLazyProperty; // Adding less ambiguous text for fullscreen button.
  26520. // In a major update this could become the default text and key.
  26521. videojs.addLanguage('en', {
  26522. 'Non-Fullscreen': 'Exit Fullscreen'
  26523. });
  26524. var urlToolkit = createCommonjsModule(function (module, exports) {
  26525. // see https://tools.ietf.org/html/rfc1808
  26526. (function (root) {
  26527. var URL_REGEX = /^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#[^]*)?$/;
  26528. var FIRST_SEGMENT_REGEX = /^([^\/?#]*)([^]*)$/;
  26529. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  26530. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
  26531. var URLToolkit = {
  26532. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  26533. // E.g
  26534. // With opts.alwaysNormalize = false (default, spec compliant)
  26535. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  26536. // With opts.alwaysNormalize = true (not spec compliant)
  26537. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  26538. buildAbsoluteURL: function buildAbsoluteURL(baseURL, relativeURL, opts) {
  26539. opts = opts || {}; // remove any remaining space and CRLF
  26540. baseURL = baseURL.trim();
  26541. relativeURL = relativeURL.trim();
  26542. if (!relativeURL) {
  26543. // 2a) If the embedded URL is entirely empty, it inherits the
  26544. // entire base URL (i.e., is set equal to the base URL)
  26545. // and we are done.
  26546. if (!opts.alwaysNormalize) {
  26547. return baseURL;
  26548. }
  26549. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  26550. if (!basePartsForNormalise) {
  26551. throw new Error('Error trying to parse base URL.');
  26552. }
  26553. basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);
  26554. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  26555. }
  26556. var relativeParts = URLToolkit.parseURL(relativeURL);
  26557. if (!relativeParts) {
  26558. throw new Error('Error trying to parse relative URL.');
  26559. }
  26560. if (relativeParts.scheme) {
  26561. // 2b) If the embedded URL starts with a scheme name, it is
  26562. // interpreted as an absolute URL and we are done.
  26563. if (!opts.alwaysNormalize) {
  26564. return relativeURL;
  26565. }
  26566. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  26567. return URLToolkit.buildURLFromParts(relativeParts);
  26568. }
  26569. var baseParts = URLToolkit.parseURL(baseURL);
  26570. if (!baseParts) {
  26571. throw new Error('Error trying to parse base URL.');
  26572. }
  26573. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
  26574. // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
  26575. // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
  26576. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  26577. baseParts.netLoc = pathParts[1];
  26578. baseParts.path = pathParts[2];
  26579. }
  26580. if (baseParts.netLoc && !baseParts.path) {
  26581. baseParts.path = '/';
  26582. }
  26583. var builtParts = {
  26584. // 2c) Otherwise, the embedded URL inherits the scheme of
  26585. // the base URL.
  26586. scheme: baseParts.scheme,
  26587. netLoc: relativeParts.netLoc,
  26588. path: null,
  26589. params: relativeParts.params,
  26590. query: relativeParts.query,
  26591. fragment: relativeParts.fragment
  26592. };
  26593. if (!relativeParts.netLoc) {
  26594. // 3) If the embedded URL's <net_loc> is non-empty, we skip to
  26595. // Step 7. Otherwise, the embedded URL inherits the <net_loc>
  26596. // (if any) of the base URL.
  26597. builtParts.netLoc = baseParts.netLoc; // 4) If the embedded URL path is preceded by a slash "/", the
  26598. // path is not relative and we skip to Step 7.
  26599. if (relativeParts.path[0] !== '/') {
  26600. if (!relativeParts.path) {
  26601. // 5) If the embedded URL path is empty (and not preceded by a
  26602. // slash), then the embedded URL inherits the base URL path
  26603. builtParts.path = baseParts.path; // 5a) if the embedded URL's <params> is non-empty, we skip to
  26604. // step 7; otherwise, it inherits the <params> of the base
  26605. // URL (if any) and
  26606. if (!relativeParts.params) {
  26607. builtParts.params = baseParts.params; // 5b) if the embedded URL's <query> is non-empty, we skip to
  26608. // step 7; otherwise, it inherits the <query> of the base
  26609. // URL (if any) and we skip to step 7.
  26610. if (!relativeParts.query) {
  26611. builtParts.query = baseParts.query;
  26612. }
  26613. }
  26614. } else {
  26615. // 6) The last segment of the base URL's path (anything
  26616. // following the rightmost slash "/", or the entire path if no
  26617. // slash is present) is removed and the embedded URL's path is
  26618. // appended in its place.
  26619. var baseURLPath = baseParts.path;
  26620. var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path;
  26621. builtParts.path = URLToolkit.normalizePath(newPath);
  26622. }
  26623. }
  26624. }
  26625. if (builtParts.path === null) {
  26626. builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;
  26627. }
  26628. return URLToolkit.buildURLFromParts(builtParts);
  26629. },
  26630. parseURL: function parseURL(url) {
  26631. var parts = URL_REGEX.exec(url);
  26632. if (!parts) {
  26633. return null;
  26634. }
  26635. return {
  26636. scheme: parts[1] || '',
  26637. netLoc: parts[2] || '',
  26638. path: parts[3] || '',
  26639. params: parts[4] || '',
  26640. query: parts[5] || '',
  26641. fragment: parts[6] || ''
  26642. };
  26643. },
  26644. normalizePath: function normalizePath(path) {
  26645. // The following operations are
  26646. // then applied, in order, to the new path:
  26647. // 6a) All occurrences of "./", where "." is a complete path
  26648. // segment, are removed.
  26649. // 6b) If the path ends with "." as a complete path segment,
  26650. // that "." is removed.
  26651. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, ''); // 6c) All occurrences of "<segment>/../", where <segment> is a
  26652. // complete path segment not equal to "..", are removed.
  26653. // Removal of these path segments is performed iteratively,
  26654. // removing the leftmost matching pattern on each iteration,
  26655. // until no matching pattern remains.
  26656. // 6d) If the path ends with "<segment>/..", where <segment> is a
  26657. // complete path segment not equal to "..", that
  26658. // "<segment>/.." is removed.
  26659. while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {}
  26660. return path.split('').reverse().join('');
  26661. },
  26662. buildURLFromParts: function buildURLFromParts(parts) {
  26663. return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
  26664. }
  26665. };
  26666. module.exports = URLToolkit;
  26667. })();
  26668. });
  26669. var DEFAULT_LOCATION$1 = 'http://example.com';
  26670. var resolveUrl$2 = function resolveUrl(baseUrl, relativeUrl) {
  26671. // return early if we don't need to resolve
  26672. if (/^[a-z]+:/i.test(relativeUrl)) {
  26673. return relativeUrl;
  26674. } // if baseUrl is a data URI, ignore it and resolve everything relative to window.location
  26675. if (/^data:/.test(baseUrl)) {
  26676. baseUrl = window.location && window.location.href || '';
  26677. } // IE11 supports URL but not the URL constructor
  26678. // feature detect the behavior we want
  26679. var nativeURL = typeof window.URL === 'function';
  26680. var protocolLess = /^\/\//.test(baseUrl); // remove location if window.location isn't available (i.e. we're in node)
  26681. // and if baseUrl isn't an absolute url
  26682. var removeLocation = !window.location && !/\/\//i.test(baseUrl); // if the base URL is relative then combine with the current location
  26683. if (nativeURL) {
  26684. baseUrl = new window.URL(baseUrl, window.location || DEFAULT_LOCATION$1);
  26685. } else if (!/\/\//i.test(baseUrl)) {
  26686. baseUrl = urlToolkit.buildAbsoluteURL(window.location && window.location.href || '', baseUrl);
  26687. }
  26688. if (nativeURL) {
  26689. var newUrl = new URL(relativeUrl, baseUrl); // if we're a protocol-less url, remove the protocol
  26690. // and if we're location-less, remove the location
  26691. // otherwise, return the url unmodified
  26692. if (removeLocation) {
  26693. return newUrl.href.slice(DEFAULT_LOCATION$1.length);
  26694. } else if (protocolLess) {
  26695. return newUrl.href.slice(newUrl.protocol.length);
  26696. }
  26697. return newUrl.href;
  26698. }
  26699. return urlToolkit.buildAbsoluteURL(baseUrl, relativeUrl);
  26700. };
  26701. /**
  26702. * @file stream.js
  26703. */
  26704. /**
  26705. * A lightweight readable stream implemention that handles event dispatching.
  26706. *
  26707. * @class Stream
  26708. */
  26709. var Stream = /*#__PURE__*/function () {
  26710. function Stream() {
  26711. this.listeners = {};
  26712. }
  26713. /**
  26714. * Add a listener for a specified event type.
  26715. *
  26716. * @param {string} type the event name
  26717. * @param {Function} listener the callback to be invoked when an event of
  26718. * the specified type occurs
  26719. */
  26720. var _proto = Stream.prototype;
  26721. _proto.on = function on(type, listener) {
  26722. if (!this.listeners[type]) {
  26723. this.listeners[type] = [];
  26724. }
  26725. this.listeners[type].push(listener);
  26726. }
  26727. /**
  26728. * Remove a listener for a specified event type.
  26729. *
  26730. * @param {string} type the event name
  26731. * @param {Function} listener a function previously registered for this
  26732. * type of event through `on`
  26733. * @return {boolean} if we could turn it off or not
  26734. */
  26735. ;
  26736. _proto.off = function off(type, listener) {
  26737. if (!this.listeners[type]) {
  26738. return false;
  26739. }
  26740. var index = this.listeners[type].indexOf(listener); // TODO: which is better?
  26741. // In Video.js we slice listener functions
  26742. // on trigger so that it does not mess up the order
  26743. // while we loop through.
  26744. //
  26745. // Here we slice on off so that the loop in trigger
  26746. // can continue using it's old reference to loop without
  26747. // messing up the order.
  26748. this.listeners[type] = this.listeners[type].slice(0);
  26749. this.listeners[type].splice(index, 1);
  26750. return index > -1;
  26751. }
  26752. /**
  26753. * Trigger an event of the specified type on this stream. Any additional
  26754. * arguments to this function are passed as parameters to event listeners.
  26755. *
  26756. * @param {string} type the event name
  26757. */
  26758. ;
  26759. _proto.trigger = function trigger(type) {
  26760. var callbacks = this.listeners[type];
  26761. if (!callbacks) {
  26762. return;
  26763. } // Slicing the arguments on every invocation of this method
  26764. // can add a significant amount of overhead. Avoid the
  26765. // intermediate object creation for the common case of a
  26766. // single callback argument
  26767. if (arguments.length === 2) {
  26768. var length = callbacks.length;
  26769. for (var i = 0; i < length; ++i) {
  26770. callbacks[i].call(this, arguments[1]);
  26771. }
  26772. } else {
  26773. var args = Array.prototype.slice.call(arguments, 1);
  26774. var _length = callbacks.length;
  26775. for (var _i = 0; _i < _length; ++_i) {
  26776. callbacks[_i].apply(this, args);
  26777. }
  26778. }
  26779. }
  26780. /**
  26781. * Destroys the stream and cleans up.
  26782. */
  26783. ;
  26784. _proto.dispose = function dispose() {
  26785. this.listeners = {};
  26786. }
  26787. /**
  26788. * Forwards all `data` events on this stream to the destination stream. The
  26789. * destination stream should provide a method `push` to receive the data
  26790. * events as they arrive.
  26791. *
  26792. * @param {Stream} destination the stream that will receive all `data` events
  26793. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  26794. */
  26795. ;
  26796. _proto.pipe = function pipe(destination) {
  26797. this.on('data', function (data) {
  26798. destination.push(data);
  26799. });
  26800. };
  26801. return Stream;
  26802. }();
  26803. var atob$1 = function atob(s) {
  26804. return window.atob ? window.atob(s) : Buffer.from(s, 'base64').toString('binary');
  26805. };
  26806. function decodeB64ToUint8Array$1(b64Text) {
  26807. var decodedString = atob$1(b64Text);
  26808. var array = new Uint8Array(decodedString.length);
  26809. for (var i = 0; i < decodedString.length; i++) {
  26810. array[i] = decodedString.charCodeAt(i);
  26811. }
  26812. return array;
  26813. }
  26814. /*! @name m3u8-parser @version 4.8.0 @license Apache-2.0 */
  26815. /**
  26816. * A stream that buffers string input and generates a `data` event for each
  26817. * line.
  26818. *
  26819. * @class LineStream
  26820. * @extends Stream
  26821. */
  26822. var LineStream = /*#__PURE__*/function (_Stream) {
  26823. inheritsLoose(LineStream, _Stream);
  26824. function LineStream() {
  26825. var _this;
  26826. _this = _Stream.call(this) || this;
  26827. _this.buffer = '';
  26828. return _this;
  26829. }
  26830. /**
  26831. * Add new data to be parsed.
  26832. *
  26833. * @param {string} data the text to process
  26834. */
  26835. var _proto = LineStream.prototype;
  26836. _proto.push = function push(data) {
  26837. var nextNewline;
  26838. this.buffer += data;
  26839. nextNewline = this.buffer.indexOf('\n');
  26840. for (; nextNewline > -1; nextNewline = this.buffer.indexOf('\n')) {
  26841. this.trigger('data', this.buffer.substring(0, nextNewline));
  26842. this.buffer = this.buffer.substring(nextNewline + 1);
  26843. }
  26844. };
  26845. return LineStream;
  26846. }(Stream);
  26847. var TAB = String.fromCharCode(0x09);
  26848. var parseByterange = function parseByterange(byterangeString) {
  26849. // optionally match and capture 0+ digits before `@`
  26850. // optionally match and capture 0+ digits after `@`
  26851. var match = /([0-9.]*)?@?([0-9.]*)?/.exec(byterangeString || '');
  26852. var result = {};
  26853. if (match[1]) {
  26854. result.length = parseInt(match[1], 10);
  26855. }
  26856. if (match[2]) {
  26857. result.offset = parseInt(match[2], 10);
  26858. }
  26859. return result;
  26860. };
  26861. /**
  26862. * "forgiving" attribute list psuedo-grammar:
  26863. * attributes -> keyvalue (',' keyvalue)*
  26864. * keyvalue -> key '=' value
  26865. * key -> [^=]*
  26866. * value -> '"' [^"]* '"' | [^,]*
  26867. */
  26868. var attributeSeparator = function attributeSeparator() {
  26869. var key = '[^=]*';
  26870. var value = '"[^"]*"|[^,]*';
  26871. var keyvalue = '(?:' + key + ')=(?:' + value + ')';
  26872. return new RegExp('(?:^|,)(' + keyvalue + ')');
  26873. };
  26874. /**
  26875. * Parse attributes from a line given the separator
  26876. *
  26877. * @param {string} attributes the attribute line to parse
  26878. */
  26879. var parseAttributes$1 = function parseAttributes(attributes) {
  26880. // split the string using attributes as the separator
  26881. var attrs = attributes.split(attributeSeparator());
  26882. var result = {};
  26883. var i = attrs.length;
  26884. var attr;
  26885. while (i--) {
  26886. // filter out unmatched portions of the string
  26887. if (attrs[i] === '') {
  26888. continue;
  26889. } // split the key and value
  26890. attr = /([^=]*)=(.*)/.exec(attrs[i]).slice(1); // trim whitespace and remove optional quotes around the value
  26891. attr[0] = attr[0].replace(/^\s+|\s+$/g, '');
  26892. attr[1] = attr[1].replace(/^\s+|\s+$/g, '');
  26893. attr[1] = attr[1].replace(/^['"](.*)['"]$/g, '$1');
  26894. result[attr[0]] = attr[1];
  26895. }
  26896. return result;
  26897. };
  26898. /**
  26899. * A line-level M3U8 parser event stream. It expects to receive input one
  26900. * line at a time and performs a context-free parse of its contents. A stream
  26901. * interpretation of a manifest can be useful if the manifest is expected to
  26902. * be too large to fit comfortably into memory or the entirety of the input
  26903. * is not immediately available. Otherwise, it's probably much easier to work
  26904. * with a regular `Parser` object.
  26905. *
  26906. * Produces `data` events with an object that captures the parser's
  26907. * interpretation of the input. That object has a property `tag` that is one
  26908. * of `uri`, `comment`, or `tag`. URIs only have a single additional
  26909. * property, `line`, which captures the entirety of the input without
  26910. * interpretation. Comments similarly have a single additional property
  26911. * `text` which is the input without the leading `#`.
  26912. *
  26913. * Tags always have a property `tagType` which is the lower-cased version of
  26914. * the M3U8 directive without the `#EXT` or `#EXT-X-` prefix. For instance,
  26915. * `#EXT-X-MEDIA-SEQUENCE` becomes `media-sequence` when parsed. Unrecognized
  26916. * tags are given the tag type `unknown` and a single additional property
  26917. * `data` with the remainder of the input.
  26918. *
  26919. * @class ParseStream
  26920. * @extends Stream
  26921. */
  26922. var ParseStream = /*#__PURE__*/function (_Stream) {
  26923. inheritsLoose(ParseStream, _Stream);
  26924. function ParseStream() {
  26925. var _this;
  26926. _this = _Stream.call(this) || this;
  26927. _this.customParsers = [];
  26928. _this.tagMappers = [];
  26929. return _this;
  26930. }
  26931. /**
  26932. * Parses an additional line of input.
  26933. *
  26934. * @param {string} line a single line of an M3U8 file to parse
  26935. */
  26936. var _proto = ParseStream.prototype;
  26937. _proto.push = function push(line) {
  26938. var _this2 = this;
  26939. var match;
  26940. var event; // strip whitespace
  26941. line = line.trim();
  26942. if (line.length === 0) {
  26943. // ignore empty lines
  26944. return;
  26945. } // URIs
  26946. if (line[0] !== '#') {
  26947. this.trigger('data', {
  26948. type: 'uri',
  26949. uri: line
  26950. });
  26951. return;
  26952. } // map tags
  26953. var newLines = this.tagMappers.reduce(function (acc, mapper) {
  26954. var mappedLine = mapper(line); // skip if unchanged
  26955. if (mappedLine === line) {
  26956. return acc;
  26957. }
  26958. return acc.concat([mappedLine]);
  26959. }, [line]);
  26960. newLines.forEach(function (newLine) {
  26961. for (var i = 0; i < _this2.customParsers.length; i++) {
  26962. if (_this2.customParsers[i].call(_this2, newLine)) {
  26963. return;
  26964. }
  26965. } // Comments
  26966. if (newLine.indexOf('#EXT') !== 0) {
  26967. _this2.trigger('data', {
  26968. type: 'comment',
  26969. text: newLine.slice(1)
  26970. });
  26971. return;
  26972. } // strip off any carriage returns here so the regex matching
  26973. // doesn't have to account for them.
  26974. newLine = newLine.replace('\r', ''); // Tags
  26975. match = /^#EXTM3U/.exec(newLine);
  26976. if (match) {
  26977. _this2.trigger('data', {
  26978. type: 'tag',
  26979. tagType: 'm3u'
  26980. });
  26981. return;
  26982. }
  26983. match = /^#EXTINF:?([0-9\.]*)?,?(.*)?$/.exec(newLine);
  26984. if (match) {
  26985. event = {
  26986. type: 'tag',
  26987. tagType: 'inf'
  26988. };
  26989. if (match[1]) {
  26990. event.duration = parseFloat(match[1]);
  26991. }
  26992. if (match[2]) {
  26993. event.title = match[2];
  26994. }
  26995. _this2.trigger('data', event);
  26996. return;
  26997. }
  26998. match = /^#EXT-X-TARGETDURATION:?([0-9.]*)?/.exec(newLine);
  26999. if (match) {
  27000. event = {
  27001. type: 'tag',
  27002. tagType: 'targetduration'
  27003. };
  27004. if (match[1]) {
  27005. event.duration = parseInt(match[1], 10);
  27006. }
  27007. _this2.trigger('data', event);
  27008. return;
  27009. }
  27010. match = /^#EXT-X-VERSION:?([0-9.]*)?/.exec(newLine);
  27011. if (match) {
  27012. event = {
  27013. type: 'tag',
  27014. tagType: 'version'
  27015. };
  27016. if (match[1]) {
  27017. event.version = parseInt(match[1], 10);
  27018. }
  27019. _this2.trigger('data', event);
  27020. return;
  27021. }
  27022. match = /^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(newLine);
  27023. if (match) {
  27024. event = {
  27025. type: 'tag',
  27026. tagType: 'media-sequence'
  27027. };
  27028. if (match[1]) {
  27029. event.number = parseInt(match[1], 10);
  27030. }
  27031. _this2.trigger('data', event);
  27032. return;
  27033. }
  27034. match = /^#EXT-X-DISCONTINUITY-SEQUENCE:?(\-?[0-9.]*)?/.exec(newLine);
  27035. if (match) {
  27036. event = {
  27037. type: 'tag',
  27038. tagType: 'discontinuity-sequence'
  27039. };
  27040. if (match[1]) {
  27041. event.number = parseInt(match[1], 10);
  27042. }
  27043. _this2.trigger('data', event);
  27044. return;
  27045. }
  27046. match = /^#EXT-X-PLAYLIST-TYPE:?(.*)?$/.exec(newLine);
  27047. if (match) {
  27048. event = {
  27049. type: 'tag',
  27050. tagType: 'playlist-type'
  27051. };
  27052. if (match[1]) {
  27053. event.playlistType = match[1];
  27054. }
  27055. _this2.trigger('data', event);
  27056. return;
  27057. }
  27058. match = /^#EXT-X-BYTERANGE:?(.*)?$/.exec(newLine);
  27059. if (match) {
  27060. event = _extends_1(parseByterange(match[1]), {
  27061. type: 'tag',
  27062. tagType: 'byterange'
  27063. });
  27064. _this2.trigger('data', event);
  27065. return;
  27066. }
  27067. match = /^#EXT-X-ALLOW-CACHE:?(YES|NO)?/.exec(newLine);
  27068. if (match) {
  27069. event = {
  27070. type: 'tag',
  27071. tagType: 'allow-cache'
  27072. };
  27073. if (match[1]) {
  27074. event.allowed = !/NO/.test(match[1]);
  27075. }
  27076. _this2.trigger('data', event);
  27077. return;
  27078. }
  27079. match = /^#EXT-X-MAP:?(.*)$/.exec(newLine);
  27080. if (match) {
  27081. event = {
  27082. type: 'tag',
  27083. tagType: 'map'
  27084. };
  27085. if (match[1]) {
  27086. var attributes = parseAttributes$1(match[1]);
  27087. if (attributes.URI) {
  27088. event.uri = attributes.URI;
  27089. }
  27090. if (attributes.BYTERANGE) {
  27091. event.byterange = parseByterange(attributes.BYTERANGE);
  27092. }
  27093. }
  27094. _this2.trigger('data', event);
  27095. return;
  27096. }
  27097. match = /^#EXT-X-STREAM-INF:?(.*)$/.exec(newLine);
  27098. if (match) {
  27099. event = {
  27100. type: 'tag',
  27101. tagType: 'stream-inf'
  27102. };
  27103. if (match[1]) {
  27104. event.attributes = parseAttributes$1(match[1]);
  27105. if (event.attributes.RESOLUTION) {
  27106. var split = event.attributes.RESOLUTION.split('x');
  27107. var resolution = {};
  27108. if (split[0]) {
  27109. resolution.width = parseInt(split[0], 10);
  27110. }
  27111. if (split[1]) {
  27112. resolution.height = parseInt(split[1], 10);
  27113. }
  27114. event.attributes.RESOLUTION = resolution;
  27115. }
  27116. if (event.attributes.BANDWIDTH) {
  27117. event.attributes.BANDWIDTH = parseInt(event.attributes.BANDWIDTH, 10);
  27118. }
  27119. if (event.attributes['FRAME-RATE']) {
  27120. event.attributes['FRAME-RATE'] = parseFloat(event.attributes['FRAME-RATE']);
  27121. }
  27122. if (event.attributes['PROGRAM-ID']) {
  27123. event.attributes['PROGRAM-ID'] = parseInt(event.attributes['PROGRAM-ID'], 10);
  27124. }
  27125. }
  27126. _this2.trigger('data', event);
  27127. return;
  27128. }
  27129. match = /^#EXT-X-MEDIA:?(.*)$/.exec(newLine);
  27130. if (match) {
  27131. event = {
  27132. type: 'tag',
  27133. tagType: 'media'
  27134. };
  27135. if (match[1]) {
  27136. event.attributes = parseAttributes$1(match[1]);
  27137. }
  27138. _this2.trigger('data', event);
  27139. return;
  27140. }
  27141. match = /^#EXT-X-ENDLIST/.exec(newLine);
  27142. if (match) {
  27143. _this2.trigger('data', {
  27144. type: 'tag',
  27145. tagType: 'endlist'
  27146. });
  27147. return;
  27148. }
  27149. match = /^#EXT-X-DISCONTINUITY/.exec(newLine);
  27150. if (match) {
  27151. _this2.trigger('data', {
  27152. type: 'tag',
  27153. tagType: 'discontinuity'
  27154. });
  27155. return;
  27156. }
  27157. match = /^#EXT-X-PROGRAM-DATE-TIME:?(.*)$/.exec(newLine);
  27158. if (match) {
  27159. event = {
  27160. type: 'tag',
  27161. tagType: 'program-date-time'
  27162. };
  27163. if (match[1]) {
  27164. event.dateTimeString = match[1];
  27165. event.dateTimeObject = new Date(match[1]);
  27166. }
  27167. _this2.trigger('data', event);
  27168. return;
  27169. }
  27170. match = /^#EXT-X-KEY:?(.*)$/.exec(newLine);
  27171. if (match) {
  27172. event = {
  27173. type: 'tag',
  27174. tagType: 'key'
  27175. };
  27176. if (match[1]) {
  27177. event.attributes = parseAttributes$1(match[1]); // parse the IV string into a Uint32Array
  27178. if (event.attributes.IV) {
  27179. if (event.attributes.IV.substring(0, 2).toLowerCase() === '0x') {
  27180. event.attributes.IV = event.attributes.IV.substring(2);
  27181. }
  27182. event.attributes.IV = event.attributes.IV.match(/.{8}/g);
  27183. event.attributes.IV[0] = parseInt(event.attributes.IV[0], 16);
  27184. event.attributes.IV[1] = parseInt(event.attributes.IV[1], 16);
  27185. event.attributes.IV[2] = parseInt(event.attributes.IV[2], 16);
  27186. event.attributes.IV[3] = parseInt(event.attributes.IV[3], 16);
  27187. event.attributes.IV = new Uint32Array(event.attributes.IV);
  27188. }
  27189. }
  27190. _this2.trigger('data', event);
  27191. return;
  27192. }
  27193. match = /^#EXT-X-START:?(.*)$/.exec(newLine);
  27194. if (match) {
  27195. event = {
  27196. type: 'tag',
  27197. tagType: 'start'
  27198. };
  27199. if (match[1]) {
  27200. event.attributes = parseAttributes$1(match[1]);
  27201. event.attributes['TIME-OFFSET'] = parseFloat(event.attributes['TIME-OFFSET']);
  27202. event.attributes.PRECISE = /YES/.test(event.attributes.PRECISE);
  27203. }
  27204. _this2.trigger('data', event);
  27205. return;
  27206. }
  27207. match = /^#EXT-X-CUE-OUT-CONT:?(.*)?$/.exec(newLine);
  27208. if (match) {
  27209. event = {
  27210. type: 'tag',
  27211. tagType: 'cue-out-cont'
  27212. };
  27213. if (match[1]) {
  27214. event.data = match[1];
  27215. } else {
  27216. event.data = '';
  27217. }
  27218. _this2.trigger('data', event);
  27219. return;
  27220. }
  27221. match = /^#EXT-X-CUE-OUT:?(.*)?$/.exec(newLine);
  27222. if (match) {
  27223. event = {
  27224. type: 'tag',
  27225. tagType: 'cue-out'
  27226. };
  27227. if (match[1]) {
  27228. event.data = match[1];
  27229. } else {
  27230. event.data = '';
  27231. }
  27232. _this2.trigger('data', event);
  27233. return;
  27234. }
  27235. match = /^#EXT-X-CUE-IN:?(.*)?$/.exec(newLine);
  27236. if (match) {
  27237. event = {
  27238. type: 'tag',
  27239. tagType: 'cue-in'
  27240. };
  27241. if (match[1]) {
  27242. event.data = match[1];
  27243. } else {
  27244. event.data = '';
  27245. }
  27246. _this2.trigger('data', event);
  27247. return;
  27248. }
  27249. match = /^#EXT-X-SKIP:(.*)$/.exec(newLine);
  27250. if (match && match[1]) {
  27251. event = {
  27252. type: 'tag',
  27253. tagType: 'skip'
  27254. };
  27255. event.attributes = parseAttributes$1(match[1]);
  27256. if (event.attributes.hasOwnProperty('SKIPPED-SEGMENTS')) {
  27257. event.attributes['SKIPPED-SEGMENTS'] = parseInt(event.attributes['SKIPPED-SEGMENTS'], 10);
  27258. }
  27259. if (event.attributes.hasOwnProperty('RECENTLY-REMOVED-DATERANGES')) {
  27260. event.attributes['RECENTLY-REMOVED-DATERANGES'] = event.attributes['RECENTLY-REMOVED-DATERANGES'].split(TAB);
  27261. }
  27262. _this2.trigger('data', event);
  27263. return;
  27264. }
  27265. match = /^#EXT-X-PART:(.*)$/.exec(newLine);
  27266. if (match && match[1]) {
  27267. event = {
  27268. type: 'tag',
  27269. tagType: 'part'
  27270. };
  27271. event.attributes = parseAttributes$1(match[1]);
  27272. ['DURATION'].forEach(function (key) {
  27273. if (event.attributes.hasOwnProperty(key)) {
  27274. event.attributes[key] = parseFloat(event.attributes[key]);
  27275. }
  27276. });
  27277. ['INDEPENDENT', 'GAP'].forEach(function (key) {
  27278. if (event.attributes.hasOwnProperty(key)) {
  27279. event.attributes[key] = /YES/.test(event.attributes[key]);
  27280. }
  27281. });
  27282. if (event.attributes.hasOwnProperty('BYTERANGE')) {
  27283. event.attributes.byterange = parseByterange(event.attributes.BYTERANGE);
  27284. }
  27285. _this2.trigger('data', event);
  27286. return;
  27287. }
  27288. match = /^#EXT-X-SERVER-CONTROL:(.*)$/.exec(newLine);
  27289. if (match && match[1]) {
  27290. event = {
  27291. type: 'tag',
  27292. tagType: 'server-control'
  27293. };
  27294. event.attributes = parseAttributes$1(match[1]);
  27295. ['CAN-SKIP-UNTIL', 'PART-HOLD-BACK', 'HOLD-BACK'].forEach(function (key) {
  27296. if (event.attributes.hasOwnProperty(key)) {
  27297. event.attributes[key] = parseFloat(event.attributes[key]);
  27298. }
  27299. });
  27300. ['CAN-SKIP-DATERANGES', 'CAN-BLOCK-RELOAD'].forEach(function (key) {
  27301. if (event.attributes.hasOwnProperty(key)) {
  27302. event.attributes[key] = /YES/.test(event.attributes[key]);
  27303. }
  27304. });
  27305. _this2.trigger('data', event);
  27306. return;
  27307. }
  27308. match = /^#EXT-X-PART-INF:(.*)$/.exec(newLine);
  27309. if (match && match[1]) {
  27310. event = {
  27311. type: 'tag',
  27312. tagType: 'part-inf'
  27313. };
  27314. event.attributes = parseAttributes$1(match[1]);
  27315. ['PART-TARGET'].forEach(function (key) {
  27316. if (event.attributes.hasOwnProperty(key)) {
  27317. event.attributes[key] = parseFloat(event.attributes[key]);
  27318. }
  27319. });
  27320. _this2.trigger('data', event);
  27321. return;
  27322. }
  27323. match = /^#EXT-X-PRELOAD-HINT:(.*)$/.exec(newLine);
  27324. if (match && match[1]) {
  27325. event = {
  27326. type: 'tag',
  27327. tagType: 'preload-hint'
  27328. };
  27329. event.attributes = parseAttributes$1(match[1]);
  27330. ['BYTERANGE-START', 'BYTERANGE-LENGTH'].forEach(function (key) {
  27331. if (event.attributes.hasOwnProperty(key)) {
  27332. event.attributes[key] = parseInt(event.attributes[key], 10);
  27333. var subkey = key === 'BYTERANGE-LENGTH' ? 'length' : 'offset';
  27334. event.attributes.byterange = event.attributes.byterange || {};
  27335. event.attributes.byterange[subkey] = event.attributes[key]; // only keep the parsed byterange object.
  27336. delete event.attributes[key];
  27337. }
  27338. });
  27339. _this2.trigger('data', event);
  27340. return;
  27341. }
  27342. match = /^#EXT-X-RENDITION-REPORT:(.*)$/.exec(newLine);
  27343. if (match && match[1]) {
  27344. event = {
  27345. type: 'tag',
  27346. tagType: 'rendition-report'
  27347. };
  27348. event.attributes = parseAttributes$1(match[1]);
  27349. ['LAST-MSN', 'LAST-PART'].forEach(function (key) {
  27350. if (event.attributes.hasOwnProperty(key)) {
  27351. event.attributes[key] = parseInt(event.attributes[key], 10);
  27352. }
  27353. });
  27354. _this2.trigger('data', event);
  27355. return;
  27356. } // unknown tag type
  27357. _this2.trigger('data', {
  27358. type: 'tag',
  27359. data: newLine.slice(4)
  27360. });
  27361. });
  27362. }
  27363. /**
  27364. * Add a parser for custom headers
  27365. *
  27366. * @param {Object} options a map of options for the added parser
  27367. * @param {RegExp} options.expression a regular expression to match the custom header
  27368. * @param {string} options.customType the custom type to register to the output
  27369. * @param {Function} [options.dataParser] function to parse the line into an object
  27370. * @param {boolean} [options.segment] should tag data be attached to the segment object
  27371. */
  27372. ;
  27373. _proto.addParser = function addParser(_ref) {
  27374. var _this3 = this;
  27375. var expression = _ref.expression,
  27376. customType = _ref.customType,
  27377. dataParser = _ref.dataParser,
  27378. segment = _ref.segment;
  27379. if (typeof dataParser !== 'function') {
  27380. dataParser = function dataParser(line) {
  27381. return line;
  27382. };
  27383. }
  27384. this.customParsers.push(function (line) {
  27385. var match = expression.exec(line);
  27386. if (match) {
  27387. _this3.trigger('data', {
  27388. type: 'custom',
  27389. data: dataParser(line),
  27390. customType: customType,
  27391. segment: segment
  27392. });
  27393. return true;
  27394. }
  27395. });
  27396. }
  27397. /**
  27398. * Add a custom header mapper
  27399. *
  27400. * @param {Object} options
  27401. * @param {RegExp} options.expression a regular expression to match the custom header
  27402. * @param {Function} options.map function to translate tag into a different tag
  27403. */
  27404. ;
  27405. _proto.addTagMapper = function addTagMapper(_ref2) {
  27406. var expression = _ref2.expression,
  27407. map = _ref2.map;
  27408. var mapFn = function mapFn(line) {
  27409. if (expression.test(line)) {
  27410. return map(line);
  27411. }
  27412. return line;
  27413. };
  27414. this.tagMappers.push(mapFn);
  27415. };
  27416. return ParseStream;
  27417. }(Stream);
  27418. var camelCase = function camelCase(str) {
  27419. return str.toLowerCase().replace(/-(\w)/g, function (a) {
  27420. return a[1].toUpperCase();
  27421. });
  27422. };
  27423. var camelCaseKeys = function camelCaseKeys(attributes) {
  27424. var result = {};
  27425. Object.keys(attributes).forEach(function (key) {
  27426. result[camelCase(key)] = attributes[key];
  27427. });
  27428. return result;
  27429. }; // set SERVER-CONTROL hold back based upon targetDuration and partTargetDuration
  27430. // we need this helper because defaults are based upon targetDuration and
  27431. // partTargetDuration being set, but they may not be if SERVER-CONTROL appears before
  27432. // target durations are set.
  27433. var setHoldBack = function setHoldBack(manifest) {
  27434. var serverControl = manifest.serverControl,
  27435. targetDuration = manifest.targetDuration,
  27436. partTargetDuration = manifest.partTargetDuration;
  27437. if (!serverControl) {
  27438. return;
  27439. }
  27440. var tag = '#EXT-X-SERVER-CONTROL';
  27441. var hb = 'holdBack';
  27442. var phb = 'partHoldBack';
  27443. var minTargetDuration = targetDuration && targetDuration * 3;
  27444. var minPartDuration = partTargetDuration && partTargetDuration * 2;
  27445. if (targetDuration && !serverControl.hasOwnProperty(hb)) {
  27446. serverControl[hb] = minTargetDuration;
  27447. this.trigger('info', {
  27448. message: tag + " defaulting HOLD-BACK to targetDuration * 3 (" + minTargetDuration + ")."
  27449. });
  27450. }
  27451. if (minTargetDuration && serverControl[hb] < minTargetDuration) {
  27452. this.trigger('warn', {
  27453. message: tag + " clamping HOLD-BACK (" + serverControl[hb] + ") to targetDuration * 3 (" + minTargetDuration + ")"
  27454. });
  27455. serverControl[hb] = minTargetDuration;
  27456. } // default no part hold back to part target duration * 3
  27457. if (partTargetDuration && !serverControl.hasOwnProperty(phb)) {
  27458. serverControl[phb] = partTargetDuration * 3;
  27459. this.trigger('info', {
  27460. message: tag + " defaulting PART-HOLD-BACK to partTargetDuration * 3 (" + serverControl[phb] + ")."
  27461. });
  27462. } // if part hold back is too small default it to part target duration * 2
  27463. if (partTargetDuration && serverControl[phb] < minPartDuration) {
  27464. this.trigger('warn', {
  27465. message: tag + " clamping PART-HOLD-BACK (" + serverControl[phb] + ") to partTargetDuration * 2 (" + minPartDuration + ")."
  27466. });
  27467. serverControl[phb] = minPartDuration;
  27468. }
  27469. };
  27470. /**
  27471. * A parser for M3U8 files. The current interpretation of the input is
  27472. * exposed as a property `manifest` on parser objects. It's just two lines to
  27473. * create and parse a manifest once you have the contents available as a string:
  27474. *
  27475. * ```js
  27476. * var parser = new m3u8.Parser();
  27477. * parser.push(xhr.responseText);
  27478. * ```
  27479. *
  27480. * New input can later be applied to update the manifest object by calling
  27481. * `push` again.
  27482. *
  27483. * The parser attempts to create a usable manifest object even if the
  27484. * underlying input is somewhat nonsensical. It emits `info` and `warning`
  27485. * events during the parse if it encounters input that seems invalid or
  27486. * requires some property of the manifest object to be defaulted.
  27487. *
  27488. * @class Parser
  27489. * @extends Stream
  27490. */
  27491. var Parser = /*#__PURE__*/function (_Stream) {
  27492. inheritsLoose(Parser, _Stream);
  27493. function Parser() {
  27494. var _this;
  27495. _this = _Stream.call(this) || this;
  27496. _this.lineStream = new LineStream();
  27497. _this.parseStream = new ParseStream();
  27498. _this.lineStream.pipe(_this.parseStream);
  27499. /* eslint-disable consistent-this */
  27500. var self = assertThisInitialized(_this);
  27501. /* eslint-enable consistent-this */
  27502. var uris = [];
  27503. var currentUri = {}; // if specified, the active EXT-X-MAP definition
  27504. var currentMap; // if specified, the active decryption key
  27505. var _key;
  27506. var hasParts = false;
  27507. var noop = function noop() {};
  27508. var defaultMediaGroups = {
  27509. 'AUDIO': {},
  27510. 'VIDEO': {},
  27511. 'CLOSED-CAPTIONS': {},
  27512. 'SUBTITLES': {}
  27513. }; // This is the Widevine UUID from DASH IF IOP. The same exact string is
  27514. // used in MPDs with Widevine encrypted streams.
  27515. var widevineUuid = 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed'; // group segments into numbered timelines delineated by discontinuities
  27516. var currentTimeline = 0; // the manifest is empty until the parse stream begins delivering data
  27517. _this.manifest = {
  27518. allowCache: true,
  27519. discontinuityStarts: [],
  27520. segments: []
  27521. }; // keep track of the last seen segment's byte range end, as segments are not required
  27522. // to provide the offset, in which case it defaults to the next byte after the
  27523. // previous segment
  27524. var lastByterangeEnd = 0; // keep track of the last seen part's byte range end.
  27525. var lastPartByterangeEnd = 0;
  27526. _this.on('end', function () {
  27527. // only add preloadSegment if we don't yet have a uri for it.
  27528. // and we actually have parts/preloadHints
  27529. if (currentUri.uri || !currentUri.parts && !currentUri.preloadHints) {
  27530. return;
  27531. }
  27532. if (!currentUri.map && currentMap) {
  27533. currentUri.map = currentMap;
  27534. }
  27535. if (!currentUri.key && _key) {
  27536. currentUri.key = _key;
  27537. }
  27538. if (!currentUri.timeline && typeof currentTimeline === 'number') {
  27539. currentUri.timeline = currentTimeline;
  27540. }
  27541. _this.manifest.preloadSegment = currentUri;
  27542. }); // update the manifest with the m3u8 entry from the parse stream
  27543. _this.parseStream.on('data', function (entry) {
  27544. var mediaGroup;
  27545. var rendition;
  27546. ({
  27547. tag: function tag() {
  27548. // switch based on the tag type
  27549. (({
  27550. version: function version() {
  27551. if (entry.version) {
  27552. this.manifest.version = entry.version;
  27553. }
  27554. },
  27555. 'allow-cache': function allowCache() {
  27556. this.manifest.allowCache = entry.allowed;
  27557. if (!('allowed' in entry)) {
  27558. this.trigger('info', {
  27559. message: 'defaulting allowCache to YES'
  27560. });
  27561. this.manifest.allowCache = true;
  27562. }
  27563. },
  27564. byterange: function byterange() {
  27565. var byterange = {};
  27566. if ('length' in entry) {
  27567. currentUri.byterange = byterange;
  27568. byterange.length = entry.length;
  27569. if (!('offset' in entry)) {
  27570. /*
  27571. * From the latest spec (as of this writing):
  27572. * https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.2
  27573. *
  27574. * Same text since EXT-X-BYTERANGE's introduction in draft 7:
  27575. * https://tools.ietf.org/html/draft-pantos-http-live-streaming-07#section-3.3.1)
  27576. *
  27577. * "If o [offset] is not present, the sub-range begins at the next byte
  27578. * following the sub-range of the previous media segment."
  27579. */
  27580. entry.offset = lastByterangeEnd;
  27581. }
  27582. }
  27583. if ('offset' in entry) {
  27584. currentUri.byterange = byterange;
  27585. byterange.offset = entry.offset;
  27586. }
  27587. lastByterangeEnd = byterange.offset + byterange.length;
  27588. },
  27589. endlist: function endlist() {
  27590. this.manifest.endList = true;
  27591. },
  27592. inf: function inf() {
  27593. if (!('mediaSequence' in this.manifest)) {
  27594. this.manifest.mediaSequence = 0;
  27595. this.trigger('info', {
  27596. message: 'defaulting media sequence to zero'
  27597. });
  27598. }
  27599. if (!('discontinuitySequence' in this.manifest)) {
  27600. this.manifest.discontinuitySequence = 0;
  27601. this.trigger('info', {
  27602. message: 'defaulting discontinuity sequence to zero'
  27603. });
  27604. }
  27605. if (entry.duration > 0) {
  27606. currentUri.duration = entry.duration;
  27607. }
  27608. if (entry.duration === 0) {
  27609. currentUri.duration = 0.01;
  27610. this.trigger('info', {
  27611. message: 'updating zero segment duration to a small value'
  27612. });
  27613. }
  27614. this.manifest.segments = uris;
  27615. },
  27616. key: function key() {
  27617. if (!entry.attributes) {
  27618. this.trigger('warn', {
  27619. message: 'ignoring key declaration without attribute list'
  27620. });
  27621. return;
  27622. } // clear the active encryption key
  27623. if (entry.attributes.METHOD === 'NONE') {
  27624. _key = null;
  27625. return;
  27626. }
  27627. if (!entry.attributes.URI) {
  27628. this.trigger('warn', {
  27629. message: 'ignoring key declaration without URI'
  27630. });
  27631. return;
  27632. }
  27633. if (entry.attributes.KEYFORMAT === 'com.apple.streamingkeydelivery') {
  27634. this.manifest.contentProtection = this.manifest.contentProtection || {}; // TODO: add full support for this.
  27635. this.manifest.contentProtection['com.apple.fps.1_0'] = {
  27636. attributes: entry.attributes
  27637. };
  27638. return;
  27639. }
  27640. if (entry.attributes.KEYFORMAT === 'com.microsoft.playready') {
  27641. this.manifest.contentProtection = this.manifest.contentProtection || {}; // TODO: add full support for this.
  27642. this.manifest.contentProtection['com.microsoft.playready'] = {
  27643. uri: entry.attributes.URI
  27644. };
  27645. return;
  27646. } // check if the content is encrypted for Widevine
  27647. // Widevine/HLS spec: https://storage.googleapis.com/wvdocs/Widevine_DRM_HLS.pdf
  27648. if (entry.attributes.KEYFORMAT === widevineUuid) {
  27649. var VALID_METHODS = ['SAMPLE-AES', 'SAMPLE-AES-CTR', 'SAMPLE-AES-CENC'];
  27650. if (VALID_METHODS.indexOf(entry.attributes.METHOD) === -1) {
  27651. this.trigger('warn', {
  27652. message: 'invalid key method provided for Widevine'
  27653. });
  27654. return;
  27655. }
  27656. if (entry.attributes.METHOD === 'SAMPLE-AES-CENC') {
  27657. this.trigger('warn', {
  27658. message: 'SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead'
  27659. });
  27660. }
  27661. if (entry.attributes.URI.substring(0, 23) !== 'data:text/plain;base64,') {
  27662. this.trigger('warn', {
  27663. message: 'invalid key URI provided for Widevine'
  27664. });
  27665. return;
  27666. }
  27667. if (!(entry.attributes.KEYID && entry.attributes.KEYID.substring(0, 2) === '0x')) {
  27668. this.trigger('warn', {
  27669. message: 'invalid key ID provided for Widevine'
  27670. });
  27671. return;
  27672. } // if Widevine key attributes are valid, store them as `contentProtection`
  27673. // on the manifest to emulate Widevine tag structure in a DASH mpd
  27674. this.manifest.contentProtection = this.manifest.contentProtection || {};
  27675. this.manifest.contentProtection['com.widevine.alpha'] = {
  27676. attributes: {
  27677. schemeIdUri: entry.attributes.KEYFORMAT,
  27678. // remove '0x' from the key id string
  27679. keyId: entry.attributes.KEYID.substring(2)
  27680. },
  27681. // decode the base64-encoded PSSH box
  27682. pssh: decodeB64ToUint8Array$1(entry.attributes.URI.split(',')[1])
  27683. };
  27684. return;
  27685. }
  27686. if (!entry.attributes.METHOD) {
  27687. this.trigger('warn', {
  27688. message: 'defaulting key method to AES-128'
  27689. });
  27690. } // setup an encryption key for upcoming segments
  27691. _key = {
  27692. method: entry.attributes.METHOD || 'AES-128',
  27693. uri: entry.attributes.URI
  27694. };
  27695. if (typeof entry.attributes.IV !== 'undefined') {
  27696. _key.iv = entry.attributes.IV;
  27697. }
  27698. },
  27699. 'media-sequence': function mediaSequence() {
  27700. if (!isFinite(entry.number)) {
  27701. this.trigger('warn', {
  27702. message: 'ignoring invalid media sequence: ' + entry.number
  27703. });
  27704. return;
  27705. }
  27706. this.manifest.mediaSequence = entry.number;
  27707. },
  27708. 'discontinuity-sequence': function discontinuitySequence() {
  27709. if (!isFinite(entry.number)) {
  27710. this.trigger('warn', {
  27711. message: 'ignoring invalid discontinuity sequence: ' + entry.number
  27712. });
  27713. return;
  27714. }
  27715. this.manifest.discontinuitySequence = entry.number;
  27716. currentTimeline = entry.number;
  27717. },
  27718. 'playlist-type': function playlistType() {
  27719. if (!/VOD|EVENT/.test(entry.playlistType)) {
  27720. this.trigger('warn', {
  27721. message: 'ignoring unknown playlist type: ' + entry.playlist
  27722. });
  27723. return;
  27724. }
  27725. this.manifest.playlistType = entry.playlistType;
  27726. },
  27727. map: function map() {
  27728. currentMap = {};
  27729. if (entry.uri) {
  27730. currentMap.uri = entry.uri;
  27731. }
  27732. if (entry.byterange) {
  27733. currentMap.byterange = entry.byterange;
  27734. }
  27735. if (_key) {
  27736. currentMap.key = _key;
  27737. }
  27738. },
  27739. 'stream-inf': function streamInf() {
  27740. this.manifest.playlists = uris;
  27741. this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
  27742. if (!entry.attributes) {
  27743. this.trigger('warn', {
  27744. message: 'ignoring empty stream-inf attributes'
  27745. });
  27746. return;
  27747. }
  27748. if (!currentUri.attributes) {
  27749. currentUri.attributes = {};
  27750. }
  27751. _extends_1(currentUri.attributes, entry.attributes);
  27752. },
  27753. media: function media() {
  27754. this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
  27755. if (!(entry.attributes && entry.attributes.TYPE && entry.attributes['GROUP-ID'] && entry.attributes.NAME)) {
  27756. this.trigger('warn', {
  27757. message: 'ignoring incomplete or missing media group'
  27758. });
  27759. return;
  27760. } // find the media group, creating defaults as necessary
  27761. var mediaGroupType = this.manifest.mediaGroups[entry.attributes.TYPE];
  27762. mediaGroupType[entry.attributes['GROUP-ID']] = mediaGroupType[entry.attributes['GROUP-ID']] || {};
  27763. mediaGroup = mediaGroupType[entry.attributes['GROUP-ID']]; // collect the rendition metadata
  27764. rendition = {
  27765. "default": /yes/i.test(entry.attributes.DEFAULT)
  27766. };
  27767. if (rendition["default"]) {
  27768. rendition.autoselect = true;
  27769. } else {
  27770. rendition.autoselect = /yes/i.test(entry.attributes.AUTOSELECT);
  27771. }
  27772. if (entry.attributes.LANGUAGE) {
  27773. rendition.language = entry.attributes.LANGUAGE;
  27774. }
  27775. if (entry.attributes.URI) {
  27776. rendition.uri = entry.attributes.URI;
  27777. }
  27778. if (entry.attributes['INSTREAM-ID']) {
  27779. rendition.instreamId = entry.attributes['INSTREAM-ID'];
  27780. }
  27781. if (entry.attributes.CHARACTERISTICS) {
  27782. rendition.characteristics = entry.attributes.CHARACTERISTICS;
  27783. }
  27784. if (entry.attributes.FORCED) {
  27785. rendition.forced = /yes/i.test(entry.attributes.FORCED);
  27786. } // insert the new rendition
  27787. mediaGroup[entry.attributes.NAME] = rendition;
  27788. },
  27789. discontinuity: function discontinuity() {
  27790. currentTimeline += 1;
  27791. currentUri.discontinuity = true;
  27792. this.manifest.discontinuityStarts.push(uris.length);
  27793. },
  27794. 'program-date-time': function programDateTime() {
  27795. if (typeof this.manifest.dateTimeString === 'undefined') {
  27796. // PROGRAM-DATE-TIME is a media-segment tag, but for backwards
  27797. // compatibility, we add the first occurence of the PROGRAM-DATE-TIME tag
  27798. // to the manifest object
  27799. // TODO: Consider removing this in future major version
  27800. this.manifest.dateTimeString = entry.dateTimeString;
  27801. this.manifest.dateTimeObject = entry.dateTimeObject;
  27802. }
  27803. currentUri.dateTimeString = entry.dateTimeString;
  27804. currentUri.dateTimeObject = entry.dateTimeObject;
  27805. },
  27806. targetduration: function targetduration() {
  27807. if (!isFinite(entry.duration) || entry.duration < 0) {
  27808. this.trigger('warn', {
  27809. message: 'ignoring invalid target duration: ' + entry.duration
  27810. });
  27811. return;
  27812. }
  27813. this.manifest.targetDuration = entry.duration;
  27814. setHoldBack.call(this, this.manifest);
  27815. },
  27816. start: function start() {
  27817. if (!entry.attributes || isNaN(entry.attributes['TIME-OFFSET'])) {
  27818. this.trigger('warn', {
  27819. message: 'ignoring start declaration without appropriate attribute list'
  27820. });
  27821. return;
  27822. }
  27823. this.manifest.start = {
  27824. timeOffset: entry.attributes['TIME-OFFSET'],
  27825. precise: entry.attributes.PRECISE
  27826. };
  27827. },
  27828. 'cue-out': function cueOut() {
  27829. currentUri.cueOut = entry.data;
  27830. },
  27831. 'cue-out-cont': function cueOutCont() {
  27832. currentUri.cueOutCont = entry.data;
  27833. },
  27834. 'cue-in': function cueIn() {
  27835. currentUri.cueIn = entry.data;
  27836. },
  27837. 'skip': function skip() {
  27838. this.manifest.skip = camelCaseKeys(entry.attributes);
  27839. this.warnOnMissingAttributes_('#EXT-X-SKIP', entry.attributes, ['SKIPPED-SEGMENTS']);
  27840. },
  27841. 'part': function part() {
  27842. var _this2 = this;
  27843. hasParts = true; // parts are always specifed before a segment
  27844. var segmentIndex = this.manifest.segments.length;
  27845. var part = camelCaseKeys(entry.attributes);
  27846. currentUri.parts = currentUri.parts || [];
  27847. currentUri.parts.push(part);
  27848. if (part.byterange) {
  27849. if (!part.byterange.hasOwnProperty('offset')) {
  27850. part.byterange.offset = lastPartByterangeEnd;
  27851. }
  27852. lastPartByterangeEnd = part.byterange.offset + part.byterange.length;
  27853. }
  27854. var partIndex = currentUri.parts.length - 1;
  27855. this.warnOnMissingAttributes_("#EXT-X-PART #" + partIndex + " for segment #" + segmentIndex, entry.attributes, ['URI', 'DURATION']);
  27856. if (this.manifest.renditionReports) {
  27857. this.manifest.renditionReports.forEach(function (r, i) {
  27858. if (!r.hasOwnProperty('lastPart')) {
  27859. _this2.trigger('warn', {
  27860. message: "#EXT-X-RENDITION-REPORT #" + i + " lacks required attribute(s): LAST-PART"
  27861. });
  27862. }
  27863. });
  27864. }
  27865. },
  27866. 'server-control': function serverControl() {
  27867. var attrs = this.manifest.serverControl = camelCaseKeys(entry.attributes);
  27868. if (!attrs.hasOwnProperty('canBlockReload')) {
  27869. attrs.canBlockReload = false;
  27870. this.trigger('info', {
  27871. message: '#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false'
  27872. });
  27873. }
  27874. setHoldBack.call(this, this.manifest);
  27875. if (attrs.canSkipDateranges && !attrs.hasOwnProperty('canSkipUntil')) {
  27876. this.trigger('warn', {
  27877. message: '#EXT-X-SERVER-CONTROL lacks required attribute CAN-SKIP-UNTIL which is required when CAN-SKIP-DATERANGES is set'
  27878. });
  27879. }
  27880. },
  27881. 'preload-hint': function preloadHint() {
  27882. // parts are always specifed before a segment
  27883. var segmentIndex = this.manifest.segments.length;
  27884. var hint = camelCaseKeys(entry.attributes);
  27885. var isPart = hint.type && hint.type === 'PART';
  27886. currentUri.preloadHints = currentUri.preloadHints || [];
  27887. currentUri.preloadHints.push(hint);
  27888. if (hint.byterange) {
  27889. if (!hint.byterange.hasOwnProperty('offset')) {
  27890. // use last part byterange end or zero if not a part.
  27891. hint.byterange.offset = isPart ? lastPartByterangeEnd : 0;
  27892. if (isPart) {
  27893. lastPartByterangeEnd = hint.byterange.offset + hint.byterange.length;
  27894. }
  27895. }
  27896. }
  27897. var index = currentUri.preloadHints.length - 1;
  27898. this.warnOnMissingAttributes_("#EXT-X-PRELOAD-HINT #" + index + " for segment #" + segmentIndex, entry.attributes, ['TYPE', 'URI']);
  27899. if (!hint.type) {
  27900. return;
  27901. } // search through all preload hints except for the current one for
  27902. // a duplicate type.
  27903. for (var i = 0; i < currentUri.preloadHints.length - 1; i++) {
  27904. var otherHint = currentUri.preloadHints[i];
  27905. if (!otherHint.type) {
  27906. continue;
  27907. }
  27908. if (otherHint.type === hint.type) {
  27909. this.trigger('warn', {
  27910. message: "#EXT-X-PRELOAD-HINT #" + index + " for segment #" + segmentIndex + " has the same TYPE " + hint.type + " as preload hint #" + i
  27911. });
  27912. }
  27913. }
  27914. },
  27915. 'rendition-report': function renditionReport() {
  27916. var report = camelCaseKeys(entry.attributes);
  27917. this.manifest.renditionReports = this.manifest.renditionReports || [];
  27918. this.manifest.renditionReports.push(report);
  27919. var index = this.manifest.renditionReports.length - 1;
  27920. var required = ['LAST-MSN', 'URI'];
  27921. if (hasParts) {
  27922. required.push('LAST-PART');
  27923. }
  27924. this.warnOnMissingAttributes_("#EXT-X-RENDITION-REPORT #" + index, entry.attributes, required);
  27925. },
  27926. 'part-inf': function partInf() {
  27927. this.manifest.partInf = camelCaseKeys(entry.attributes);
  27928. this.warnOnMissingAttributes_('#EXT-X-PART-INF', entry.attributes, ['PART-TARGET']);
  27929. if (this.manifest.partInf.partTarget) {
  27930. this.manifest.partTargetDuration = this.manifest.partInf.partTarget;
  27931. }
  27932. setHoldBack.call(this, this.manifest);
  27933. }
  27934. })[entry.tagType] || noop).call(self);
  27935. },
  27936. uri: function uri() {
  27937. currentUri.uri = entry.uri;
  27938. uris.push(currentUri); // if no explicit duration was declared, use the target duration
  27939. if (this.manifest.targetDuration && !('duration' in currentUri)) {
  27940. this.trigger('warn', {
  27941. message: 'defaulting segment duration to the target duration'
  27942. });
  27943. currentUri.duration = this.manifest.targetDuration;
  27944. } // annotate with encryption information, if necessary
  27945. if (_key) {
  27946. currentUri.key = _key;
  27947. }
  27948. currentUri.timeline = currentTimeline; // annotate with initialization segment information, if necessary
  27949. if (currentMap) {
  27950. currentUri.map = currentMap;
  27951. } // reset the last byterange end as it needs to be 0 between parts
  27952. lastPartByterangeEnd = 0; // prepare for the next URI
  27953. currentUri = {};
  27954. },
  27955. comment: function comment() {// comments are not important for playback
  27956. },
  27957. custom: function custom() {
  27958. // if this is segment-level data attach the output to the segment
  27959. if (entry.segment) {
  27960. currentUri.custom = currentUri.custom || {};
  27961. currentUri.custom[entry.customType] = entry.data; // if this is manifest-level data attach to the top level manifest object
  27962. } else {
  27963. this.manifest.custom = this.manifest.custom || {};
  27964. this.manifest.custom[entry.customType] = entry.data;
  27965. }
  27966. }
  27967. })[entry.type].call(self);
  27968. });
  27969. return _this;
  27970. }
  27971. var _proto = Parser.prototype;
  27972. _proto.warnOnMissingAttributes_ = function warnOnMissingAttributes_(identifier, attributes, required) {
  27973. var missing = [];
  27974. required.forEach(function (key) {
  27975. if (!attributes.hasOwnProperty(key)) {
  27976. missing.push(key);
  27977. }
  27978. });
  27979. if (missing.length) {
  27980. this.trigger('warn', {
  27981. message: identifier + " lacks required attribute(s): " + missing.join(', ')
  27982. });
  27983. }
  27984. }
  27985. /**
  27986. * Parse the input string and update the manifest object.
  27987. *
  27988. * @param {string} chunk a potentially incomplete portion of the manifest
  27989. */
  27990. ;
  27991. _proto.push = function push(chunk) {
  27992. this.lineStream.push(chunk);
  27993. }
  27994. /**
  27995. * Flush any remaining input. This can be handy if the last line of an M3U8
  27996. * manifest did not contain a trailing newline but the file has been
  27997. * completely received.
  27998. */
  27999. ;
  28000. _proto.end = function end() {
  28001. // flush any buffered input
  28002. this.lineStream.push('\n');
  28003. this.trigger('end');
  28004. }
  28005. /**
  28006. * Add an additional parser for non-standard tags
  28007. *
  28008. * @param {Object} options a map of options for the added parser
  28009. * @param {RegExp} options.expression a regular expression to match the custom header
  28010. * @param {string} options.type the type to register to the output
  28011. * @param {Function} [options.dataParser] function to parse the line into an object
  28012. * @param {boolean} [options.segment] should tag data be attached to the segment object
  28013. */
  28014. ;
  28015. _proto.addParser = function addParser(options) {
  28016. this.parseStream.addParser(options);
  28017. }
  28018. /**
  28019. * Add a custom header mapper
  28020. *
  28021. * @param {Object} options
  28022. * @param {RegExp} options.expression a regular expression to match the custom header
  28023. * @param {Function} options.map function to translate tag into a different tag
  28024. */
  28025. ;
  28026. _proto.addTagMapper = function addTagMapper(options) {
  28027. this.parseStream.addTagMapper(options);
  28028. };
  28029. return Parser;
  28030. }(Stream);
  28031. var regexs = {
  28032. // to determine mime types
  28033. mp4: /^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,
  28034. webm: /^(vp0?[89]|av0?1|opus|vorbis)/,
  28035. ogg: /^(vp0?[89]|theora|flac|opus|vorbis)/,
  28036. // to determine if a codec is audio or video
  28037. video: /^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,
  28038. audio: /^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,
  28039. text: /^(stpp.ttml.im1t)/,
  28040. // mux.js support regex
  28041. muxerVideo: /^(avc0?1)/,
  28042. muxerAudio: /^(mp4a)/,
  28043. // match nothing as muxer does not support text right now.
  28044. // there cannot never be a character before the start of a string
  28045. // so this matches nothing.
  28046. muxerText: /a^/
  28047. };
  28048. var mediaTypes = ['video', 'audio', 'text'];
  28049. var upperMediaTypes = ['Video', 'Audio', 'Text'];
  28050. /**
  28051. * Replace the old apple-style `avc1.<dd>.<dd>` codec string with the standard
  28052. * `avc1.<hhhhhh>`
  28053. *
  28054. * @param {string} codec
  28055. * Codec string to translate
  28056. * @return {string}
  28057. * The translated codec string
  28058. */
  28059. var translateLegacyCodec = function translateLegacyCodec(codec) {
  28060. if (!codec) {
  28061. return codec;
  28062. }
  28063. return codec.replace(/avc1\.(\d+)\.(\d+)/i, function (orig, profile, avcLevel) {
  28064. var profileHex = ('00' + Number(profile).toString(16)).slice(-2);
  28065. var avcLevelHex = ('00' + Number(avcLevel).toString(16)).slice(-2);
  28066. return 'avc1.' + profileHex + '00' + avcLevelHex;
  28067. });
  28068. };
  28069. /**
  28070. * @typedef {Object} ParsedCodecInfo
  28071. * @property {number} codecCount
  28072. * Number of codecs parsed
  28073. * @property {string} [videoCodec]
  28074. * Parsed video codec (if found)
  28075. * @property {string} [videoObjectTypeIndicator]
  28076. * Video object type indicator (if found)
  28077. * @property {string|null} audioProfile
  28078. * Audio profile
  28079. */
  28080. /**
  28081. * Parses a codec string to retrieve the number of codecs specified, the video codec and
  28082. * object type indicator, and the audio profile.
  28083. *
  28084. * @param {string} [codecString]
  28085. * The codec string to parse
  28086. * @return {ParsedCodecInfo}
  28087. * Parsed codec info
  28088. */
  28089. var parseCodecs = function parseCodecs(codecString) {
  28090. if (codecString === void 0) {
  28091. codecString = '';
  28092. }
  28093. var codecs = codecString.split(',');
  28094. var result = [];
  28095. codecs.forEach(function (codec) {
  28096. codec = codec.trim();
  28097. var codecType;
  28098. mediaTypes.forEach(function (name) {
  28099. var match = regexs[name].exec(codec.toLowerCase());
  28100. if (!match || match.length <= 1) {
  28101. return;
  28102. }
  28103. codecType = name; // maintain codec case
  28104. var type = codec.substring(0, match[1].length);
  28105. var details = codec.replace(type, '');
  28106. result.push({
  28107. type: type,
  28108. details: details,
  28109. mediaType: name
  28110. });
  28111. });
  28112. if (!codecType) {
  28113. result.push({
  28114. type: codec,
  28115. details: '',
  28116. mediaType: 'unknown'
  28117. });
  28118. }
  28119. });
  28120. return result;
  28121. };
  28122. /**
  28123. * Returns a ParsedCodecInfo object for the default alternate audio playlist if there is
  28124. * a default alternate audio playlist for the provided audio group.
  28125. *
  28126. * @param {Object} master
  28127. * The master playlist
  28128. * @param {string} audioGroupId
  28129. * ID of the audio group for which to find the default codec info
  28130. * @return {ParsedCodecInfo}
  28131. * Parsed codec info
  28132. */
  28133. var codecsFromDefault = function codecsFromDefault(master, audioGroupId) {
  28134. if (!master.mediaGroups.AUDIO || !audioGroupId) {
  28135. return null;
  28136. }
  28137. var audioGroup = master.mediaGroups.AUDIO[audioGroupId];
  28138. if (!audioGroup) {
  28139. return null;
  28140. }
  28141. for (var name in audioGroup) {
  28142. var audioType = audioGroup[name];
  28143. if (audioType["default"] && audioType.playlists) {
  28144. // codec should be the same for all playlists within the audio type
  28145. return parseCodecs(audioType.playlists[0].attributes.CODECS);
  28146. }
  28147. }
  28148. return null;
  28149. };
  28150. var isAudioCodec = function isAudioCodec(codec) {
  28151. if (codec === void 0) {
  28152. codec = '';
  28153. }
  28154. return regexs.audio.test(codec.trim().toLowerCase());
  28155. };
  28156. var isTextCodec = function isTextCodec(codec) {
  28157. if (codec === void 0) {
  28158. codec = '';
  28159. }
  28160. return regexs.text.test(codec.trim().toLowerCase());
  28161. };
  28162. var getMimeForCodec = function getMimeForCodec(codecString) {
  28163. if (!codecString || typeof codecString !== 'string') {
  28164. return;
  28165. }
  28166. var codecs = codecString.toLowerCase().split(',').map(function (c) {
  28167. return translateLegacyCodec(c.trim());
  28168. }); // default to video type
  28169. var type = 'video'; // only change to audio type if the only codec we have is
  28170. // audio
  28171. if (codecs.length === 1 && isAudioCodec(codecs[0])) {
  28172. type = 'audio';
  28173. } else if (codecs.length === 1 && isTextCodec(codecs[0])) {
  28174. // text uses application/<container> for now
  28175. type = 'application';
  28176. } // default the container to mp4
  28177. var container = 'mp4'; // every codec must be able to go into the container
  28178. // for that container to be the correct one
  28179. if (codecs.every(function (c) {
  28180. return regexs.mp4.test(c);
  28181. })) {
  28182. container = 'mp4';
  28183. } else if (codecs.every(function (c) {
  28184. return regexs.webm.test(c);
  28185. })) {
  28186. container = 'webm';
  28187. } else if (codecs.every(function (c) {
  28188. return regexs.ogg.test(c);
  28189. })) {
  28190. container = 'ogg';
  28191. }
  28192. return type + "/" + container + ";codecs=\"" + codecString + "\"";
  28193. };
  28194. var browserSupportsCodec = function browserSupportsCodec(codecString) {
  28195. if (codecString === void 0) {
  28196. codecString = '';
  28197. }
  28198. return window.MediaSource && window.MediaSource.isTypeSupported && window.MediaSource.isTypeSupported(getMimeForCodec(codecString)) || false;
  28199. };
  28200. var muxerSupportsCodec = function muxerSupportsCodec(codecString) {
  28201. if (codecString === void 0) {
  28202. codecString = '';
  28203. }
  28204. return codecString.toLowerCase().split(',').every(function (codec) {
  28205. codec = codec.trim(); // any match is supported.
  28206. for (var i = 0; i < upperMediaTypes.length; i++) {
  28207. var type = upperMediaTypes[i];
  28208. if (regexs["muxer" + type].test(codec)) {
  28209. return true;
  28210. }
  28211. }
  28212. return false;
  28213. });
  28214. };
  28215. var DEFAULT_AUDIO_CODEC = 'mp4a.40.2';
  28216. var DEFAULT_VIDEO_CODEC = 'avc1.4d400d';
  28217. var MPEGURL_REGEX = /^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i;
  28218. var DASH_REGEX = /^application\/dash\+xml/i;
  28219. /**
  28220. * Returns a string that describes the type of source based on a video source object's
  28221. * media type.
  28222. *
  28223. * @see {@link https://dev.w3.org/html5/pf-summary/video.html#dom-source-type|Source Type}
  28224. *
  28225. * @param {string} type
  28226. * Video source object media type
  28227. * @return {('hls'|'dash'|'vhs-json'|null)}
  28228. * VHS source type string
  28229. */
  28230. var simpleTypeFromSourceType = function simpleTypeFromSourceType(type) {
  28231. if (MPEGURL_REGEX.test(type)) {
  28232. return 'hls';
  28233. }
  28234. if (DASH_REGEX.test(type)) {
  28235. return 'dash';
  28236. } // Denotes the special case of a manifest object passed to http-streaming instead of a
  28237. // source URL.
  28238. //
  28239. // See https://en.wikipedia.org/wiki/Media_type for details on specifying media types.
  28240. //
  28241. // In this case, vnd stands for vendor, video.js for the organization, VHS for this
  28242. // project, and the +json suffix identifies the structure of the media type.
  28243. if (type === 'application/vnd.videojs.vhs+json') {
  28244. return 'vhs-json';
  28245. }
  28246. return null;
  28247. };
  28248. // const log2 = Math.log2 ? Math.log2 : (x) => (Math.log(x) / Math.log(2));
  28249. // we used to do this with log2 but BigInt does not support builtin math
  28250. // Math.ceil(log2(x));
  28251. var countBits = function countBits(x) {
  28252. return x.toString(2).length;
  28253. }; // count the number of whole bytes it would take to represent a number
  28254. var countBytes = function countBytes(x) {
  28255. return Math.ceil(countBits(x) / 8);
  28256. };
  28257. var isArrayBufferView = function isArrayBufferView(obj) {
  28258. if (ArrayBuffer.isView === 'function') {
  28259. return ArrayBuffer.isView(obj);
  28260. }
  28261. return obj && obj.buffer instanceof ArrayBuffer;
  28262. };
  28263. var isTypedArray = function isTypedArray(obj) {
  28264. return isArrayBufferView(obj);
  28265. };
  28266. var toUint8 = function toUint8(bytes) {
  28267. if (bytes instanceof Uint8Array) {
  28268. return bytes;
  28269. }
  28270. if (!Array.isArray(bytes) && !isTypedArray(bytes) && !(bytes instanceof ArrayBuffer)) {
  28271. // any non-number or NaN leads to empty uint8array
  28272. // eslint-disable-next-line
  28273. if (typeof bytes !== 'number' || typeof bytes === 'number' && bytes !== bytes) {
  28274. bytes = 0;
  28275. } else {
  28276. bytes = [bytes];
  28277. }
  28278. }
  28279. return new Uint8Array(bytes && bytes.buffer || bytes, bytes && bytes.byteOffset || 0, bytes && bytes.byteLength || 0);
  28280. };
  28281. var BigInt = window.BigInt || Number;
  28282. var BYTE_TABLE = [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
  28283. var bytesToNumber = function bytesToNumber(bytes, _temp) {
  28284. var _ref = _temp === void 0 ? {} : _temp,
  28285. _ref$signed = _ref.signed,
  28286. signed = _ref$signed === void 0 ? false : _ref$signed,
  28287. _ref$le = _ref.le,
  28288. le = _ref$le === void 0 ? false : _ref$le;
  28289. bytes = toUint8(bytes);
  28290. var fn = le ? 'reduce' : 'reduceRight';
  28291. var obj = bytes[fn] ? bytes[fn] : Array.prototype[fn];
  28292. var number = obj.call(bytes, function (total, _byte, i) {
  28293. var exponent = le ? i : Math.abs(i + 1 - bytes.length);
  28294. return total + BigInt(_byte) * BYTE_TABLE[exponent];
  28295. }, BigInt(0));
  28296. if (signed) {
  28297. var max = BYTE_TABLE[bytes.length] / BigInt(2) - BigInt(1);
  28298. number = BigInt(number);
  28299. if (number > max) {
  28300. number -= max;
  28301. number -= max;
  28302. number -= BigInt(2);
  28303. }
  28304. }
  28305. return Number(number);
  28306. };
  28307. var numberToBytes = function numberToBytes(number, _temp2) {
  28308. var _ref2 = _temp2 === void 0 ? {} : _temp2,
  28309. _ref2$le = _ref2.le,
  28310. le = _ref2$le === void 0 ? false : _ref2$le; // eslint-disable-next-line
  28311. if (typeof number !== 'bigint' && typeof number !== 'number' || typeof number === 'number' && number !== number) {
  28312. number = 0;
  28313. }
  28314. number = BigInt(number);
  28315. var byteCount = countBytes(number);
  28316. var bytes = new Uint8Array(new ArrayBuffer(byteCount));
  28317. for (var i = 0; i < byteCount; i++) {
  28318. var byteIndex = le ? i : Math.abs(i + 1 - bytes.length);
  28319. bytes[byteIndex] = Number(number / BYTE_TABLE[i] & BigInt(0xFF));
  28320. if (number < 0) {
  28321. bytes[byteIndex] = Math.abs(~bytes[byteIndex]);
  28322. bytes[byteIndex] -= i === 0 ? 1 : 2;
  28323. }
  28324. }
  28325. return bytes;
  28326. };
  28327. var stringToBytes = function stringToBytes(string, stringIsBytes) {
  28328. if (typeof string !== 'string' && string && typeof string.toString === 'function') {
  28329. string = string.toString();
  28330. }
  28331. if (typeof string !== 'string') {
  28332. return new Uint8Array();
  28333. } // If the string already is bytes, we don't have to do this
  28334. // otherwise we do this so that we split multi length characters
  28335. // into individual bytes
  28336. if (!stringIsBytes) {
  28337. string = unescape(encodeURIComponent(string));
  28338. }
  28339. var view = new Uint8Array(string.length);
  28340. for (var i = 0; i < string.length; i++) {
  28341. view[i] = string.charCodeAt(i);
  28342. }
  28343. return view;
  28344. };
  28345. var concatTypedArrays = function concatTypedArrays() {
  28346. for (var _len = arguments.length, buffers = new Array(_len), _key = 0; _key < _len; _key++) {
  28347. buffers[_key] = arguments[_key];
  28348. }
  28349. buffers = buffers.filter(function (b) {
  28350. return b && (b.byteLength || b.length) && typeof b !== 'string';
  28351. });
  28352. if (buffers.length <= 1) {
  28353. // for 0 length we will return empty uint8
  28354. // for 1 length we return the first uint8
  28355. return toUint8(buffers[0]);
  28356. }
  28357. var totalLen = buffers.reduce(function (total, buf, i) {
  28358. return total + (buf.byteLength || buf.length);
  28359. }, 0);
  28360. var tempBuffer = new Uint8Array(totalLen);
  28361. var offset = 0;
  28362. buffers.forEach(function (buf) {
  28363. buf = toUint8(buf);
  28364. tempBuffer.set(buf, offset);
  28365. offset += buf.byteLength;
  28366. });
  28367. return tempBuffer;
  28368. };
  28369. /**
  28370. * Check if the bytes "b" are contained within bytes "a".
  28371. *
  28372. * @param {Uint8Array|Array} a
  28373. * Bytes to check in
  28374. *
  28375. * @param {Uint8Array|Array} b
  28376. * Bytes to check for
  28377. *
  28378. * @param {Object} options
  28379. * options
  28380. *
  28381. * @param {Array|Uint8Array} [offset=0]
  28382. * offset to use when looking at bytes in a
  28383. *
  28384. * @param {Array|Uint8Array} [mask=[]]
  28385. * mask to use on bytes before comparison.
  28386. *
  28387. * @return {boolean}
  28388. * If all bytes in b are inside of a, taking into account
  28389. * bit masks.
  28390. */
  28391. var bytesMatch = function bytesMatch(a, b, _temp3) {
  28392. var _ref3 = _temp3 === void 0 ? {} : _temp3,
  28393. _ref3$offset = _ref3.offset,
  28394. offset = _ref3$offset === void 0 ? 0 : _ref3$offset,
  28395. _ref3$mask = _ref3.mask,
  28396. mask = _ref3$mask === void 0 ? [] : _ref3$mask;
  28397. a = toUint8(a);
  28398. b = toUint8(b); // ie 11 does not support uint8 every
  28399. var fn = b.every ? b.every : Array.prototype.every;
  28400. return b.length && a.length - offset >= b.length && // ie 11 doesn't support every on uin8
  28401. fn.call(b, function (bByte, i) {
  28402. var aByte = mask[i] ? mask[i] & a[offset + i] : a[offset + i];
  28403. return bByte === aByte;
  28404. });
  28405. };
  28406. var DEFAULT_LOCATION = 'http://example.com';
  28407. var resolveUrl$1 = function resolveUrl(baseUrl, relativeUrl) {
  28408. // return early if we don't need to resolve
  28409. if (/^[a-z]+:/i.test(relativeUrl)) {
  28410. return relativeUrl;
  28411. } // if baseUrl is a data URI, ignore it and resolve everything relative to window.location
  28412. if (/^data:/.test(baseUrl)) {
  28413. baseUrl = window.location && window.location.href || '';
  28414. } // IE11 supports URL but not the URL constructor
  28415. // feature detect the behavior we want
  28416. var nativeURL = typeof window.URL === 'function';
  28417. var protocolLess = /^\/\//.test(baseUrl); // remove location if window.location isn't available (i.e. we're in node)
  28418. // and if baseUrl isn't an absolute url
  28419. var removeLocation = !window.location && !/\/\//i.test(baseUrl); // if the base URL is relative then combine with the current location
  28420. if (nativeURL) {
  28421. baseUrl = new window.URL(baseUrl, window.location || DEFAULT_LOCATION);
  28422. } else if (!/\/\//i.test(baseUrl)) {
  28423. baseUrl = urlToolkit.buildAbsoluteURL(window.location && window.location.href || '', baseUrl);
  28424. }
  28425. if (nativeURL) {
  28426. var newUrl = new URL(relativeUrl, baseUrl); // if we're a protocol-less url, remove the protocol
  28427. // and if we're location-less, remove the location
  28428. // otherwise, return the url unmodified
  28429. if (removeLocation) {
  28430. return newUrl.href.slice(DEFAULT_LOCATION.length);
  28431. } else if (protocolLess) {
  28432. return newUrl.href.slice(newUrl.protocol.length);
  28433. }
  28434. return newUrl.href;
  28435. }
  28436. return urlToolkit.buildAbsoluteURL(baseUrl, relativeUrl);
  28437. };
  28438. /**
  28439. * Loops through all supported media groups in master and calls the provided
  28440. * callback for each group
  28441. *
  28442. * @param {Object} master
  28443. * The parsed master manifest object
  28444. * @param {string[]} groups
  28445. * The media groups to call the callback for
  28446. * @param {Function} callback
  28447. * Callback to call for each media group
  28448. */
  28449. var forEachMediaGroup$1 = function forEachMediaGroup(master, groups, callback) {
  28450. groups.forEach(function (mediaType) {
  28451. for (var groupKey in master.mediaGroups[mediaType]) {
  28452. for (var labelKey in master.mediaGroups[mediaType][groupKey]) {
  28453. var mediaProperties = master.mediaGroups[mediaType][groupKey][labelKey];
  28454. callback(mediaProperties, mediaType, groupKey, labelKey);
  28455. }
  28456. }
  28457. });
  28458. };
  28459. var atob = function atob(s) {
  28460. return window.atob ? window.atob(s) : Buffer.from(s, 'base64').toString('binary');
  28461. };
  28462. function decodeB64ToUint8Array(b64Text) {
  28463. var decodedString = atob(b64Text);
  28464. var array = new Uint8Array(decodedString.length);
  28465. for (var i = 0; i < decodedString.length; i++) {
  28466. array[i] = decodedString.charCodeAt(i);
  28467. }
  28468. return array;
  28469. }
  28470. /**
  28471. * Ponyfill for `Array.prototype.find` which is only available in ES6 runtimes.
  28472. *
  28473. * Works with anything that has a `length` property and index access properties, including NodeList.
  28474. *
  28475. * @template {unknown} T
  28476. * @param {Array<T> | ({length:number, [number]: T})} list
  28477. * @param {function (item: T, index: number, list:Array<T> | ({length:number, [number]: T})):boolean} predicate
  28478. * @param {Partial<Pick<ArrayConstructor['prototype'], 'find'>>?} ac `Array.prototype` by default,
  28479. * allows injecting a custom implementation in tests
  28480. * @returns {T | undefined}
  28481. *
  28482. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
  28483. * @see https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.find
  28484. */
  28485. function find$1(list, predicate, ac) {
  28486. if (ac === undefined) {
  28487. ac = Array.prototype;
  28488. }
  28489. if (list && typeof ac.find === 'function') {
  28490. return ac.find.call(list, predicate);
  28491. }
  28492. for (var i = 0; i < list.length; i++) {
  28493. if (Object.prototype.hasOwnProperty.call(list, i)) {
  28494. var item = list[i];
  28495. if (predicate.call(undefined, item, i, list)) {
  28496. return item;
  28497. }
  28498. }
  28499. }
  28500. }
  28501. /**
  28502. * "Shallow freezes" an object to render it immutable.
  28503. * Uses `Object.freeze` if available,
  28504. * otherwise the immutability is only in the type.
  28505. *
  28506. * Is used to create "enum like" objects.
  28507. *
  28508. * @template T
  28509. * @param {T} object the object to freeze
  28510. * @param {Pick<ObjectConstructor, 'freeze'> = Object} oc `Object` by default,
  28511. * allows to inject custom object constructor for tests
  28512. * @returns {Readonly<T>}
  28513. *
  28514. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
  28515. */
  28516. function freeze(object, oc) {
  28517. if (oc === undefined) {
  28518. oc = Object;
  28519. }
  28520. return oc && typeof oc.freeze === 'function' ? oc.freeze(object) : object;
  28521. }
  28522. /**
  28523. * Since we can not rely on `Object.assign` we provide a simplified version
  28524. * that is sufficient for our needs.
  28525. *
  28526. * @param {Object} target
  28527. * @param {Object | null | undefined} source
  28528. *
  28529. * @returns {Object} target
  28530. * @throws TypeError if target is not an object
  28531. *
  28532. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  28533. * @see https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.assign
  28534. */
  28535. function assign(target, source) {
  28536. if (target === null || typeof target !== 'object') {
  28537. throw new TypeError('target is not an object');
  28538. }
  28539. for (var key in source) {
  28540. if (Object.prototype.hasOwnProperty.call(source, key)) {
  28541. target[key] = source[key];
  28542. }
  28543. }
  28544. return target;
  28545. }
  28546. /**
  28547. * All mime types that are allowed as input to `DOMParser.parseFromString`
  28548. *
  28549. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#Argument02 MDN
  28550. * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#domparsersupportedtype WHATWG HTML Spec
  28551. * @see DOMParser.prototype.parseFromString
  28552. */
  28553. var MIME_TYPE = freeze({
  28554. /**
  28555. * `text/html`, the only mime type that triggers treating an XML document as HTML.
  28556. *
  28557. * @see DOMParser.SupportedType.isHTML
  28558. * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration
  28559. * @see https://en.wikipedia.org/wiki/HTML Wikipedia
  28560. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN
  28561. * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring WHATWG HTML Spec
  28562. */
  28563. HTML: 'text/html',
  28564. /**
  28565. * Helper method to check a mime type if it indicates an HTML document
  28566. *
  28567. * @param {string} [value]
  28568. * @returns {boolean}
  28569. *
  28570. * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration
  28571. * @see https://en.wikipedia.org/wiki/HTML Wikipedia
  28572. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN
  28573. * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring */
  28574. isHTML: function isHTML(value) {
  28575. return value === MIME_TYPE.HTML;
  28576. },
  28577. /**
  28578. * `application/xml`, the standard mime type for XML documents.
  28579. *
  28580. * @see https://www.iana.org/assignments/media-types/application/xml IANA MimeType registration
  28581. * @see https://tools.ietf.org/html/rfc7303#section-9.1 RFC 7303
  28582. * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia
  28583. */
  28584. XML_APPLICATION: 'application/xml',
  28585. /**
  28586. * `text/html`, an alias for `application/xml`.
  28587. *
  28588. * @see https://tools.ietf.org/html/rfc7303#section-9.2 RFC 7303
  28589. * @see https://www.iana.org/assignments/media-types/text/xml IANA MimeType registration
  28590. * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia
  28591. */
  28592. XML_TEXT: 'text/xml',
  28593. /**
  28594. * `application/xhtml+xml`, indicates an XML document that has the default HTML namespace,
  28595. * but is parsed as an XML document.
  28596. *
  28597. * @see https://www.iana.org/assignments/media-types/application/xhtml+xml IANA MimeType registration
  28598. * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument WHATWG DOM Spec
  28599. * @see https://en.wikipedia.org/wiki/XHTML Wikipedia
  28600. */
  28601. XML_XHTML_APPLICATION: 'application/xhtml+xml',
  28602. /**
  28603. * `image/svg+xml`,
  28604. *
  28605. * @see https://www.iana.org/assignments/media-types/image/svg+xml IANA MimeType registration
  28606. * @see https://www.w3.org/TR/SVG11/ W3C SVG 1.1
  28607. * @see https://en.wikipedia.org/wiki/Scalable_Vector_Graphics Wikipedia
  28608. */
  28609. XML_SVG_IMAGE: 'image/svg+xml'
  28610. });
  28611. /**
  28612. * Namespaces that are used in this code base.
  28613. *
  28614. * @see http://www.w3.org/TR/REC-xml-names
  28615. */
  28616. var NAMESPACE$3 = freeze({
  28617. /**
  28618. * The XHTML namespace.
  28619. *
  28620. * @see http://www.w3.org/1999/xhtml
  28621. */
  28622. HTML: 'http://www.w3.org/1999/xhtml',
  28623. /**
  28624. * Checks if `uri` equals `NAMESPACE.HTML`.
  28625. *
  28626. * @param {string} [uri]
  28627. *
  28628. * @see NAMESPACE.HTML
  28629. */
  28630. isHTML: function isHTML(uri) {
  28631. return uri === NAMESPACE$3.HTML;
  28632. },
  28633. /**
  28634. * The SVG namespace.
  28635. *
  28636. * @see http://www.w3.org/2000/svg
  28637. */
  28638. SVG: 'http://www.w3.org/2000/svg',
  28639. /**
  28640. * The `xml:` namespace.
  28641. *
  28642. * @see http://www.w3.org/XML/1998/namespace
  28643. */
  28644. XML: 'http://www.w3.org/XML/1998/namespace',
  28645. /**
  28646. * The `xmlns:` namespace
  28647. *
  28648. * @see https://www.w3.org/2000/xmlns/
  28649. */
  28650. XMLNS: 'http://www.w3.org/2000/xmlns/'
  28651. });
  28652. var assign_1 = assign;
  28653. var find_1 = find$1;
  28654. var freeze_1 = freeze;
  28655. var MIME_TYPE_1 = MIME_TYPE;
  28656. var NAMESPACE_1 = NAMESPACE$3;
  28657. var conventions = {
  28658. assign: assign_1,
  28659. find: find_1,
  28660. freeze: freeze_1,
  28661. MIME_TYPE: MIME_TYPE_1,
  28662. NAMESPACE: NAMESPACE_1
  28663. };
  28664. var find = conventions.find;
  28665. var NAMESPACE$2 = conventions.NAMESPACE;
  28666. /**
  28667. * A prerequisite for `[].filter`, to drop elements that are empty
  28668. * @param {string} input
  28669. * @returns {boolean}
  28670. */
  28671. function notEmptyString(input) {
  28672. return input !== '';
  28673. }
  28674. /**
  28675. * @see https://infra.spec.whatwg.org/#split-on-ascii-whitespace
  28676. * @see https://infra.spec.whatwg.org/#ascii-whitespace
  28677. *
  28678. * @param {string} input
  28679. * @returns {string[]} (can be empty)
  28680. */
  28681. function splitOnASCIIWhitespace(input) {
  28682. // U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, U+0020 SPACE
  28683. return input ? input.split(/[\t\n\f\r ]+/).filter(notEmptyString) : [];
  28684. }
  28685. /**
  28686. * Adds element as a key to current if it is not already present.
  28687. *
  28688. * @param {Record<string, boolean | undefined>} current
  28689. * @param {string} element
  28690. * @returns {Record<string, boolean | undefined>}
  28691. */
  28692. function orderedSetReducer(current, element) {
  28693. if (!current.hasOwnProperty(element)) {
  28694. current[element] = true;
  28695. }
  28696. return current;
  28697. }
  28698. /**
  28699. * @see https://infra.spec.whatwg.org/#ordered-set
  28700. * @param {string} input
  28701. * @returns {string[]}
  28702. */
  28703. function toOrderedSet(input) {
  28704. if (!input) return [];
  28705. var list = splitOnASCIIWhitespace(input);
  28706. return Object.keys(list.reduce(orderedSetReducer, {}));
  28707. }
  28708. /**
  28709. * Uses `list.indexOf` to implement something like `Array.prototype.includes`,
  28710. * which we can not rely on being available.
  28711. *
  28712. * @param {any[]} list
  28713. * @returns {function(any): boolean}
  28714. */
  28715. function arrayIncludes(list) {
  28716. return function (element) {
  28717. return list && list.indexOf(element) !== -1;
  28718. };
  28719. }
  28720. function copy(src, dest) {
  28721. for (var p in src) {
  28722. if (Object.prototype.hasOwnProperty.call(src, p)) {
  28723. dest[p] = src[p];
  28724. }
  28725. }
  28726. }
  28727. /**
  28728. ^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
  28729. ^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
  28730. */
  28731. function _extends(Class, Super) {
  28732. var pt = Class.prototype;
  28733. if (!(pt instanceof Super)) {
  28734. var t = function t() {};
  28735. t.prototype = Super.prototype;
  28736. t = new t();
  28737. copy(pt, t);
  28738. Class.prototype = pt = t;
  28739. }
  28740. if (pt.constructor != Class) {
  28741. if (typeof Class != 'function') {
  28742. console.error("unknown Class:" + Class);
  28743. }
  28744. pt.constructor = Class;
  28745. }
  28746. } // Node Types
  28747. var NodeType = {};
  28748. var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
  28749. var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
  28750. var TEXT_NODE = NodeType.TEXT_NODE = 3;
  28751. var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
  28752. var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
  28753. var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
  28754. var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
  28755. var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
  28756. var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
  28757. var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
  28758. var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
  28759. var NOTATION_NODE = NodeType.NOTATION_NODE = 12; // ExceptionCode
  28760. var ExceptionCode = {};
  28761. var ExceptionMessage = {};
  28762. ExceptionCode.INDEX_SIZE_ERR = (ExceptionMessage[1] = "Index size error", 1);
  28763. ExceptionCode.DOMSTRING_SIZE_ERR = (ExceptionMessage[2] = "DOMString size error", 2);
  28764. var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = (ExceptionMessage[3] = "Hierarchy request error", 3);
  28765. ExceptionCode.WRONG_DOCUMENT_ERR = (ExceptionMessage[4] = "Wrong document", 4);
  28766. ExceptionCode.INVALID_CHARACTER_ERR = (ExceptionMessage[5] = "Invalid character", 5);
  28767. ExceptionCode.NO_DATA_ALLOWED_ERR = (ExceptionMessage[6] = "No data allowed", 6);
  28768. ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = (ExceptionMessage[7] = "No modification allowed", 7);
  28769. var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = (ExceptionMessage[8] = "Not found", 8);
  28770. ExceptionCode.NOT_SUPPORTED_ERR = (ExceptionMessage[9] = "Not supported", 9);
  28771. var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = (ExceptionMessage[10] = "Attribute in use", 10); //level2
  28772. ExceptionCode.INVALID_STATE_ERR = (ExceptionMessage[11] = "Invalid state", 11);
  28773. ExceptionCode.SYNTAX_ERR = (ExceptionMessage[12] = "Syntax error", 12);
  28774. ExceptionCode.INVALID_MODIFICATION_ERR = (ExceptionMessage[13] = "Invalid modification", 13);
  28775. ExceptionCode.NAMESPACE_ERR = (ExceptionMessage[14] = "Invalid namespace", 14);
  28776. ExceptionCode.INVALID_ACCESS_ERR = (ExceptionMessage[15] = "Invalid access", 15);
  28777. /**
  28778. * DOM Level 2
  28779. * Object DOMException
  28780. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
  28781. * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
  28782. */
  28783. function DOMException(code, message) {
  28784. if (message instanceof Error) {
  28785. var error = message;
  28786. } else {
  28787. error = this;
  28788. Error.call(this, ExceptionMessage[code]);
  28789. this.message = ExceptionMessage[code];
  28790. if (Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
  28791. }
  28792. error.code = code;
  28793. if (message) this.message = this.message + ": " + message;
  28794. return error;
  28795. }
  28796. DOMException.prototype = Error.prototype;
  28797. copy(ExceptionCode, DOMException);
  28798. /**
  28799. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
  28800. * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.
  28801. * The items in the NodeList are accessible via an integral index, starting from 0.
  28802. */
  28803. function NodeList() {}
  28804. NodeList.prototype = {
  28805. /**
  28806. * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
  28807. * @standard level1
  28808. */
  28809. length: 0,
  28810. /**
  28811. * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.
  28812. * @standard level1
  28813. * @param index unsigned long
  28814. * Index into the collection.
  28815. * @return Node
  28816. * The node at the indexth position in the NodeList, or null if that is not a valid index.
  28817. */
  28818. item: function item(index) {
  28819. return this[index] || null;
  28820. },
  28821. toString: function toString(isHTML, nodeFilter) {
  28822. for (var buf = [], i = 0; i < this.length; i++) {
  28823. serializeToString(this[i], buf, isHTML, nodeFilter);
  28824. }
  28825. return buf.join('');
  28826. },
  28827. /**
  28828. * @private
  28829. * @param {function (Node):boolean} predicate
  28830. * @returns {Node[]}
  28831. */
  28832. filter: function filter(predicate) {
  28833. return Array.prototype.filter.call(this, predicate);
  28834. },
  28835. /**
  28836. * @private
  28837. * @param {Node} item
  28838. * @returns {number}
  28839. */
  28840. indexOf: function indexOf(item) {
  28841. return Array.prototype.indexOf.call(this, item);
  28842. }
  28843. };
  28844. function LiveNodeList(node, refresh) {
  28845. this._node = node;
  28846. this._refresh = refresh;
  28847. _updateLiveList(this);
  28848. }
  28849. function _updateLiveList(list) {
  28850. var inc = list._node._inc || list._node.ownerDocument._inc;
  28851. if (list._inc != inc) {
  28852. var ls = list._refresh(list._node); //console.log(ls.length)
  28853. __set__(list, 'length', ls.length);
  28854. copy(ls, list);
  28855. list._inc = inc;
  28856. }
  28857. }
  28858. LiveNodeList.prototype.item = function (i) {
  28859. _updateLiveList(this);
  28860. return this[i];
  28861. };
  28862. _extends(LiveNodeList, NodeList);
  28863. /**
  28864. * Objects implementing the NamedNodeMap interface are used
  28865. * to represent collections of nodes that can be accessed by name.
  28866. * Note that NamedNodeMap does not inherit from NodeList;
  28867. * NamedNodeMaps are not maintained in any particular order.
  28868. * Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index,
  28869. * but this is simply to allow convenient enumeration of the contents of a NamedNodeMap,
  28870. * and does not imply that the DOM specifies an order to these Nodes.
  28871. * NamedNodeMap objects in the DOM are live.
  28872. * used for attributes or DocumentType entities
  28873. */
  28874. function NamedNodeMap() {}
  28875. function _findNodeIndex(list, node) {
  28876. var i = list.length;
  28877. while (i--) {
  28878. if (list[i] === node) {
  28879. return i;
  28880. }
  28881. }
  28882. }
  28883. function _addNamedNode(el, list, newAttr, oldAttr) {
  28884. if (oldAttr) {
  28885. list[_findNodeIndex(list, oldAttr)] = newAttr;
  28886. } else {
  28887. list[list.length++] = newAttr;
  28888. }
  28889. if (el) {
  28890. newAttr.ownerElement = el;
  28891. var doc = el.ownerDocument;
  28892. if (doc) {
  28893. oldAttr && _onRemoveAttribute(doc, el, oldAttr);
  28894. _onAddAttribute(doc, el, newAttr);
  28895. }
  28896. }
  28897. }
  28898. function _removeNamedNode(el, list, attr) {
  28899. //console.log('remove attr:'+attr)
  28900. var i = _findNodeIndex(list, attr);
  28901. if (i >= 0) {
  28902. var lastIndex = list.length - 1;
  28903. while (i < lastIndex) {
  28904. list[i] = list[++i];
  28905. }
  28906. list.length = lastIndex;
  28907. if (el) {
  28908. var doc = el.ownerDocument;
  28909. if (doc) {
  28910. _onRemoveAttribute(doc, el, attr);
  28911. attr.ownerElement = null;
  28912. }
  28913. }
  28914. } else {
  28915. throw new DOMException(NOT_FOUND_ERR, new Error(el.tagName + '@' + attr));
  28916. }
  28917. }
  28918. NamedNodeMap.prototype = {
  28919. length: 0,
  28920. item: NodeList.prototype.item,
  28921. getNamedItem: function getNamedItem(key) {
  28922. // if(key.indexOf(':')>0 || key == 'xmlns'){
  28923. // return null;
  28924. // }
  28925. //console.log()
  28926. var i = this.length;
  28927. while (i--) {
  28928. var attr = this[i]; //console.log(attr.nodeName,key)
  28929. if (attr.nodeName == key) {
  28930. return attr;
  28931. }
  28932. }
  28933. },
  28934. setNamedItem: function setNamedItem(attr) {
  28935. var el = attr.ownerElement;
  28936. if (el && el != this._ownerElement) {
  28937. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  28938. }
  28939. var oldAttr = this.getNamedItem(attr.nodeName);
  28940. _addNamedNode(this._ownerElement, this, attr, oldAttr);
  28941. return oldAttr;
  28942. },
  28943. /* returns Node */
  28944. setNamedItemNS: function setNamedItemNS(attr) {
  28945. // raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
  28946. var el = attr.ownerElement,
  28947. oldAttr;
  28948. if (el && el != this._ownerElement) {
  28949. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  28950. }
  28951. oldAttr = this.getNamedItemNS(attr.namespaceURI, attr.localName);
  28952. _addNamedNode(this._ownerElement, this, attr, oldAttr);
  28953. return oldAttr;
  28954. },
  28955. /* returns Node */
  28956. removeNamedItem: function removeNamedItem(key) {
  28957. var attr = this.getNamedItem(key);
  28958. _removeNamedNode(this._ownerElement, this, attr);
  28959. return attr;
  28960. },
  28961. // raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
  28962. //for level2
  28963. removeNamedItemNS: function removeNamedItemNS(namespaceURI, localName) {
  28964. var attr = this.getNamedItemNS(namespaceURI, localName);
  28965. _removeNamedNode(this._ownerElement, this, attr);
  28966. return attr;
  28967. },
  28968. getNamedItemNS: function getNamedItemNS(namespaceURI, localName) {
  28969. var i = this.length;
  28970. while (i--) {
  28971. var node = this[i];
  28972. if (node.localName == localName && node.namespaceURI == namespaceURI) {
  28973. return node;
  28974. }
  28975. }
  28976. return null;
  28977. }
  28978. };
  28979. /**
  28980. * The DOMImplementation interface represents an object providing methods
  28981. * which are not dependent on any particular document.
  28982. * Such an object is returned by the `Document.implementation` property.
  28983. *
  28984. * __The individual methods describe the differences compared to the specs.__
  28985. *
  28986. * @constructor
  28987. *
  28988. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation MDN
  28989. * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490 DOM Level 1 Core (Initial)
  28990. * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-102161490 DOM Level 2 Core
  28991. * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-102161490 DOM Level 3 Core
  28992. * @see https://dom.spec.whatwg.org/#domimplementation DOM Living Standard
  28993. */
  28994. function DOMImplementation$1() {}
  28995. DOMImplementation$1.prototype = {
  28996. /**
  28997. * The DOMImplementation.hasFeature() method returns a Boolean flag indicating if a given feature is supported.
  28998. * The different implementations fairly diverged in what kind of features were reported.
  28999. * The latest version of the spec settled to force this method to always return true, where the functionality was accurate and in use.
  29000. *
  29001. * @deprecated It is deprecated and modern browsers return true in all cases.
  29002. *
  29003. * @param {string} feature
  29004. * @param {string} [version]
  29005. * @returns {boolean} always true
  29006. *
  29007. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/hasFeature MDN
  29008. * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-5CED94D7 DOM Level 1 Core
  29009. * @see https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature DOM Living Standard
  29010. */
  29011. hasFeature: function hasFeature(feature, version) {
  29012. return true;
  29013. },
  29014. /**
  29015. * Creates an XML Document object of the specified type with its document element.
  29016. *
  29017. * __It behaves slightly different from the description in the living standard__:
  29018. * - There is no interface/class `XMLDocument`, it returns a `Document` instance.
  29019. * - `contentType`, `encoding`, `mode`, `origin`, `url` fields are currently not declared.
  29020. * - this implementation is not validating names or qualified names
  29021. * (when parsing XML strings, the SAX parser takes care of that)
  29022. *
  29023. * @param {string|null} namespaceURI
  29024. * @param {string} qualifiedName
  29025. * @param {DocumentType=null} doctype
  29026. * @returns {Document}
  29027. *
  29028. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument MDN
  29029. * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocument DOM Level 2 Core (initial)
  29030. * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument DOM Level 2 Core
  29031. *
  29032. * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract
  29033. * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names
  29034. * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names
  29035. */
  29036. createDocument: function createDocument(namespaceURI, qualifiedName, doctype) {
  29037. var doc = new Document();
  29038. doc.implementation = this;
  29039. doc.childNodes = new NodeList();
  29040. doc.doctype = doctype || null;
  29041. if (doctype) {
  29042. doc.appendChild(doctype);
  29043. }
  29044. if (qualifiedName) {
  29045. var root = doc.createElementNS(namespaceURI, qualifiedName);
  29046. doc.appendChild(root);
  29047. }
  29048. return doc;
  29049. },
  29050. /**
  29051. * Returns a doctype, with the given `qualifiedName`, `publicId`, and `systemId`.
  29052. *
  29053. * __This behavior is slightly different from the in the specs__:
  29054. * - this implementation is not validating names or qualified names
  29055. * (when parsing XML strings, the SAX parser takes care of that)
  29056. *
  29057. * @param {string} qualifiedName
  29058. * @param {string} [publicId]
  29059. * @param {string} [systemId]
  29060. * @returns {DocumentType} which can either be used with `DOMImplementation.createDocument` upon document creation
  29061. * or can be put into the document via methods like `Node.insertBefore()` or `Node.replaceChild()`
  29062. *
  29063. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocumentType MDN
  29064. * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocType DOM Level 2 Core
  29065. * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype DOM Living Standard
  29066. *
  29067. * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract
  29068. * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names
  29069. * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names
  29070. */
  29071. createDocumentType: function createDocumentType(qualifiedName, publicId, systemId) {
  29072. var node = new DocumentType();
  29073. node.name = qualifiedName;
  29074. node.nodeName = qualifiedName;
  29075. node.publicId = publicId || '';
  29076. node.systemId = systemId || '';
  29077. return node;
  29078. }
  29079. };
  29080. /**
  29081. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
  29082. */
  29083. function Node() {}
  29084. Node.prototype = {
  29085. firstChild: null,
  29086. lastChild: null,
  29087. previousSibling: null,
  29088. nextSibling: null,
  29089. attributes: null,
  29090. parentNode: null,
  29091. childNodes: null,
  29092. ownerDocument: null,
  29093. nodeValue: null,
  29094. namespaceURI: null,
  29095. prefix: null,
  29096. localName: null,
  29097. // Modified in DOM Level 2:
  29098. insertBefore: function insertBefore(newChild, refChild) {
  29099. //raises
  29100. return _insertBefore(this, newChild, refChild);
  29101. },
  29102. replaceChild: function replaceChild(newChild, oldChild) {
  29103. //raises
  29104. _insertBefore(this, newChild, oldChild, assertPreReplacementValidityInDocument);
  29105. if (oldChild) {
  29106. this.removeChild(oldChild);
  29107. }
  29108. },
  29109. removeChild: function removeChild(oldChild) {
  29110. return _removeChild(this, oldChild);
  29111. },
  29112. appendChild: function appendChild(newChild) {
  29113. return this.insertBefore(newChild, null);
  29114. },
  29115. hasChildNodes: function hasChildNodes() {
  29116. return this.firstChild != null;
  29117. },
  29118. cloneNode: function cloneNode(deep) {
  29119. return _cloneNode(this.ownerDocument || this, this, deep);
  29120. },
  29121. // Modified in DOM Level 2:
  29122. normalize: function normalize() {
  29123. var child = this.firstChild;
  29124. while (child) {
  29125. var next = child.nextSibling;
  29126. if (next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE) {
  29127. this.removeChild(next);
  29128. child.appendData(next.data);
  29129. } else {
  29130. child.normalize();
  29131. child = next;
  29132. }
  29133. }
  29134. },
  29135. // Introduced in DOM Level 2:
  29136. isSupported: function isSupported(feature, version) {
  29137. return this.ownerDocument.implementation.hasFeature(feature, version);
  29138. },
  29139. // Introduced in DOM Level 2:
  29140. hasAttributes: function hasAttributes() {
  29141. return this.attributes.length > 0;
  29142. },
  29143. /**
  29144. * Look up the prefix associated to the given namespace URI, starting from this node.
  29145. * **The default namespace declarations are ignored by this method.**
  29146. * See Namespace Prefix Lookup for details on the algorithm used by this method.
  29147. *
  29148. * _Note: The implementation seems to be incomplete when compared to the algorithm described in the specs._
  29149. *
  29150. * @param {string | null} namespaceURI
  29151. * @returns {string | null}
  29152. * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespacePrefix
  29153. * @see https://www.w3.org/TR/DOM-Level-3-Core/namespaces-algorithms.html#lookupNamespacePrefixAlgo
  29154. * @see https://dom.spec.whatwg.org/#dom-node-lookupprefix
  29155. * @see https://github.com/xmldom/xmldom/issues/322
  29156. */
  29157. lookupPrefix: function lookupPrefix(namespaceURI) {
  29158. var el = this;
  29159. while (el) {
  29160. var map = el._nsMap; //console.dir(map)
  29161. if (map) {
  29162. for (var n in map) {
  29163. if (Object.prototype.hasOwnProperty.call(map, n) && map[n] === namespaceURI) {
  29164. return n;
  29165. }
  29166. }
  29167. }
  29168. el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode;
  29169. }
  29170. return null;
  29171. },
  29172. // Introduced in DOM Level 3:
  29173. lookupNamespaceURI: function lookupNamespaceURI(prefix) {
  29174. var el = this;
  29175. while (el) {
  29176. var map = el._nsMap; //console.dir(map)
  29177. if (map) {
  29178. if (Object.prototype.hasOwnProperty.call(map, prefix)) {
  29179. return map[prefix];
  29180. }
  29181. }
  29182. el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode;
  29183. }
  29184. return null;
  29185. },
  29186. // Introduced in DOM Level 3:
  29187. isDefaultNamespace: function isDefaultNamespace(namespaceURI) {
  29188. var prefix = this.lookupPrefix(namespaceURI);
  29189. return prefix == null;
  29190. }
  29191. };
  29192. function _xmlEncoder(c) {
  29193. return c == '<' && '&lt;' || c == '>' && '&gt;' || c == '&' && '&amp;' || c == '"' && '&quot;' || '&#' + c.charCodeAt() + ';';
  29194. }
  29195. copy(NodeType, Node);
  29196. copy(NodeType, Node.prototype);
  29197. /**
  29198. * @param callback return true for continue,false for break
  29199. * @return boolean true: break visit;
  29200. */
  29201. function _visitNode(node, callback) {
  29202. if (callback(node)) {
  29203. return true;
  29204. }
  29205. if (node = node.firstChild) {
  29206. do {
  29207. if (_visitNode(node, callback)) {
  29208. return true;
  29209. }
  29210. } while (node = node.nextSibling);
  29211. }
  29212. }
  29213. function Document() {
  29214. this.ownerDocument = this;
  29215. }
  29216. function _onAddAttribute(doc, el, newAttr) {
  29217. doc && doc._inc++;
  29218. var ns = newAttr.namespaceURI;
  29219. if (ns === NAMESPACE$2.XMLNS) {
  29220. //update namespace
  29221. el._nsMap[newAttr.prefix ? newAttr.localName : ''] = newAttr.value;
  29222. }
  29223. }
  29224. function _onRemoveAttribute(doc, el, newAttr, remove) {
  29225. doc && doc._inc++;
  29226. var ns = newAttr.namespaceURI;
  29227. if (ns === NAMESPACE$2.XMLNS) {
  29228. //update namespace
  29229. delete el._nsMap[newAttr.prefix ? newAttr.localName : ''];
  29230. }
  29231. }
  29232. /**
  29233. * Updates `el.childNodes`, updating the indexed items and it's `length`.
  29234. * Passing `newChild` means it will be appended.
  29235. * Otherwise it's assumed that an item has been removed,
  29236. * and `el.firstNode` and it's `.nextSibling` are used
  29237. * to walk the current list of child nodes.
  29238. *
  29239. * @param {Document} doc
  29240. * @param {Node} el
  29241. * @param {Node} [newChild]
  29242. * @private
  29243. */
  29244. function _onUpdateChild(doc, el, newChild) {
  29245. if (doc && doc._inc) {
  29246. doc._inc++; //update childNodes
  29247. var cs = el.childNodes;
  29248. if (newChild) {
  29249. cs[cs.length++] = newChild;
  29250. } else {
  29251. var child = el.firstChild;
  29252. var i = 0;
  29253. while (child) {
  29254. cs[i++] = child;
  29255. child = child.nextSibling;
  29256. }
  29257. cs.length = i;
  29258. delete cs[cs.length];
  29259. }
  29260. }
  29261. }
  29262. /**
  29263. * Removes the connections between `parentNode` and `child`
  29264. * and any existing `child.previousSibling` or `child.nextSibling`.
  29265. *
  29266. * @see https://github.com/xmldom/xmldom/issues/135
  29267. * @see https://github.com/xmldom/xmldom/issues/145
  29268. *
  29269. * @param {Node} parentNode
  29270. * @param {Node} child
  29271. * @returns {Node} the child that was removed.
  29272. * @private
  29273. */
  29274. function _removeChild(parentNode, child) {
  29275. var previous = child.previousSibling;
  29276. var next = child.nextSibling;
  29277. if (previous) {
  29278. previous.nextSibling = next;
  29279. } else {
  29280. parentNode.firstChild = next;
  29281. }
  29282. if (next) {
  29283. next.previousSibling = previous;
  29284. } else {
  29285. parentNode.lastChild = previous;
  29286. }
  29287. child.parentNode = null;
  29288. child.previousSibling = null;
  29289. child.nextSibling = null;
  29290. _onUpdateChild(parentNode.ownerDocument, parentNode);
  29291. return child;
  29292. }
  29293. /**
  29294. * Returns `true` if `node` can be a parent for insertion.
  29295. * @param {Node} node
  29296. * @returns {boolean}
  29297. */
  29298. function hasValidParentNodeType(node) {
  29299. return node && (node.nodeType === Node.DOCUMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || node.nodeType === Node.ELEMENT_NODE);
  29300. }
  29301. /**
  29302. * Returns `true` if `node` can be inserted according to it's `nodeType`.
  29303. * @param {Node} node
  29304. * @returns {boolean}
  29305. */
  29306. function hasInsertableNodeType(node) {
  29307. return node && (isElementNode(node) || isTextNode(node) || isDocTypeNode(node) || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || node.nodeType === Node.COMMENT_NODE || node.nodeType === Node.PROCESSING_INSTRUCTION_NODE);
  29308. }
  29309. /**
  29310. * Returns true if `node` is a DOCTYPE node
  29311. * @param {Node} node
  29312. * @returns {boolean}
  29313. */
  29314. function isDocTypeNode(node) {
  29315. return node && node.nodeType === Node.DOCUMENT_TYPE_NODE;
  29316. }
  29317. /**
  29318. * Returns true if the node is an element
  29319. * @param {Node} node
  29320. * @returns {boolean}
  29321. */
  29322. function isElementNode(node) {
  29323. return node && node.nodeType === Node.ELEMENT_NODE;
  29324. }
  29325. /**
  29326. * Returns true if `node` is a text node
  29327. * @param {Node} node
  29328. * @returns {boolean}
  29329. */
  29330. function isTextNode(node) {
  29331. return node && node.nodeType === Node.TEXT_NODE;
  29332. }
  29333. /**
  29334. * Check if en element node can be inserted before `child`, or at the end if child is falsy,
  29335. * according to the presence and position of a doctype node on the same level.
  29336. *
  29337. * @param {Document} doc The document node
  29338. * @param {Node} child the node that would become the nextSibling if the element would be inserted
  29339. * @returns {boolean} `true` if an element can be inserted before child
  29340. * @private
  29341. * https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  29342. */
  29343. function isElementInsertionPossible(doc, child) {
  29344. var parentChildNodes = doc.childNodes || [];
  29345. if (find(parentChildNodes, isElementNode) || isDocTypeNode(child)) {
  29346. return false;
  29347. }
  29348. var docTypeNode = find(parentChildNodes, isDocTypeNode);
  29349. return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child));
  29350. }
  29351. /**
  29352. * Check if en element node can be inserted before `child`, or at the end if child is falsy,
  29353. * according to the presence and position of a doctype node on the same level.
  29354. *
  29355. * @param {Node} doc The document node
  29356. * @param {Node} child the node that would become the nextSibling if the element would be inserted
  29357. * @returns {boolean} `true` if an element can be inserted before child
  29358. * @private
  29359. * https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  29360. */
  29361. function isElementReplacementPossible(doc, child) {
  29362. var parentChildNodes = doc.childNodes || [];
  29363. function hasElementChildThatIsNotChild(node) {
  29364. return isElementNode(node) && node !== child;
  29365. }
  29366. if (find(parentChildNodes, hasElementChildThatIsNotChild)) {
  29367. return false;
  29368. }
  29369. var docTypeNode = find(parentChildNodes, isDocTypeNode);
  29370. return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child));
  29371. }
  29372. /**
  29373. * @private
  29374. * Steps 1-5 of the checks before inserting and before replacing a child are the same.
  29375. *
  29376. * @param {Node} parent the parent node to insert `node` into
  29377. * @param {Node} node the node to insert
  29378. * @param {Node=} child the node that should become the `nextSibling` of `node`
  29379. * @returns {Node}
  29380. * @throws DOMException for several node combinations that would create a DOM that is not well-formed.
  29381. * @throws DOMException if `child` is provided but is not a child of `parent`.
  29382. * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  29383. * @see https://dom.spec.whatwg.org/#concept-node-replace
  29384. */
  29385. function assertPreInsertionValidity1to5(parent, node, child) {
  29386. // 1. If `parent` is not a Document, DocumentFragment, or Element node, then throw a "HierarchyRequestError" DOMException.
  29387. if (!hasValidParentNodeType(parent)) {
  29388. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Unexpected parent node type ' + parent.nodeType);
  29389. } // 2. If `node` is a host-including inclusive ancestor of `parent`, then throw a "HierarchyRequestError" DOMException.
  29390. // not implemented!
  29391. // 3. If `child` is non-null and its parent is not `parent`, then throw a "NotFoundError" DOMException.
  29392. if (child && child.parentNode !== parent) {
  29393. throw new DOMException(NOT_FOUND_ERR, 'child not in parent');
  29394. }
  29395. if ( // 4. If `node` is not a DocumentFragment, DocumentType, Element, or CharacterData node, then throw a "HierarchyRequestError" DOMException.
  29396. !hasInsertableNodeType(node) || // 5. If either `node` is a Text node and `parent` is a document,
  29397. // the sax parser currently adds top level text nodes, this will be fixed in 0.9.0
  29398. // || (node.nodeType === Node.TEXT_NODE && parent.nodeType === Node.DOCUMENT_NODE)
  29399. // or `node` is a doctype and `parent` is not a document, then throw a "HierarchyRequestError" DOMException.
  29400. isDocTypeNode(node) && parent.nodeType !== Node.DOCUMENT_NODE) {
  29401. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Unexpected node type ' + node.nodeType + ' for parent node type ' + parent.nodeType);
  29402. }
  29403. }
  29404. /**
  29405. * @private
  29406. * Step 6 of the checks before inserting and before replacing a child are different.
  29407. *
  29408. * @param {Document} parent the parent node to insert `node` into
  29409. * @param {Node} node the node to insert
  29410. * @param {Node | undefined} child the node that should become the `nextSibling` of `node`
  29411. * @returns {Node}
  29412. * @throws DOMException for several node combinations that would create a DOM that is not well-formed.
  29413. * @throws DOMException if `child` is provided but is not a child of `parent`.
  29414. * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  29415. * @see https://dom.spec.whatwg.org/#concept-node-replace
  29416. */
  29417. function assertPreInsertionValidityInDocument(parent, node, child) {
  29418. var parentChildNodes = parent.childNodes || [];
  29419. var nodeChildNodes = node.childNodes || []; // DocumentFragment
  29420. if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
  29421. var nodeChildElements = nodeChildNodes.filter(isElementNode); // If node has more than one element child or has a Text node child.
  29422. if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) {
  29423. throw new DOMException(HIERARCHY_REQUEST_ERR, 'More than one element or text in fragment');
  29424. } // Otherwise, if `node` has one element child and either `parent` has an element child,
  29425. // `child` is a doctype, or `child` is non-null and a doctype is following `child`.
  29426. if (nodeChildElements.length === 1 && !isElementInsertionPossible(parent, child)) {
  29427. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Element in fragment can not be inserted before doctype');
  29428. }
  29429. } // Element
  29430. if (isElementNode(node)) {
  29431. // `parent` has an element child, `child` is a doctype,
  29432. // or `child` is non-null and a doctype is following `child`.
  29433. if (!isElementInsertionPossible(parent, child)) {
  29434. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one element can be added and only after doctype');
  29435. }
  29436. } // DocumentType
  29437. if (isDocTypeNode(node)) {
  29438. // `parent` has a doctype child,
  29439. if (find(parentChildNodes, isDocTypeNode)) {
  29440. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one doctype is allowed');
  29441. }
  29442. var parentElementChild = find(parentChildNodes, isElementNode); // `child` is non-null and an element is preceding `child`,
  29443. if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) {
  29444. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can only be inserted before an element');
  29445. } // or `child` is null and `parent` has an element child.
  29446. if (!child && parentElementChild) {
  29447. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can not be appended since element is present');
  29448. }
  29449. }
  29450. }
  29451. /**
  29452. * @private
  29453. * Step 6 of the checks before inserting and before replacing a child are different.
  29454. *
  29455. * @param {Document} parent the parent node to insert `node` into
  29456. * @param {Node} node the node to insert
  29457. * @param {Node | undefined} child the node that should become the `nextSibling` of `node`
  29458. * @returns {Node}
  29459. * @throws DOMException for several node combinations that would create a DOM that is not well-formed.
  29460. * @throws DOMException if `child` is provided but is not a child of `parent`.
  29461. * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  29462. * @see https://dom.spec.whatwg.org/#concept-node-replace
  29463. */
  29464. function assertPreReplacementValidityInDocument(parent, node, child) {
  29465. var parentChildNodes = parent.childNodes || [];
  29466. var nodeChildNodes = node.childNodes || []; // DocumentFragment
  29467. if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
  29468. var nodeChildElements = nodeChildNodes.filter(isElementNode); // If `node` has more than one element child or has a Text node child.
  29469. if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) {
  29470. throw new DOMException(HIERARCHY_REQUEST_ERR, 'More than one element or text in fragment');
  29471. } // Otherwise, if `node` has one element child and either `parent` has an element child that is not `child` or a doctype is following `child`.
  29472. if (nodeChildElements.length === 1 && !isElementReplacementPossible(parent, child)) {
  29473. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Element in fragment can not be inserted before doctype');
  29474. }
  29475. } // Element
  29476. if (isElementNode(node)) {
  29477. // `parent` has an element child that is not `child` or a doctype is following `child`.
  29478. if (!isElementReplacementPossible(parent, child)) {
  29479. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one element can be added and only after doctype');
  29480. }
  29481. } // DocumentType
  29482. if (isDocTypeNode(node)) {
  29483. var hasDoctypeChildThatIsNotChild = function hasDoctypeChildThatIsNotChild(node) {
  29484. return isDocTypeNode(node) && node !== child;
  29485. }; // `parent` has a doctype child that is not `child`,
  29486. if (find(parentChildNodes, hasDoctypeChildThatIsNotChild)) {
  29487. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one doctype is allowed');
  29488. }
  29489. var parentElementChild = find(parentChildNodes, isElementNode); // or an element is preceding `child`.
  29490. if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) {
  29491. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can only be inserted before an element');
  29492. }
  29493. }
  29494. }
  29495. /**
  29496. * @private
  29497. * @param {Node} parent the parent node to insert `node` into
  29498. * @param {Node} node the node to insert
  29499. * @param {Node=} child the node that should become the `nextSibling` of `node`
  29500. * @returns {Node}
  29501. * @throws DOMException for several node combinations that would create a DOM that is not well-formed.
  29502. * @throws DOMException if `child` is provided but is not a child of `parent`.
  29503. * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  29504. */
  29505. function _insertBefore(parent, node, child, _inDocumentAssertion) {
  29506. // To ensure pre-insertion validity of a node into a parent before a child, run these steps:
  29507. assertPreInsertionValidity1to5(parent, node, child); // If parent is a document, and any of the statements below, switched on the interface node implements,
  29508. // are true, then throw a "HierarchyRequestError" DOMException.
  29509. if (parent.nodeType === Node.DOCUMENT_NODE) {
  29510. (_inDocumentAssertion || assertPreInsertionValidityInDocument)(parent, node, child);
  29511. }
  29512. var cp = node.parentNode;
  29513. if (cp) {
  29514. cp.removeChild(node); //remove and update
  29515. }
  29516. if (node.nodeType === DOCUMENT_FRAGMENT_NODE) {
  29517. var newFirst = node.firstChild;
  29518. if (newFirst == null) {
  29519. return node;
  29520. }
  29521. var newLast = node.lastChild;
  29522. } else {
  29523. newFirst = newLast = node;
  29524. }
  29525. var pre = child ? child.previousSibling : parent.lastChild;
  29526. newFirst.previousSibling = pre;
  29527. newLast.nextSibling = child;
  29528. if (pre) {
  29529. pre.nextSibling = newFirst;
  29530. } else {
  29531. parent.firstChild = newFirst;
  29532. }
  29533. if (child == null) {
  29534. parent.lastChild = newLast;
  29535. } else {
  29536. child.previousSibling = newLast;
  29537. }
  29538. do {
  29539. newFirst.parentNode = parent;
  29540. } while (newFirst !== newLast && (newFirst = newFirst.nextSibling));
  29541. _onUpdateChild(parent.ownerDocument || parent, parent); //console.log(parent.lastChild.nextSibling == null)
  29542. if (node.nodeType == DOCUMENT_FRAGMENT_NODE) {
  29543. node.firstChild = node.lastChild = null;
  29544. }
  29545. return node;
  29546. }
  29547. /**
  29548. * Appends `newChild` to `parentNode`.
  29549. * If `newChild` is already connected to a `parentNode` it is first removed from it.
  29550. *
  29551. * @see https://github.com/xmldom/xmldom/issues/135
  29552. * @see https://github.com/xmldom/xmldom/issues/145
  29553. * @param {Node} parentNode
  29554. * @param {Node} newChild
  29555. * @returns {Node}
  29556. * @private
  29557. */
  29558. function _appendSingleChild(parentNode, newChild) {
  29559. if (newChild.parentNode) {
  29560. newChild.parentNode.removeChild(newChild);
  29561. }
  29562. newChild.parentNode = parentNode;
  29563. newChild.previousSibling = parentNode.lastChild;
  29564. newChild.nextSibling = null;
  29565. if (newChild.previousSibling) {
  29566. newChild.previousSibling.nextSibling = newChild;
  29567. } else {
  29568. parentNode.firstChild = newChild;
  29569. }
  29570. parentNode.lastChild = newChild;
  29571. _onUpdateChild(parentNode.ownerDocument, parentNode, newChild);
  29572. return newChild;
  29573. }
  29574. Document.prototype = {
  29575. //implementation : null,
  29576. nodeName: '#document',
  29577. nodeType: DOCUMENT_NODE,
  29578. /**
  29579. * The DocumentType node of the document.
  29580. *
  29581. * @readonly
  29582. * @type DocumentType
  29583. */
  29584. doctype: null,
  29585. documentElement: null,
  29586. _inc: 1,
  29587. insertBefore: function insertBefore(newChild, refChild) {
  29588. //raises
  29589. if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
  29590. var child = newChild.firstChild;
  29591. while (child) {
  29592. var next = child.nextSibling;
  29593. this.insertBefore(child, refChild);
  29594. child = next;
  29595. }
  29596. return newChild;
  29597. }
  29598. _insertBefore(this, newChild, refChild);
  29599. newChild.ownerDocument = this;
  29600. if (this.documentElement === null && newChild.nodeType === ELEMENT_NODE) {
  29601. this.documentElement = newChild;
  29602. }
  29603. return newChild;
  29604. },
  29605. removeChild: function removeChild(oldChild) {
  29606. if (this.documentElement == oldChild) {
  29607. this.documentElement = null;
  29608. }
  29609. return _removeChild(this, oldChild);
  29610. },
  29611. replaceChild: function replaceChild(newChild, oldChild) {
  29612. //raises
  29613. _insertBefore(this, newChild, oldChild, assertPreReplacementValidityInDocument);
  29614. newChild.ownerDocument = this;
  29615. if (oldChild) {
  29616. this.removeChild(oldChild);
  29617. }
  29618. if (isElementNode(newChild)) {
  29619. this.documentElement = newChild;
  29620. }
  29621. },
  29622. // Introduced in DOM Level 2:
  29623. importNode: function importNode(importedNode, deep) {
  29624. return _importNode(this, importedNode, deep);
  29625. },
  29626. // Introduced in DOM Level 2:
  29627. getElementById: function getElementById(id) {
  29628. var rtv = null;
  29629. _visitNode(this.documentElement, function (node) {
  29630. if (node.nodeType == ELEMENT_NODE) {
  29631. if (node.getAttribute('id') == id) {
  29632. rtv = node;
  29633. return true;
  29634. }
  29635. }
  29636. });
  29637. return rtv;
  29638. },
  29639. /**
  29640. * The `getElementsByClassName` method of `Document` interface returns an array-like object
  29641. * of all child elements which have **all** of the given class name(s).
  29642. *
  29643. * Returns an empty list if `classeNames` is an empty string or only contains HTML white space characters.
  29644. *
  29645. *
  29646. * Warning: This is a live LiveNodeList.
  29647. * Changes in the DOM will reflect in the array as the changes occur.
  29648. * If an element selected by this array no longer qualifies for the selector,
  29649. * it will automatically be removed. Be aware of this for iteration purposes.
  29650. *
  29651. * @param {string} classNames is a string representing the class name(s) to match; multiple class names are separated by (ASCII-)whitespace
  29652. *
  29653. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
  29654. * @see https://dom.spec.whatwg.org/#concept-getelementsbyclassname
  29655. */
  29656. getElementsByClassName: function getElementsByClassName(classNames) {
  29657. var classNamesSet = toOrderedSet(classNames);
  29658. return new LiveNodeList(this, function (base) {
  29659. var ls = [];
  29660. if (classNamesSet.length > 0) {
  29661. _visitNode(base.documentElement, function (node) {
  29662. if (node !== base && node.nodeType === ELEMENT_NODE) {
  29663. var nodeClassNames = node.getAttribute('class'); // can be null if the attribute does not exist
  29664. if (nodeClassNames) {
  29665. // before splitting and iterating just compare them for the most common case
  29666. var matches = classNames === nodeClassNames;
  29667. if (!matches) {
  29668. var nodeClassNamesSet = toOrderedSet(nodeClassNames);
  29669. matches = classNamesSet.every(arrayIncludes(nodeClassNamesSet));
  29670. }
  29671. if (matches) {
  29672. ls.push(node);
  29673. }
  29674. }
  29675. }
  29676. });
  29677. }
  29678. return ls;
  29679. });
  29680. },
  29681. //document factory method:
  29682. createElement: function createElement(tagName) {
  29683. var node = new Element();
  29684. node.ownerDocument = this;
  29685. node.nodeName = tagName;
  29686. node.tagName = tagName;
  29687. node.localName = tagName;
  29688. node.childNodes = new NodeList();
  29689. var attrs = node.attributes = new NamedNodeMap();
  29690. attrs._ownerElement = node;
  29691. return node;
  29692. },
  29693. createDocumentFragment: function createDocumentFragment() {
  29694. var node = new DocumentFragment();
  29695. node.ownerDocument = this;
  29696. node.childNodes = new NodeList();
  29697. return node;
  29698. },
  29699. createTextNode: function createTextNode(data) {
  29700. var node = new Text();
  29701. node.ownerDocument = this;
  29702. node.appendData(data);
  29703. return node;
  29704. },
  29705. createComment: function createComment(data) {
  29706. var node = new Comment();
  29707. node.ownerDocument = this;
  29708. node.appendData(data);
  29709. return node;
  29710. },
  29711. createCDATASection: function createCDATASection(data) {
  29712. var node = new CDATASection();
  29713. node.ownerDocument = this;
  29714. node.appendData(data);
  29715. return node;
  29716. },
  29717. createProcessingInstruction: function createProcessingInstruction(target, data) {
  29718. var node = new ProcessingInstruction();
  29719. node.ownerDocument = this;
  29720. node.tagName = node.target = target;
  29721. node.nodeValue = node.data = data;
  29722. return node;
  29723. },
  29724. createAttribute: function createAttribute(name) {
  29725. var node = new Attr();
  29726. node.ownerDocument = this;
  29727. node.name = name;
  29728. node.nodeName = name;
  29729. node.localName = name;
  29730. node.specified = true;
  29731. return node;
  29732. },
  29733. createEntityReference: function createEntityReference(name) {
  29734. var node = new EntityReference();
  29735. node.ownerDocument = this;
  29736. node.nodeName = name;
  29737. return node;
  29738. },
  29739. // Introduced in DOM Level 2:
  29740. createElementNS: function createElementNS(namespaceURI, qualifiedName) {
  29741. var node = new Element();
  29742. var pl = qualifiedName.split(':');
  29743. var attrs = node.attributes = new NamedNodeMap();
  29744. node.childNodes = new NodeList();
  29745. node.ownerDocument = this;
  29746. node.nodeName = qualifiedName;
  29747. node.tagName = qualifiedName;
  29748. node.namespaceURI = namespaceURI;
  29749. if (pl.length == 2) {
  29750. node.prefix = pl[0];
  29751. node.localName = pl[1];
  29752. } else {
  29753. //el.prefix = null;
  29754. node.localName = qualifiedName;
  29755. }
  29756. attrs._ownerElement = node;
  29757. return node;
  29758. },
  29759. // Introduced in DOM Level 2:
  29760. createAttributeNS: function createAttributeNS(namespaceURI, qualifiedName) {
  29761. var node = new Attr();
  29762. var pl = qualifiedName.split(':');
  29763. node.ownerDocument = this;
  29764. node.nodeName = qualifiedName;
  29765. node.name = qualifiedName;
  29766. node.namespaceURI = namespaceURI;
  29767. node.specified = true;
  29768. if (pl.length == 2) {
  29769. node.prefix = pl[0];
  29770. node.localName = pl[1];
  29771. } else {
  29772. //el.prefix = null;
  29773. node.localName = qualifiedName;
  29774. }
  29775. return node;
  29776. }
  29777. };
  29778. _extends(Document, Node);
  29779. function Element() {
  29780. this._nsMap = {};
  29781. }
  29782. Element.prototype = {
  29783. nodeType: ELEMENT_NODE,
  29784. hasAttribute: function hasAttribute(name) {
  29785. return this.getAttributeNode(name) != null;
  29786. },
  29787. getAttribute: function getAttribute(name) {
  29788. var attr = this.getAttributeNode(name);
  29789. return attr && attr.value || '';
  29790. },
  29791. getAttributeNode: function getAttributeNode(name) {
  29792. return this.attributes.getNamedItem(name);
  29793. },
  29794. setAttribute: function setAttribute(name, value) {
  29795. var attr = this.ownerDocument.createAttribute(name);
  29796. attr.value = attr.nodeValue = "" + value;
  29797. this.setAttributeNode(attr);
  29798. },
  29799. removeAttribute: function removeAttribute(name) {
  29800. var attr = this.getAttributeNode(name);
  29801. attr && this.removeAttributeNode(attr);
  29802. },
  29803. //four real opeartion method
  29804. appendChild: function appendChild(newChild) {
  29805. if (newChild.nodeType === DOCUMENT_FRAGMENT_NODE) {
  29806. return this.insertBefore(newChild, null);
  29807. } else {
  29808. return _appendSingleChild(this, newChild);
  29809. }
  29810. },
  29811. setAttributeNode: function setAttributeNode(newAttr) {
  29812. return this.attributes.setNamedItem(newAttr);
  29813. },
  29814. setAttributeNodeNS: function setAttributeNodeNS(newAttr) {
  29815. return this.attributes.setNamedItemNS(newAttr);
  29816. },
  29817. removeAttributeNode: function removeAttributeNode(oldAttr) {
  29818. //console.log(this == oldAttr.ownerElement)
  29819. return this.attributes.removeNamedItem(oldAttr.nodeName);
  29820. },
  29821. //get real attribute name,and remove it by removeAttributeNode
  29822. removeAttributeNS: function removeAttributeNS(namespaceURI, localName) {
  29823. var old = this.getAttributeNodeNS(namespaceURI, localName);
  29824. old && this.removeAttributeNode(old);
  29825. },
  29826. hasAttributeNS: function hasAttributeNS(namespaceURI, localName) {
  29827. return this.getAttributeNodeNS(namespaceURI, localName) != null;
  29828. },
  29829. getAttributeNS: function getAttributeNS(namespaceURI, localName) {
  29830. var attr = this.getAttributeNodeNS(namespaceURI, localName);
  29831. return attr && attr.value || '';
  29832. },
  29833. setAttributeNS: function setAttributeNS(namespaceURI, qualifiedName, value) {
  29834. var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
  29835. attr.value = attr.nodeValue = "" + value;
  29836. this.setAttributeNode(attr);
  29837. },
  29838. getAttributeNodeNS: function getAttributeNodeNS(namespaceURI, localName) {
  29839. return this.attributes.getNamedItemNS(namespaceURI, localName);
  29840. },
  29841. getElementsByTagName: function getElementsByTagName(tagName) {
  29842. return new LiveNodeList(this, function (base) {
  29843. var ls = [];
  29844. _visitNode(base, function (node) {
  29845. if (node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)) {
  29846. ls.push(node);
  29847. }
  29848. });
  29849. return ls;
  29850. });
  29851. },
  29852. getElementsByTagNameNS: function getElementsByTagNameNS(namespaceURI, localName) {
  29853. return new LiveNodeList(this, function (base) {
  29854. var ls = [];
  29855. _visitNode(base, function (node) {
  29856. if (node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)) {
  29857. ls.push(node);
  29858. }
  29859. });
  29860. return ls;
  29861. });
  29862. }
  29863. };
  29864. Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
  29865. Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
  29866. _extends(Element, Node);
  29867. function Attr() {}
  29868. Attr.prototype.nodeType = ATTRIBUTE_NODE;
  29869. _extends(Attr, Node);
  29870. function CharacterData() {}
  29871. CharacterData.prototype = {
  29872. data: '',
  29873. substringData: function substringData(offset, count) {
  29874. return this.data.substring(offset, offset + count);
  29875. },
  29876. appendData: function appendData(text) {
  29877. text = this.data + text;
  29878. this.nodeValue = this.data = text;
  29879. this.length = text.length;
  29880. },
  29881. insertData: function insertData(offset, text) {
  29882. this.replaceData(offset, 0, text);
  29883. },
  29884. appendChild: function appendChild(newChild) {
  29885. throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR]);
  29886. },
  29887. deleteData: function deleteData(offset, count) {
  29888. this.replaceData(offset, count, "");
  29889. },
  29890. replaceData: function replaceData(offset, count, text) {
  29891. var start = this.data.substring(0, offset);
  29892. var end = this.data.substring(offset + count);
  29893. text = start + text + end;
  29894. this.nodeValue = this.data = text;
  29895. this.length = text.length;
  29896. }
  29897. };
  29898. _extends(CharacterData, Node);
  29899. function Text() {}
  29900. Text.prototype = {
  29901. nodeName: "#text",
  29902. nodeType: TEXT_NODE,
  29903. splitText: function splitText(offset) {
  29904. var text = this.data;
  29905. var newText = text.substring(offset);
  29906. text = text.substring(0, offset);
  29907. this.data = this.nodeValue = text;
  29908. this.length = text.length;
  29909. var newNode = this.ownerDocument.createTextNode(newText);
  29910. if (this.parentNode) {
  29911. this.parentNode.insertBefore(newNode, this.nextSibling);
  29912. }
  29913. return newNode;
  29914. }
  29915. };
  29916. _extends(Text, CharacterData);
  29917. function Comment() {}
  29918. Comment.prototype = {
  29919. nodeName: "#comment",
  29920. nodeType: COMMENT_NODE
  29921. };
  29922. _extends(Comment, CharacterData);
  29923. function CDATASection() {}
  29924. CDATASection.prototype = {
  29925. nodeName: "#cdata-section",
  29926. nodeType: CDATA_SECTION_NODE
  29927. };
  29928. _extends(CDATASection, CharacterData);
  29929. function DocumentType() {}
  29930. DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
  29931. _extends(DocumentType, Node);
  29932. function Notation() {}
  29933. Notation.prototype.nodeType = NOTATION_NODE;
  29934. _extends(Notation, Node);
  29935. function Entity() {}
  29936. Entity.prototype.nodeType = ENTITY_NODE;
  29937. _extends(Entity, Node);
  29938. function EntityReference() {}
  29939. EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
  29940. _extends(EntityReference, Node);
  29941. function DocumentFragment() {}
  29942. DocumentFragment.prototype.nodeName = "#document-fragment";
  29943. DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
  29944. _extends(DocumentFragment, Node);
  29945. function ProcessingInstruction() {}
  29946. ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
  29947. _extends(ProcessingInstruction, Node);
  29948. function XMLSerializer() {}
  29949. XMLSerializer.prototype.serializeToString = function (node, isHtml, nodeFilter) {
  29950. return nodeSerializeToString.call(node, isHtml, nodeFilter);
  29951. };
  29952. Node.prototype.toString = nodeSerializeToString;
  29953. function nodeSerializeToString(isHtml, nodeFilter) {
  29954. var buf = [];
  29955. var refNode = this.nodeType == 9 && this.documentElement || this;
  29956. var prefix = refNode.prefix;
  29957. var uri = refNode.namespaceURI;
  29958. if (uri && prefix == null) {
  29959. //console.log(prefix)
  29960. var prefix = refNode.lookupPrefix(uri);
  29961. if (prefix == null) {
  29962. //isHTML = true;
  29963. var visibleNamespaces = [{
  29964. namespace: uri,
  29965. prefix: null
  29966. } //{namespace:uri,prefix:''}
  29967. ];
  29968. }
  29969. }
  29970. serializeToString(this, buf, isHtml, nodeFilter, visibleNamespaces); //console.log('###',this.nodeType,uri,prefix,buf.join(''))
  29971. return buf.join('');
  29972. }
  29973. function needNamespaceDefine(node, isHTML, visibleNamespaces) {
  29974. var prefix = node.prefix || '';
  29975. var uri = node.namespaceURI; // According to [Namespaces in XML 1.0](https://www.w3.org/TR/REC-xml-names/#ns-using) ,
  29976. // and more specifically https://www.w3.org/TR/REC-xml-names/#nsc-NoPrefixUndecl :
  29977. // > In a namespace declaration for a prefix [...], the attribute value MUST NOT be empty.
  29978. // in a similar manner [Namespaces in XML 1.1](https://www.w3.org/TR/xml-names11/#ns-using)
  29979. // and more specifically https://www.w3.org/TR/xml-names11/#nsc-NSDeclared :
  29980. // > [...] Furthermore, the attribute value [...] must not be an empty string.
  29981. // so serializing empty namespace value like xmlns:ds="" would produce an invalid XML document.
  29982. if (!uri) {
  29983. return false;
  29984. }
  29985. if (prefix === "xml" && uri === NAMESPACE$2.XML || uri === NAMESPACE$2.XMLNS) {
  29986. return false;
  29987. }
  29988. var i = visibleNamespaces.length;
  29989. while (i--) {
  29990. var ns = visibleNamespaces[i]; // get namespace prefix
  29991. if (ns.prefix === prefix) {
  29992. return ns.namespace !== uri;
  29993. }
  29994. }
  29995. return true;
  29996. }
  29997. /**
  29998. * Well-formed constraint: No < in Attribute Values
  29999. * > The replacement text of any entity referred to directly or indirectly
  30000. * > in an attribute value must not contain a <.
  30001. * @see https://www.w3.org/TR/xml11/#CleanAttrVals
  30002. * @see https://www.w3.org/TR/xml11/#NT-AttValue
  30003. *
  30004. * Literal whitespace other than space that appear in attribute values
  30005. * are serialized as their entity references, so they will be preserved.
  30006. * (In contrast to whitespace literals in the input which are normalized to spaces)
  30007. * @see https://www.w3.org/TR/xml11/#AVNormalize
  30008. * @see https://w3c.github.io/DOM-Parsing/#serializing-an-element-s-attributes
  30009. */
  30010. function addSerializedAttribute(buf, qualifiedName, value) {
  30011. buf.push(' ', qualifiedName, '="', value.replace(/[<>&"\t\n\r]/g, _xmlEncoder), '"');
  30012. }
  30013. function serializeToString(node, buf, isHTML, nodeFilter, visibleNamespaces) {
  30014. if (!visibleNamespaces) {
  30015. visibleNamespaces = [];
  30016. }
  30017. if (nodeFilter) {
  30018. node = nodeFilter(node);
  30019. if (node) {
  30020. if (typeof node == 'string') {
  30021. buf.push(node);
  30022. return;
  30023. }
  30024. } else {
  30025. return;
  30026. } //buf.sort.apply(attrs, attributeSorter);
  30027. }
  30028. switch (node.nodeType) {
  30029. case ELEMENT_NODE:
  30030. var attrs = node.attributes;
  30031. var len = attrs.length;
  30032. var child = node.firstChild;
  30033. var nodeName = node.tagName;
  30034. isHTML = NAMESPACE$2.isHTML(node.namespaceURI) || isHTML;
  30035. var prefixedNodeName = nodeName;
  30036. if (!isHTML && !node.prefix && node.namespaceURI) {
  30037. var defaultNS; // lookup current default ns from `xmlns` attribute
  30038. for (var ai = 0; ai < attrs.length; ai++) {
  30039. if (attrs.item(ai).name === 'xmlns') {
  30040. defaultNS = attrs.item(ai).value;
  30041. break;
  30042. }
  30043. }
  30044. if (!defaultNS) {
  30045. // lookup current default ns in visibleNamespaces
  30046. for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) {
  30047. var namespace = visibleNamespaces[nsi];
  30048. if (namespace.prefix === '' && namespace.namespace === node.namespaceURI) {
  30049. defaultNS = namespace.namespace;
  30050. break;
  30051. }
  30052. }
  30053. }
  30054. if (defaultNS !== node.namespaceURI) {
  30055. for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) {
  30056. var namespace = visibleNamespaces[nsi];
  30057. if (namespace.namespace === node.namespaceURI) {
  30058. if (namespace.prefix) {
  30059. prefixedNodeName = namespace.prefix + ':' + nodeName;
  30060. }
  30061. break;
  30062. }
  30063. }
  30064. }
  30065. }
  30066. buf.push('<', prefixedNodeName);
  30067. for (var i = 0; i < len; i++) {
  30068. // add namespaces for attributes
  30069. var attr = attrs.item(i);
  30070. if (attr.prefix == 'xmlns') {
  30071. visibleNamespaces.push({
  30072. prefix: attr.localName,
  30073. namespace: attr.value
  30074. });
  30075. } else if (attr.nodeName == 'xmlns') {
  30076. visibleNamespaces.push({
  30077. prefix: '',
  30078. namespace: attr.value
  30079. });
  30080. }
  30081. }
  30082. for (var i = 0; i < len; i++) {
  30083. var attr = attrs.item(i);
  30084. if (needNamespaceDefine(attr, isHTML, visibleNamespaces)) {
  30085. var prefix = attr.prefix || '';
  30086. var uri = attr.namespaceURI;
  30087. addSerializedAttribute(buf, prefix ? 'xmlns:' + prefix : "xmlns", uri);
  30088. visibleNamespaces.push({
  30089. prefix: prefix,
  30090. namespace: uri
  30091. });
  30092. }
  30093. serializeToString(attr, buf, isHTML, nodeFilter, visibleNamespaces);
  30094. } // add namespace for current node
  30095. if (nodeName === prefixedNodeName && needNamespaceDefine(node, isHTML, visibleNamespaces)) {
  30096. var prefix = node.prefix || '';
  30097. var uri = node.namespaceURI;
  30098. addSerializedAttribute(buf, prefix ? 'xmlns:' + prefix : "xmlns", uri);
  30099. visibleNamespaces.push({
  30100. prefix: prefix,
  30101. namespace: uri
  30102. });
  30103. }
  30104. if (child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)) {
  30105. buf.push('>'); //if is cdata child node
  30106. if (isHTML && /^script$/i.test(nodeName)) {
  30107. while (child) {
  30108. if (child.data) {
  30109. buf.push(child.data);
  30110. } else {
  30111. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
  30112. }
  30113. child = child.nextSibling;
  30114. }
  30115. } else {
  30116. while (child) {
  30117. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
  30118. child = child.nextSibling;
  30119. }
  30120. }
  30121. buf.push('</', prefixedNodeName, '>');
  30122. } else {
  30123. buf.push('/>');
  30124. } // remove added visible namespaces
  30125. //visibleNamespaces.length = startVisibleNamespaces;
  30126. return;
  30127. case DOCUMENT_NODE:
  30128. case DOCUMENT_FRAGMENT_NODE:
  30129. var child = node.firstChild;
  30130. while (child) {
  30131. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
  30132. child = child.nextSibling;
  30133. }
  30134. return;
  30135. case ATTRIBUTE_NODE:
  30136. return addSerializedAttribute(buf, node.name, node.value);
  30137. case TEXT_NODE:
  30138. /**
  30139. * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form,
  30140. * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section.
  30141. * If they are needed elsewhere, they must be escaped using either numeric character references or the strings
  30142. * `&amp;` and `&lt;` respectively.
  30143. * The right angle bracket (>) may be represented using the string " &gt; ", and must, for compatibility,
  30144. * be escaped using either `&gt;` or a character reference when it appears in the string `]]>` in content,
  30145. * when that string is not marking the end of a CDATA section.
  30146. *
  30147. * In the content of elements, character data is any string of characters
  30148. * which does not contain the start-delimiter of any markup
  30149. * and does not include the CDATA-section-close delimiter, `]]>`.
  30150. *
  30151. * @see https://www.w3.org/TR/xml/#NT-CharData
  30152. * @see https://w3c.github.io/DOM-Parsing/#xml-serializing-a-text-node
  30153. */
  30154. return buf.push(node.data.replace(/[<&>]/g, _xmlEncoder));
  30155. case CDATA_SECTION_NODE:
  30156. return buf.push('<![CDATA[', node.data, ']]>');
  30157. case COMMENT_NODE:
  30158. return buf.push("<!--", node.data, "-->");
  30159. case DOCUMENT_TYPE_NODE:
  30160. var pubid = node.publicId;
  30161. var sysid = node.systemId;
  30162. buf.push('<!DOCTYPE ', node.name);
  30163. if (pubid) {
  30164. buf.push(' PUBLIC ', pubid);
  30165. if (sysid && sysid != '.') {
  30166. buf.push(' ', sysid);
  30167. }
  30168. buf.push('>');
  30169. } else if (sysid && sysid != '.') {
  30170. buf.push(' SYSTEM ', sysid, '>');
  30171. } else {
  30172. var sub = node.internalSubset;
  30173. if (sub) {
  30174. buf.push(" [", sub, "]");
  30175. }
  30176. buf.push(">");
  30177. }
  30178. return;
  30179. case PROCESSING_INSTRUCTION_NODE:
  30180. return buf.push("<?", node.target, " ", node.data, "?>");
  30181. case ENTITY_REFERENCE_NODE:
  30182. return buf.push('&', node.nodeName, ';');
  30183. //case ENTITY_NODE:
  30184. //case NOTATION_NODE:
  30185. default:
  30186. buf.push('??', node.nodeName);
  30187. }
  30188. }
  30189. function _importNode(doc, node, deep) {
  30190. var node2;
  30191. switch (node.nodeType) {
  30192. case ELEMENT_NODE:
  30193. node2 = node.cloneNode(false);
  30194. node2.ownerDocument = doc;
  30195. //var attrs = node2.attributes;
  30196. //var len = attrs.length;
  30197. //for(var i=0;i<len;i++){
  30198. //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
  30199. //}
  30200. case DOCUMENT_FRAGMENT_NODE:
  30201. break;
  30202. case ATTRIBUTE_NODE:
  30203. deep = true;
  30204. break;
  30205. //case ENTITY_REFERENCE_NODE:
  30206. //case PROCESSING_INSTRUCTION_NODE:
  30207. ////case TEXT_NODE:
  30208. //case CDATA_SECTION_NODE:
  30209. //case COMMENT_NODE:
  30210. // deep = false;
  30211. // break;
  30212. //case DOCUMENT_NODE:
  30213. //case DOCUMENT_TYPE_NODE:
  30214. //cannot be imported.
  30215. //case ENTITY_NODE:
  30216. //case NOTATION_NODE:
  30217. //can not hit in level3
  30218. //default:throw e;
  30219. }
  30220. if (!node2) {
  30221. node2 = node.cloneNode(false); //false
  30222. }
  30223. node2.ownerDocument = doc;
  30224. node2.parentNode = null;
  30225. if (deep) {
  30226. var child = node.firstChild;
  30227. while (child) {
  30228. node2.appendChild(_importNode(doc, child, deep));
  30229. child = child.nextSibling;
  30230. }
  30231. }
  30232. return node2;
  30233. } //
  30234. //var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
  30235. // attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};
  30236. function _cloneNode(doc, node, deep) {
  30237. var node2 = new node.constructor();
  30238. for (var n in node) {
  30239. if (Object.prototype.hasOwnProperty.call(node, n)) {
  30240. var v = node[n];
  30241. if (typeof v != "object") {
  30242. if (v != node2[n]) {
  30243. node2[n] = v;
  30244. }
  30245. }
  30246. }
  30247. }
  30248. if (node.childNodes) {
  30249. node2.childNodes = new NodeList();
  30250. }
  30251. node2.ownerDocument = doc;
  30252. switch (node2.nodeType) {
  30253. case ELEMENT_NODE:
  30254. var attrs = node.attributes;
  30255. var attrs2 = node2.attributes = new NamedNodeMap();
  30256. var len = attrs.length;
  30257. attrs2._ownerElement = node2;
  30258. for (var i = 0; i < len; i++) {
  30259. node2.setAttributeNode(_cloneNode(doc, attrs.item(i), true));
  30260. }
  30261. break;
  30262. case ATTRIBUTE_NODE:
  30263. deep = true;
  30264. }
  30265. if (deep) {
  30266. var child = node.firstChild;
  30267. while (child) {
  30268. node2.appendChild(_cloneNode(doc, child, deep));
  30269. child = child.nextSibling;
  30270. }
  30271. }
  30272. return node2;
  30273. }
  30274. function __set__(object, key, value) {
  30275. object[key] = value;
  30276. } //do dynamic
  30277. try {
  30278. if (Object.defineProperty) {
  30279. var getTextContent = function getTextContent(node) {
  30280. switch (node.nodeType) {
  30281. case ELEMENT_NODE:
  30282. case DOCUMENT_FRAGMENT_NODE:
  30283. var buf = [];
  30284. node = node.firstChild;
  30285. while (node) {
  30286. if (node.nodeType !== 7 && node.nodeType !== 8) {
  30287. buf.push(getTextContent(node));
  30288. }
  30289. node = node.nextSibling;
  30290. }
  30291. return buf.join('');
  30292. default:
  30293. return node.nodeValue;
  30294. }
  30295. };
  30296. Object.defineProperty(LiveNodeList.prototype, 'length', {
  30297. get: function get() {
  30298. _updateLiveList(this);
  30299. return this.$$length;
  30300. }
  30301. });
  30302. Object.defineProperty(Node.prototype, 'textContent', {
  30303. get: function get() {
  30304. return getTextContent(this);
  30305. },
  30306. set: function set(data) {
  30307. switch (this.nodeType) {
  30308. case ELEMENT_NODE:
  30309. case DOCUMENT_FRAGMENT_NODE:
  30310. while (this.firstChild) {
  30311. this.removeChild(this.firstChild);
  30312. }
  30313. if (data || String(data)) {
  30314. this.appendChild(this.ownerDocument.createTextNode(data));
  30315. }
  30316. break;
  30317. default:
  30318. this.data = data;
  30319. this.value = data;
  30320. this.nodeValue = data;
  30321. }
  30322. }
  30323. });
  30324. __set__ = function __set__(object, key, value) {
  30325. //console.log(value)
  30326. object['$$' + key] = value;
  30327. };
  30328. }
  30329. } catch (e) {//ie8
  30330. } //if(typeof require == 'function'){
  30331. var DocumentType_1 = DocumentType;
  30332. var DOMException_1 = DOMException;
  30333. var DOMImplementation_1 = DOMImplementation$1;
  30334. var Element_1 = Element;
  30335. var Node_1 = Node;
  30336. var NodeList_1 = NodeList;
  30337. var XMLSerializer_1 = XMLSerializer; //}
  30338. var dom = {
  30339. DocumentType: DocumentType_1,
  30340. DOMException: DOMException_1,
  30341. DOMImplementation: DOMImplementation_1,
  30342. Element: Element_1,
  30343. Node: Node_1,
  30344. NodeList: NodeList_1,
  30345. XMLSerializer: XMLSerializer_1
  30346. };
  30347. var entities = createCommonjsModule(function (module, exports) {
  30348. var freeze = conventions.freeze;
  30349. /**
  30350. * The entities that are predefined in every XML document.
  30351. *
  30352. * @see https://www.w3.org/TR/2006/REC-xml11-20060816/#sec-predefined-ent W3C XML 1.1
  30353. * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-predefined-ent W3C XML 1.0
  30354. * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Predefined_entities_in_XML Wikipedia
  30355. */
  30356. exports.XML_ENTITIES = freeze({
  30357. amp: '&',
  30358. apos: "'",
  30359. gt: '>',
  30360. lt: '<',
  30361. quot: '"'
  30362. });
  30363. /**
  30364. * A map of currently 241 entities that are detected in an HTML document.
  30365. * They contain all entries from `XML_ENTITIES`.
  30366. *
  30367. * @see XML_ENTITIES
  30368. * @see DOMParser.parseFromString
  30369. * @see DOMImplementation.prototype.createHTMLDocument
  30370. * @see https://html.spec.whatwg.org/#named-character-references WHATWG HTML(5) Spec
  30371. * @see https://www.w3.org/TR/xml-entity-names/ W3C XML Entity Names
  30372. * @see https://www.w3.org/TR/html4/sgml/entities.html W3C HTML4/SGML
  30373. * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Character_entity_references_in_HTML Wikipedia (HTML)
  30374. * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Entities_representing_special_characters_in_XHTML Wikpedia (XHTML)
  30375. */
  30376. exports.HTML_ENTITIES = freeze({
  30377. lt: '<',
  30378. gt: '>',
  30379. amp: '&',
  30380. quot: '"',
  30381. apos: "'",
  30382. Agrave: "À",
  30383. Aacute: "Á",
  30384. Acirc: "Â",
  30385. Atilde: "Ã",
  30386. Auml: "Ä",
  30387. Aring: "Å",
  30388. AElig: "Æ",
  30389. Ccedil: "Ç",
  30390. Egrave: "È",
  30391. Eacute: "É",
  30392. Ecirc: "Ê",
  30393. Euml: "Ë",
  30394. Igrave: "Ì",
  30395. Iacute: "Í",
  30396. Icirc: "Î",
  30397. Iuml: "Ï",
  30398. ETH: "Ð",
  30399. Ntilde: "Ñ",
  30400. Ograve: "Ò",
  30401. Oacute: "Ó",
  30402. Ocirc: "Ô",
  30403. Otilde: "Õ",
  30404. Ouml: "Ö",
  30405. Oslash: "Ø",
  30406. Ugrave: "Ù",
  30407. Uacute: "Ú",
  30408. Ucirc: "Û",
  30409. Uuml: "Ü",
  30410. Yacute: "Ý",
  30411. THORN: "Þ",
  30412. szlig: "ß",
  30413. agrave: "à",
  30414. aacute: "á",
  30415. acirc: "â",
  30416. atilde: "ã",
  30417. auml: "ä",
  30418. aring: "å",
  30419. aelig: "æ",
  30420. ccedil: "ç",
  30421. egrave: "è",
  30422. eacute: "é",
  30423. ecirc: "ê",
  30424. euml: "ë",
  30425. igrave: "ì",
  30426. iacute: "í",
  30427. icirc: "î",
  30428. iuml: "ï",
  30429. eth: "ð",
  30430. ntilde: "ñ",
  30431. ograve: "ò",
  30432. oacute: "ó",
  30433. ocirc: "ô",
  30434. otilde: "õ",
  30435. ouml: "ö",
  30436. oslash: "ø",
  30437. ugrave: "ù",
  30438. uacute: "ú",
  30439. ucirc: "û",
  30440. uuml: "ü",
  30441. yacute: "ý",
  30442. thorn: "þ",
  30443. yuml: "ÿ",
  30444. nbsp: "\xA0",
  30445. iexcl: "¡",
  30446. cent: "¢",
  30447. pound: "£",
  30448. curren: "¤",
  30449. yen: "¥",
  30450. brvbar: "¦",
  30451. sect: "§",
  30452. uml: "¨",
  30453. copy: "©",
  30454. ordf: "ª",
  30455. laquo: "«",
  30456. not: "¬",
  30457. shy: "­­",
  30458. reg: "®",
  30459. macr: "¯",
  30460. deg: "°",
  30461. plusmn: "±",
  30462. sup2: "²",
  30463. sup3: "³",
  30464. acute: "´",
  30465. micro: "µ",
  30466. para: "¶",
  30467. middot: "·",
  30468. cedil: "¸",
  30469. sup1: "¹",
  30470. ordm: "º",
  30471. raquo: "»",
  30472. frac14: "¼",
  30473. frac12: "½",
  30474. frac34: "¾",
  30475. iquest: "¿",
  30476. times: "×",
  30477. divide: "÷",
  30478. forall: "∀",
  30479. part: "∂",
  30480. exist: "∃",
  30481. empty: "∅",
  30482. nabla: "∇",
  30483. isin: "∈",
  30484. notin: "∉",
  30485. ni: "∋",
  30486. prod: "∏",
  30487. sum: "∑",
  30488. minus: "−",
  30489. lowast: "∗",
  30490. radic: "√",
  30491. prop: "∝",
  30492. infin: "∞",
  30493. ang: "∠",
  30494. and: "∧",
  30495. or: "∨",
  30496. cap: "∩",
  30497. cup: "∪",
  30498. 'int': "∫",
  30499. there4: "∴",
  30500. sim: "∼",
  30501. cong: "≅",
  30502. asymp: "≈",
  30503. ne: "≠",
  30504. equiv: "≡",
  30505. le: "≤",
  30506. ge: "≥",
  30507. sub: "⊂",
  30508. sup: "⊃",
  30509. nsub: "⊄",
  30510. sube: "⊆",
  30511. supe: "⊇",
  30512. oplus: "⊕",
  30513. otimes: "⊗",
  30514. perp: "⊥",
  30515. sdot: "⋅",
  30516. Alpha: "Α",
  30517. Beta: "Β",
  30518. Gamma: "Γ",
  30519. Delta: "Δ",
  30520. Epsilon: "Ε",
  30521. Zeta: "Ζ",
  30522. Eta: "Η",
  30523. Theta: "Θ",
  30524. Iota: "Ι",
  30525. Kappa: "Κ",
  30526. Lambda: "Λ",
  30527. Mu: "Μ",
  30528. Nu: "Ν",
  30529. Xi: "Ξ",
  30530. Omicron: "Ο",
  30531. Pi: "Π",
  30532. Rho: "Ρ",
  30533. Sigma: "Σ",
  30534. Tau: "Τ",
  30535. Upsilon: "Υ",
  30536. Phi: "Φ",
  30537. Chi: "Χ",
  30538. Psi: "Ψ",
  30539. Omega: "Ω",
  30540. alpha: "α",
  30541. beta: "β",
  30542. gamma: "γ",
  30543. delta: "δ",
  30544. epsilon: "ε",
  30545. zeta: "ζ",
  30546. eta: "η",
  30547. theta: "θ",
  30548. iota: "ι",
  30549. kappa: "κ",
  30550. lambda: "λ",
  30551. mu: "μ",
  30552. nu: "ν",
  30553. xi: "ξ",
  30554. omicron: "ο",
  30555. pi: "π",
  30556. rho: "ρ",
  30557. sigmaf: "ς",
  30558. sigma: "σ",
  30559. tau: "τ",
  30560. upsilon: "υ",
  30561. phi: "φ",
  30562. chi: "χ",
  30563. psi: "ψ",
  30564. omega: "ω",
  30565. thetasym: "ϑ",
  30566. upsih: "ϒ",
  30567. piv: "ϖ",
  30568. OElig: "Œ",
  30569. oelig: "œ",
  30570. Scaron: "Š",
  30571. scaron: "š",
  30572. Yuml: "Ÿ",
  30573. fnof: "ƒ",
  30574. circ: "ˆ",
  30575. tilde: "˜",
  30576. ensp: " ",
  30577. emsp: " ",
  30578. thinsp: " ",
  30579. zwnj: "‌",
  30580. zwj: "‍",
  30581. lrm: "‎",
  30582. rlm: "‏",
  30583. ndash: "–",
  30584. mdash: "—",
  30585. lsquo: "‘",
  30586. rsquo: "’",
  30587. sbquo: "‚",
  30588. ldquo: "“",
  30589. rdquo: "”",
  30590. bdquo: "„",
  30591. dagger: "†",
  30592. Dagger: "‡",
  30593. bull: "•",
  30594. hellip: "…",
  30595. permil: "‰",
  30596. prime: "′",
  30597. Prime: "″",
  30598. lsaquo: "‹",
  30599. rsaquo: "›",
  30600. oline: "‾",
  30601. euro: "€",
  30602. trade: "™",
  30603. larr: "←",
  30604. uarr: "↑",
  30605. rarr: "→",
  30606. darr: "↓",
  30607. harr: "↔",
  30608. crarr: "↵",
  30609. lceil: "⌈",
  30610. rceil: "⌉",
  30611. lfloor: "⌊",
  30612. rfloor: "⌋",
  30613. loz: "◊",
  30614. spades: "♠",
  30615. clubs: "♣",
  30616. hearts: "♥",
  30617. diams: "♦"
  30618. });
  30619. /**
  30620. * @deprecated use `HTML_ENTITIES` instead
  30621. * @see HTML_ENTITIES
  30622. */
  30623. exports.entityMap = exports.HTML_ENTITIES;
  30624. });
  30625. entities.XML_ENTITIES;
  30626. entities.HTML_ENTITIES;
  30627. entities.entityMap;
  30628. var NAMESPACE$1 = conventions.NAMESPACE; //[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
  30629. //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
  30630. //[5] Name ::= NameStartChar (NameChar)*
  30631. var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/; //\u10000-\uEFFFF
  30632. var nameChar = new RegExp("[\\-\\.0-9" + nameStartChar.source.slice(1, -1) + "\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
  30633. var tagNamePattern = new RegExp('^' + nameStartChar.source + nameChar.source + '*(?:\:' + nameStartChar.source + nameChar.source + '*)?$'); //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
  30634. //var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',')
  30635. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  30636. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  30637. var S_TAG = 0; //tag name offerring
  30638. var S_ATTR = 1; //attr name offerring
  30639. var S_ATTR_SPACE = 2; //attr name end and space offer
  30640. var S_EQ = 3; //=space?
  30641. var S_ATTR_NOQUOT_VALUE = 4; //attr value(no quot value only)
  30642. var S_ATTR_END = 5; //attr value end and no space(quot end)
  30643. var S_TAG_SPACE = 6; //(attr value end || tag end ) && (space offer)
  30644. var S_TAG_CLOSE = 7; //closed el<el />
  30645. /**
  30646. * Creates an error that will not be caught by XMLReader aka the SAX parser.
  30647. *
  30648. * @param {string} message
  30649. * @param {any?} locator Optional, can provide details about the location in the source
  30650. * @constructor
  30651. */
  30652. function ParseError$1(message, locator) {
  30653. this.message = message;
  30654. this.locator = locator;
  30655. if (Error.captureStackTrace) Error.captureStackTrace(this, ParseError$1);
  30656. }
  30657. ParseError$1.prototype = new Error();
  30658. ParseError$1.prototype.name = ParseError$1.name;
  30659. function XMLReader$1() {}
  30660. XMLReader$1.prototype = {
  30661. parse: function parse(source, defaultNSMap, entityMap) {
  30662. var domBuilder = this.domBuilder;
  30663. domBuilder.startDocument();
  30664. _copy(defaultNSMap, defaultNSMap = {});
  30665. _parse(source, defaultNSMap, entityMap, domBuilder, this.errorHandler);
  30666. domBuilder.endDocument();
  30667. }
  30668. };
  30669. function _parse(source, defaultNSMapCopy, entityMap, domBuilder, errorHandler) {
  30670. function fixedFromCharCode(code) {
  30671. // String.prototype.fromCharCode does not supports
  30672. // > 2 bytes unicode chars directly
  30673. if (code > 0xffff) {
  30674. code -= 0x10000;
  30675. var surrogate1 = 0xd800 + (code >> 10),
  30676. surrogate2 = 0xdc00 + (code & 0x3ff);
  30677. return String.fromCharCode(surrogate1, surrogate2);
  30678. } else {
  30679. return String.fromCharCode(code);
  30680. }
  30681. }
  30682. function entityReplacer(a) {
  30683. var k = a.slice(1, -1);
  30684. if (Object.hasOwnProperty.call(entityMap, k)) {
  30685. return entityMap[k];
  30686. } else if (k.charAt(0) === '#') {
  30687. return fixedFromCharCode(parseInt(k.substr(1).replace('x', '0x')));
  30688. } else {
  30689. errorHandler.error('entity not found:' + a);
  30690. return a;
  30691. }
  30692. }
  30693. function appendText(end) {
  30694. //has some bugs
  30695. if (end > start) {
  30696. var xt = source.substring(start, end).replace(/&#?\w+;/g, entityReplacer);
  30697. locator && position(start);
  30698. domBuilder.characters(xt, 0, end - start);
  30699. start = end;
  30700. }
  30701. }
  30702. function position(p, m) {
  30703. while (p >= lineEnd && (m = linePattern.exec(source))) {
  30704. lineStart = m.index;
  30705. lineEnd = lineStart + m[0].length;
  30706. locator.lineNumber++; //console.log('line++:',locator,startPos,endPos)
  30707. }
  30708. locator.columnNumber = p - lineStart + 1;
  30709. }
  30710. var lineStart = 0;
  30711. var lineEnd = 0;
  30712. var linePattern = /.*(?:\r\n?|\n)|.*$/g;
  30713. var locator = domBuilder.locator;
  30714. var parseStack = [{
  30715. currentNSMap: defaultNSMapCopy
  30716. }];
  30717. var closeMap = {};
  30718. var start = 0;
  30719. while (true) {
  30720. try {
  30721. var tagStart = source.indexOf('<', start);
  30722. if (tagStart < 0) {
  30723. if (!source.substr(start).match(/^\s*$/)) {
  30724. var doc = domBuilder.doc;
  30725. var text = doc.createTextNode(source.substr(start));
  30726. doc.appendChild(text);
  30727. domBuilder.currentElement = text;
  30728. }
  30729. return;
  30730. }
  30731. if (tagStart > start) {
  30732. appendText(tagStart);
  30733. }
  30734. switch (source.charAt(tagStart + 1)) {
  30735. case '/':
  30736. var end = source.indexOf('>', tagStart + 3);
  30737. var tagName = source.substring(tagStart + 2, end).replace(/[ \t\n\r]+$/g, '');
  30738. var config = parseStack.pop();
  30739. if (end < 0) {
  30740. tagName = source.substring(tagStart + 2).replace(/[\s<].*/, '');
  30741. errorHandler.error("end tag name: " + tagName + ' is not complete:' + config.tagName);
  30742. end = tagStart + 1 + tagName.length;
  30743. } else if (tagName.match(/\s</)) {
  30744. tagName = tagName.replace(/[\s<].*/, '');
  30745. errorHandler.error("end tag name: " + tagName + ' maybe not complete');
  30746. end = tagStart + 1 + tagName.length;
  30747. }
  30748. var localNSMap = config.localNSMap;
  30749. var endMatch = config.tagName == tagName;
  30750. var endIgnoreCaseMach = endMatch || config.tagName && config.tagName.toLowerCase() == tagName.toLowerCase();
  30751. if (endIgnoreCaseMach) {
  30752. domBuilder.endElement(config.uri, config.localName, tagName);
  30753. if (localNSMap) {
  30754. for (var prefix in localNSMap) {
  30755. if (Object.prototype.hasOwnProperty.call(localNSMap, prefix)) {
  30756. domBuilder.endPrefixMapping(prefix);
  30757. }
  30758. }
  30759. }
  30760. if (!endMatch) {
  30761. errorHandler.fatalError("end tag name: " + tagName + ' is not match the current start tagName:' + config.tagName); // No known test case
  30762. }
  30763. } else {
  30764. parseStack.push(config);
  30765. }
  30766. end++;
  30767. break;
  30768. // end elment
  30769. case '?':
  30770. // <?...?>
  30771. locator && position(tagStart);
  30772. end = parseInstruction(source, tagStart, domBuilder);
  30773. break;
  30774. case '!':
  30775. // <!doctype,<![CDATA,<!--
  30776. locator && position(tagStart);
  30777. end = parseDCC(source, tagStart, domBuilder, errorHandler);
  30778. break;
  30779. default:
  30780. locator && position(tagStart);
  30781. var el = new ElementAttributes();
  30782. var currentNSMap = parseStack[parseStack.length - 1].currentNSMap; //elStartEnd
  30783. var end = parseElementStartPart(source, tagStart, el, currentNSMap, entityReplacer, errorHandler);
  30784. var len = el.length;
  30785. if (!el.closed && fixSelfClosed(source, end, el.tagName, closeMap)) {
  30786. el.closed = true;
  30787. if (!entityMap.nbsp) {
  30788. errorHandler.warning('unclosed xml attribute');
  30789. }
  30790. }
  30791. if (locator && len) {
  30792. var locator2 = copyLocator(locator, {}); //try{//attribute position fixed
  30793. for (var i = 0; i < len; i++) {
  30794. var a = el[i];
  30795. position(a.offset);
  30796. a.locator = copyLocator(locator, {});
  30797. }
  30798. domBuilder.locator = locator2;
  30799. if (appendElement$1(el, domBuilder, currentNSMap)) {
  30800. parseStack.push(el);
  30801. }
  30802. domBuilder.locator = locator;
  30803. } else {
  30804. if (appendElement$1(el, domBuilder, currentNSMap)) {
  30805. parseStack.push(el);
  30806. }
  30807. }
  30808. if (NAMESPACE$1.isHTML(el.uri) && !el.closed) {
  30809. end = parseHtmlSpecialContent(source, end, el.tagName, entityReplacer, domBuilder);
  30810. } else {
  30811. end++;
  30812. }
  30813. }
  30814. } catch (e) {
  30815. if (e instanceof ParseError$1) {
  30816. throw e;
  30817. }
  30818. errorHandler.error('element parse error: ' + e);
  30819. end = -1;
  30820. }
  30821. if (end > start) {
  30822. start = end;
  30823. } else {
  30824. //TODO: 这里有可能sax回退,有位置错误风险
  30825. appendText(Math.max(tagStart, start) + 1);
  30826. }
  30827. }
  30828. }
  30829. function copyLocator(f, t) {
  30830. t.lineNumber = f.lineNumber;
  30831. t.columnNumber = f.columnNumber;
  30832. return t;
  30833. }
  30834. /**
  30835. * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
  30836. * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
  30837. */
  30838. function parseElementStartPart(source, start, el, currentNSMap, entityReplacer, errorHandler) {
  30839. /**
  30840. * @param {string} qname
  30841. * @param {string} value
  30842. * @param {number} startIndex
  30843. */
  30844. function addAttribute(qname, value, startIndex) {
  30845. if (el.attributeNames.hasOwnProperty(qname)) {
  30846. errorHandler.fatalError('Attribute ' + qname + ' redefined');
  30847. }
  30848. el.addValue(qname, // @see https://www.w3.org/TR/xml/#AVNormalize
  30849. // since the xmldom sax parser does not "interpret" DTD the following is not implemented:
  30850. // - recursive replacement of (DTD) entity references
  30851. // - trimming and collapsing multiple spaces into a single one for attributes that are not of type CDATA
  30852. value.replace(/[\t\n\r]/g, ' ').replace(/&#?\w+;/g, entityReplacer), startIndex);
  30853. }
  30854. var attrName;
  30855. var value;
  30856. var p = ++start;
  30857. var s = S_TAG; //status
  30858. while (true) {
  30859. var c = source.charAt(p);
  30860. switch (c) {
  30861. case '=':
  30862. if (s === S_ATTR) {
  30863. //attrName
  30864. attrName = source.slice(start, p);
  30865. s = S_EQ;
  30866. } else if (s === S_ATTR_SPACE) {
  30867. s = S_EQ;
  30868. } else {
  30869. //fatalError: equal must after attrName or space after attrName
  30870. throw new Error('attribute equal must after attrName'); // No known test case
  30871. }
  30872. break;
  30873. case '\'':
  30874. case '"':
  30875. if (s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
  30876. ) {
  30877. //equal
  30878. if (s === S_ATTR) {
  30879. errorHandler.warning('attribute value must after "="');
  30880. attrName = source.slice(start, p);
  30881. }
  30882. start = p + 1;
  30883. p = source.indexOf(c, start);
  30884. if (p > 0) {
  30885. value = source.slice(start, p);
  30886. addAttribute(attrName, value, start - 1);
  30887. s = S_ATTR_END;
  30888. } else {
  30889. //fatalError: no end quot match
  30890. throw new Error('attribute value no end \'' + c + '\' match');
  30891. }
  30892. } else if (s == S_ATTR_NOQUOT_VALUE) {
  30893. value = source.slice(start, p);
  30894. addAttribute(attrName, value, start);
  30895. errorHandler.warning('attribute "' + attrName + '" missed start quot(' + c + ')!!');
  30896. start = p + 1;
  30897. s = S_ATTR_END;
  30898. } else {
  30899. //fatalError: no equal before
  30900. throw new Error('attribute value must after "="'); // No known test case
  30901. }
  30902. break;
  30903. case '/':
  30904. switch (s) {
  30905. case S_TAG:
  30906. el.setTagName(source.slice(start, p));
  30907. case S_ATTR_END:
  30908. case S_TAG_SPACE:
  30909. case S_TAG_CLOSE:
  30910. s = S_TAG_CLOSE;
  30911. el.closed = true;
  30912. case S_ATTR_NOQUOT_VALUE:
  30913. case S_ATTR:
  30914. case S_ATTR_SPACE:
  30915. break;
  30916. //case S_EQ:
  30917. default:
  30918. throw new Error("attribute invalid close char('/')");
  30919. // No known test case
  30920. }
  30921. break;
  30922. case '':
  30923. //end document
  30924. errorHandler.error('unexpected end of input');
  30925. if (s == S_TAG) {
  30926. el.setTagName(source.slice(start, p));
  30927. }
  30928. return p;
  30929. case '>':
  30930. switch (s) {
  30931. case S_TAG:
  30932. el.setTagName(source.slice(start, p));
  30933. case S_ATTR_END:
  30934. case S_TAG_SPACE:
  30935. case S_TAG_CLOSE:
  30936. break;
  30937. //normal
  30938. case S_ATTR_NOQUOT_VALUE: //Compatible state
  30939. case S_ATTR:
  30940. value = source.slice(start, p);
  30941. if (value.slice(-1) === '/') {
  30942. el.closed = true;
  30943. value = value.slice(0, -1);
  30944. }
  30945. case S_ATTR_SPACE:
  30946. if (s === S_ATTR_SPACE) {
  30947. value = attrName;
  30948. }
  30949. if (s == S_ATTR_NOQUOT_VALUE) {
  30950. errorHandler.warning('attribute "' + value + '" missed quot(")!');
  30951. addAttribute(attrName, value, start);
  30952. } else {
  30953. if (!NAMESPACE$1.isHTML(currentNSMap['']) || !value.match(/^(?:disabled|checked|selected)$/i)) {
  30954. errorHandler.warning('attribute "' + value + '" missed value!! "' + value + '" instead!!');
  30955. }
  30956. addAttribute(value, value, start);
  30957. }
  30958. break;
  30959. case S_EQ:
  30960. throw new Error('attribute value missed!!');
  30961. } // console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
  30962. return p;
  30963. /*xml space '\x20' | #x9 | #xD | #xA; */
  30964. case "\x80":
  30965. c = ' ';
  30966. default:
  30967. if (c <= ' ') {
  30968. //space
  30969. switch (s) {
  30970. case S_TAG:
  30971. el.setTagName(source.slice(start, p)); //tagName
  30972. s = S_TAG_SPACE;
  30973. break;
  30974. case S_ATTR:
  30975. attrName = source.slice(start, p);
  30976. s = S_ATTR_SPACE;
  30977. break;
  30978. case S_ATTR_NOQUOT_VALUE:
  30979. var value = source.slice(start, p);
  30980. errorHandler.warning('attribute "' + value + '" missed quot(")!!');
  30981. addAttribute(attrName, value, start);
  30982. case S_ATTR_END:
  30983. s = S_TAG_SPACE;
  30984. break;
  30985. //case S_TAG_SPACE:
  30986. //case S_EQ:
  30987. //case S_ATTR_SPACE:
  30988. // void();break;
  30989. //case S_TAG_CLOSE:
  30990. //ignore warning
  30991. }
  30992. } else {
  30993. //not space
  30994. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  30995. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  30996. switch (s) {
  30997. //case S_TAG:void();break;
  30998. //case S_ATTR:void();break;
  30999. //case S_ATTR_NOQUOT_VALUE:void();break;
  31000. case S_ATTR_SPACE:
  31001. el.tagName;
  31002. if (!NAMESPACE$1.isHTML(currentNSMap['']) || !attrName.match(/^(?:disabled|checked|selected)$/i)) {
  31003. errorHandler.warning('attribute "' + attrName + '" missed value!! "' + attrName + '" instead2!!');
  31004. }
  31005. addAttribute(attrName, attrName, start);
  31006. start = p;
  31007. s = S_ATTR;
  31008. break;
  31009. case S_ATTR_END:
  31010. errorHandler.warning('attribute space is required"' + attrName + '"!!');
  31011. case S_TAG_SPACE:
  31012. s = S_ATTR;
  31013. start = p;
  31014. break;
  31015. case S_EQ:
  31016. s = S_ATTR_NOQUOT_VALUE;
  31017. start = p;
  31018. break;
  31019. case S_TAG_CLOSE:
  31020. throw new Error("elements closed character '/' and '>' must be connected to");
  31021. }
  31022. }
  31023. } //end outer switch
  31024. //console.log('p++',p)
  31025. p++;
  31026. }
  31027. }
  31028. /**
  31029. * @return true if has new namespace define
  31030. */
  31031. function appendElement$1(el, domBuilder, currentNSMap) {
  31032. var tagName = el.tagName;
  31033. var localNSMap = null; //var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
  31034. var i = el.length;
  31035. while (i--) {
  31036. var a = el[i];
  31037. var qName = a.qName;
  31038. var value = a.value;
  31039. var nsp = qName.indexOf(':');
  31040. if (nsp > 0) {
  31041. var prefix = a.prefix = qName.slice(0, nsp);
  31042. var localName = qName.slice(nsp + 1);
  31043. var nsPrefix = prefix === 'xmlns' && localName;
  31044. } else {
  31045. localName = qName;
  31046. prefix = null;
  31047. nsPrefix = qName === 'xmlns' && '';
  31048. } //can not set prefix,because prefix !== ''
  31049. a.localName = localName; //prefix == null for no ns prefix attribute
  31050. if (nsPrefix !== false) {
  31051. //hack!!
  31052. if (localNSMap == null) {
  31053. localNSMap = {}; //console.log(currentNSMap,0)
  31054. _copy(currentNSMap, currentNSMap = {}); //console.log(currentNSMap,1)
  31055. }
  31056. currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
  31057. a.uri = NAMESPACE$1.XMLNS;
  31058. domBuilder.startPrefixMapping(nsPrefix, value);
  31059. }
  31060. }
  31061. var i = el.length;
  31062. while (i--) {
  31063. a = el[i];
  31064. var prefix = a.prefix;
  31065. if (prefix) {
  31066. //no prefix attribute has no namespace
  31067. if (prefix === 'xml') {
  31068. a.uri = NAMESPACE$1.XML;
  31069. }
  31070. if (prefix !== 'xmlns') {
  31071. a.uri = currentNSMap[prefix || '']; //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
  31072. }
  31073. }
  31074. }
  31075. var nsp = tagName.indexOf(':');
  31076. if (nsp > 0) {
  31077. prefix = el.prefix = tagName.slice(0, nsp);
  31078. localName = el.localName = tagName.slice(nsp + 1);
  31079. } else {
  31080. prefix = null; //important!!
  31081. localName = el.localName = tagName;
  31082. } //no prefix element has default namespace
  31083. var ns = el.uri = currentNSMap[prefix || ''];
  31084. domBuilder.startElement(ns, localName, tagName, el); //endPrefixMapping and startPrefixMapping have not any help for dom builder
  31085. //localNSMap = null
  31086. if (el.closed) {
  31087. domBuilder.endElement(ns, localName, tagName);
  31088. if (localNSMap) {
  31089. for (prefix in localNSMap) {
  31090. if (Object.prototype.hasOwnProperty.call(localNSMap, prefix)) {
  31091. domBuilder.endPrefixMapping(prefix);
  31092. }
  31093. }
  31094. }
  31095. } else {
  31096. el.currentNSMap = currentNSMap;
  31097. el.localNSMap = localNSMap; //parseStack.push(el);
  31098. return true;
  31099. }
  31100. }
  31101. function parseHtmlSpecialContent(source, elStartEnd, tagName, entityReplacer, domBuilder) {
  31102. if (/^(?:script|textarea)$/i.test(tagName)) {
  31103. var elEndStart = source.indexOf('</' + tagName + '>', elStartEnd);
  31104. var text = source.substring(elStartEnd + 1, elEndStart);
  31105. if (/[&<]/.test(text)) {
  31106. if (/^script$/i.test(tagName)) {
  31107. //if(!/\]\]>/.test(text)){
  31108. //lexHandler.startCDATA();
  31109. domBuilder.characters(text, 0, text.length); //lexHandler.endCDATA();
  31110. return elEndStart; //}
  31111. } //}else{//text area
  31112. text = text.replace(/&#?\w+;/g, entityReplacer);
  31113. domBuilder.characters(text, 0, text.length);
  31114. return elEndStart; //}
  31115. }
  31116. }
  31117. return elStartEnd + 1;
  31118. }
  31119. function fixSelfClosed(source, elStartEnd, tagName, closeMap) {
  31120. //if(tagName in closeMap){
  31121. var pos = closeMap[tagName];
  31122. if (pos == null) {
  31123. //console.log(tagName)
  31124. pos = source.lastIndexOf('</' + tagName + '>');
  31125. if (pos < elStartEnd) {
  31126. //忘记闭合
  31127. pos = source.lastIndexOf('</' + tagName);
  31128. }
  31129. closeMap[tagName] = pos;
  31130. }
  31131. return pos < elStartEnd; //}
  31132. }
  31133. function _copy(source, target) {
  31134. for (var n in source) {
  31135. if (Object.prototype.hasOwnProperty.call(source, n)) {
  31136. target[n] = source[n];
  31137. }
  31138. }
  31139. }
  31140. function parseDCC(source, start, domBuilder, errorHandler) {
  31141. //sure start with '<!'
  31142. var next = source.charAt(start + 2);
  31143. switch (next) {
  31144. case '-':
  31145. if (source.charAt(start + 3) === '-') {
  31146. var end = source.indexOf('-->', start + 4); //append comment source.substring(4,end)//<!--
  31147. if (end > start) {
  31148. domBuilder.comment(source, start + 4, end - start - 4);
  31149. return end + 3;
  31150. } else {
  31151. errorHandler.error("Unclosed comment");
  31152. return -1;
  31153. }
  31154. } else {
  31155. //error
  31156. return -1;
  31157. }
  31158. default:
  31159. if (source.substr(start + 3, 6) == 'CDATA[') {
  31160. var end = source.indexOf(']]>', start + 9);
  31161. domBuilder.startCDATA();
  31162. domBuilder.characters(source, start + 9, end - start - 9);
  31163. domBuilder.endCDATA();
  31164. return end + 3;
  31165. } //<!DOCTYPE
  31166. //startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
  31167. var matchs = split(source, start);
  31168. var len = matchs.length;
  31169. if (len > 1 && /!doctype/i.test(matchs[0][0])) {
  31170. var name = matchs[1][0];
  31171. var pubid = false;
  31172. var sysid = false;
  31173. if (len > 3) {
  31174. if (/^public$/i.test(matchs[2][0])) {
  31175. pubid = matchs[3][0];
  31176. sysid = len > 4 && matchs[4][0];
  31177. } else if (/^system$/i.test(matchs[2][0])) {
  31178. sysid = matchs[3][0];
  31179. }
  31180. }
  31181. var lastMatch = matchs[len - 1];
  31182. domBuilder.startDTD(name, pubid, sysid);
  31183. domBuilder.endDTD();
  31184. return lastMatch.index + lastMatch[0].length;
  31185. }
  31186. }
  31187. return -1;
  31188. }
  31189. function parseInstruction(source, start, domBuilder) {
  31190. var end = source.indexOf('?>', start);
  31191. if (end) {
  31192. var match = source.substring(start, end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
  31193. if (match) {
  31194. match[0].length;
  31195. domBuilder.processingInstruction(match[1], match[2]);
  31196. return end + 2;
  31197. } else {
  31198. //error
  31199. return -1;
  31200. }
  31201. }
  31202. return -1;
  31203. }
  31204. function ElementAttributes() {
  31205. this.attributeNames = {};
  31206. }
  31207. ElementAttributes.prototype = {
  31208. setTagName: function setTagName(tagName) {
  31209. if (!tagNamePattern.test(tagName)) {
  31210. throw new Error('invalid tagName:' + tagName);
  31211. }
  31212. this.tagName = tagName;
  31213. },
  31214. addValue: function addValue(qName, value, offset) {
  31215. if (!tagNamePattern.test(qName)) {
  31216. throw new Error('invalid attribute:' + qName);
  31217. }
  31218. this.attributeNames[qName] = this.length;
  31219. this[this.length++] = {
  31220. qName: qName,
  31221. value: value,
  31222. offset: offset
  31223. };
  31224. },
  31225. length: 0,
  31226. getLocalName: function getLocalName(i) {
  31227. return this[i].localName;
  31228. },
  31229. getLocator: function getLocator(i) {
  31230. return this[i].locator;
  31231. },
  31232. getQName: function getQName(i) {
  31233. return this[i].qName;
  31234. },
  31235. getURI: function getURI(i) {
  31236. return this[i].uri;
  31237. },
  31238. getValue: function getValue(i) {
  31239. return this[i].value;
  31240. } // ,getIndex:function(uri, localName)){
  31241. // if(localName){
  31242. //
  31243. // }else{
  31244. // var qName = uri
  31245. // }
  31246. // },
  31247. // getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
  31248. // getType:function(uri,localName){}
  31249. // getType:function(i){},
  31250. };
  31251. function split(source, start) {
  31252. var match;
  31253. var buf = [];
  31254. var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
  31255. reg.lastIndex = start;
  31256. reg.exec(source); //skip <
  31257. while (match = reg.exec(source)) {
  31258. buf.push(match);
  31259. if (match[1]) return buf;
  31260. }
  31261. }
  31262. var XMLReader_1 = XMLReader$1;
  31263. var ParseError_1 = ParseError$1;
  31264. var sax = {
  31265. XMLReader: XMLReader_1,
  31266. ParseError: ParseError_1
  31267. };
  31268. var DOMImplementation = dom.DOMImplementation;
  31269. var NAMESPACE = conventions.NAMESPACE;
  31270. var ParseError = sax.ParseError;
  31271. var XMLReader = sax.XMLReader;
  31272. /**
  31273. * Normalizes line ending according to https://www.w3.org/TR/xml11/#sec-line-ends:
  31274. *
  31275. * > XML parsed entities are often stored in computer files which,
  31276. * > for editing convenience, are organized into lines.
  31277. * > These lines are typically separated by some combination
  31278. * > of the characters CARRIAGE RETURN (#xD) and LINE FEED (#xA).
  31279. * >
  31280. * > To simplify the tasks of applications, the XML processor must behave
  31281. * > as if it normalized all line breaks in external parsed entities (including the document entity)
  31282. * > on input, before parsing, by translating all of the following to a single #xA character:
  31283. * >
  31284. * > 1. the two-character sequence #xD #xA
  31285. * > 2. the two-character sequence #xD #x85
  31286. * > 3. the single character #x85
  31287. * > 4. the single character #x2028
  31288. * > 5. any #xD character that is not immediately followed by #xA or #x85.
  31289. *
  31290. * @param {string} input
  31291. * @returns {string}
  31292. */
  31293. function normalizeLineEndings(input) {
  31294. return input.replace(/\r[\n\u0085]/g, '\n').replace(/[\r\u0085\u2028]/g, '\n');
  31295. }
  31296. /**
  31297. * @typedef Locator
  31298. * @property {number} [columnNumber]
  31299. * @property {number} [lineNumber]
  31300. */
  31301. /**
  31302. * @typedef DOMParserOptions
  31303. * @property {DOMHandler} [domBuilder]
  31304. * @property {Function} [errorHandler]
  31305. * @property {(string) => string} [normalizeLineEndings] used to replace line endings before parsing
  31306. * defaults to `normalizeLineEndings`
  31307. * @property {Locator} [locator]
  31308. * @property {Record<string, string>} [xmlns]
  31309. *
  31310. * @see normalizeLineEndings
  31311. */
  31312. /**
  31313. * The DOMParser interface provides the ability to parse XML or HTML source code
  31314. * from a string into a DOM `Document`.
  31315. *
  31316. * _xmldom is different from the spec in that it allows an `options` parameter,
  31317. * to override the default behavior._
  31318. *
  31319. * @param {DOMParserOptions} [options]
  31320. * @constructor
  31321. *
  31322. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
  31323. * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-parsing-and-serialization
  31324. */
  31325. function DOMParser$1(options) {
  31326. this.options = options || {
  31327. locator: {}
  31328. };
  31329. }
  31330. DOMParser$1.prototype.parseFromString = function (source, mimeType) {
  31331. var options = this.options;
  31332. var sax = new XMLReader();
  31333. var domBuilder = options.domBuilder || new DOMHandler(); //contentHandler and LexicalHandler
  31334. var errorHandler = options.errorHandler;
  31335. var locator = options.locator;
  31336. var defaultNSMap = options.xmlns || {};
  31337. var isHTML = /\/x?html?$/.test(mimeType); //mimeType.toLowerCase().indexOf('html') > -1;
  31338. var entityMap = isHTML ? entities.HTML_ENTITIES : entities.XML_ENTITIES;
  31339. if (locator) {
  31340. domBuilder.setDocumentLocator(locator);
  31341. }
  31342. sax.errorHandler = buildErrorHandler(errorHandler, domBuilder, locator);
  31343. sax.domBuilder = options.domBuilder || domBuilder;
  31344. if (isHTML) {
  31345. defaultNSMap[''] = NAMESPACE.HTML;
  31346. }
  31347. defaultNSMap.xml = defaultNSMap.xml || NAMESPACE.XML;
  31348. var normalize = options.normalizeLineEndings || normalizeLineEndings;
  31349. if (source && typeof source === 'string') {
  31350. sax.parse(normalize(source), defaultNSMap, entityMap);
  31351. } else {
  31352. sax.errorHandler.error('invalid doc source');
  31353. }
  31354. return domBuilder.doc;
  31355. };
  31356. function buildErrorHandler(errorImpl, domBuilder, locator) {
  31357. if (!errorImpl) {
  31358. if (domBuilder instanceof DOMHandler) {
  31359. return domBuilder;
  31360. }
  31361. errorImpl = domBuilder;
  31362. }
  31363. var errorHandler = {};
  31364. var isCallback = errorImpl instanceof Function;
  31365. locator = locator || {};
  31366. function build(key) {
  31367. var fn = errorImpl[key];
  31368. if (!fn && isCallback) {
  31369. fn = errorImpl.length == 2 ? function (msg) {
  31370. errorImpl(key, msg);
  31371. } : errorImpl;
  31372. }
  31373. errorHandler[key] = fn && function (msg) {
  31374. fn('[xmldom ' + key + ']\t' + msg + _locator(locator));
  31375. } || function () {};
  31376. }
  31377. build('warning');
  31378. build('error');
  31379. build('fatalError');
  31380. return errorHandler;
  31381. } //console.log('#\n\n\n\n\n\n\n####')
  31382. /**
  31383. * +ContentHandler+ErrorHandler
  31384. * +LexicalHandler+EntityResolver2
  31385. * -DeclHandler-DTDHandler
  31386. *
  31387. * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
  31388. * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
  31389. * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
  31390. */
  31391. function DOMHandler() {
  31392. this.cdata = false;
  31393. }
  31394. function position(locator, node) {
  31395. node.lineNumber = locator.lineNumber;
  31396. node.columnNumber = locator.columnNumber;
  31397. }
  31398. /**
  31399. * @see org.xml.sax.ContentHandler#startDocument
  31400. * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
  31401. */
  31402. DOMHandler.prototype = {
  31403. startDocument: function startDocument() {
  31404. this.doc = new DOMImplementation().createDocument(null, null, null);
  31405. if (this.locator) {
  31406. this.doc.documentURI = this.locator.systemId;
  31407. }
  31408. },
  31409. startElement: function startElement(namespaceURI, localName, qName, attrs) {
  31410. var doc = this.doc;
  31411. var el = doc.createElementNS(namespaceURI, qName || localName);
  31412. var len = attrs.length;
  31413. appendElement(this, el);
  31414. this.currentElement = el;
  31415. this.locator && position(this.locator, el);
  31416. for (var i = 0; i < len; i++) {
  31417. var namespaceURI = attrs.getURI(i);
  31418. var value = attrs.getValue(i);
  31419. var qName = attrs.getQName(i);
  31420. var attr = doc.createAttributeNS(namespaceURI, qName);
  31421. this.locator && position(attrs.getLocator(i), attr);
  31422. attr.value = attr.nodeValue = value;
  31423. el.setAttributeNode(attr);
  31424. }
  31425. },
  31426. endElement: function endElement(namespaceURI, localName, qName) {
  31427. var current = this.currentElement;
  31428. current.tagName;
  31429. this.currentElement = current.parentNode;
  31430. },
  31431. startPrefixMapping: function startPrefixMapping(prefix, uri) {},
  31432. endPrefixMapping: function endPrefixMapping(prefix) {},
  31433. processingInstruction: function processingInstruction(target, data) {
  31434. var ins = this.doc.createProcessingInstruction(target, data);
  31435. this.locator && position(this.locator, ins);
  31436. appendElement(this, ins);
  31437. },
  31438. ignorableWhitespace: function ignorableWhitespace(ch, start, length) {},
  31439. characters: function characters(chars, start, length) {
  31440. chars = _toString.apply(this, arguments); //console.log(chars)
  31441. if (chars) {
  31442. if (this.cdata) {
  31443. var charNode = this.doc.createCDATASection(chars);
  31444. } else {
  31445. var charNode = this.doc.createTextNode(chars);
  31446. }
  31447. if (this.currentElement) {
  31448. this.currentElement.appendChild(charNode);
  31449. } else if (/^\s*$/.test(chars)) {
  31450. this.doc.appendChild(charNode); //process xml
  31451. }
  31452. this.locator && position(this.locator, charNode);
  31453. }
  31454. },
  31455. skippedEntity: function skippedEntity(name) {},
  31456. endDocument: function endDocument() {
  31457. this.doc.normalize();
  31458. },
  31459. setDocumentLocator: function setDocumentLocator(locator) {
  31460. if (this.locator = locator) {
  31461. // && !('lineNumber' in locator)){
  31462. locator.lineNumber = 0;
  31463. }
  31464. },
  31465. //LexicalHandler
  31466. comment: function comment(chars, start, length) {
  31467. chars = _toString.apply(this, arguments);
  31468. var comm = this.doc.createComment(chars);
  31469. this.locator && position(this.locator, comm);
  31470. appendElement(this, comm);
  31471. },
  31472. startCDATA: function startCDATA() {
  31473. //used in characters() methods
  31474. this.cdata = true;
  31475. },
  31476. endCDATA: function endCDATA() {
  31477. this.cdata = false;
  31478. },
  31479. startDTD: function startDTD(name, publicId, systemId) {
  31480. var impl = this.doc.implementation;
  31481. if (impl && impl.createDocumentType) {
  31482. var dt = impl.createDocumentType(name, publicId, systemId);
  31483. this.locator && position(this.locator, dt);
  31484. appendElement(this, dt);
  31485. this.doc.doctype = dt;
  31486. }
  31487. },
  31488. /**
  31489. * @see org.xml.sax.ErrorHandler
  31490. * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
  31491. */
  31492. warning: function warning(error) {
  31493. console.warn('[xmldom warning]\t' + error, _locator(this.locator));
  31494. },
  31495. error: function error(_error) {
  31496. console.error('[xmldom error]\t' + _error, _locator(this.locator));
  31497. },
  31498. fatalError: function fatalError(error) {
  31499. throw new ParseError(error, this.locator);
  31500. }
  31501. };
  31502. function _locator(l) {
  31503. if (l) {
  31504. return '\n@' + (l.systemId || '') + '#[line:' + l.lineNumber + ',col:' + l.columnNumber + ']';
  31505. }
  31506. }
  31507. function _toString(chars, start, length) {
  31508. if (typeof chars == 'string') {
  31509. return chars.substr(start, length);
  31510. } else {
  31511. //java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
  31512. if (chars.length >= start + length || start) {
  31513. return new java.lang.String(chars, start, length) + '';
  31514. }
  31515. return chars;
  31516. }
  31517. }
  31518. /*
  31519. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
  31520. * used method of org.xml.sax.ext.LexicalHandler:
  31521. * #comment(chars, start, length)
  31522. * #startCDATA()
  31523. * #endCDATA()
  31524. * #startDTD(name, publicId, systemId)
  31525. *
  31526. *
  31527. * IGNORED method of org.xml.sax.ext.LexicalHandler:
  31528. * #endDTD()
  31529. * #startEntity(name)
  31530. * #endEntity(name)
  31531. *
  31532. *
  31533. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
  31534. * IGNORED method of org.xml.sax.ext.DeclHandler
  31535. * #attributeDecl(eName, aName, type, mode, value)
  31536. * #elementDecl(name, model)
  31537. * #externalEntityDecl(name, publicId, systemId)
  31538. * #internalEntityDecl(name, value)
  31539. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
  31540. * IGNORED method of org.xml.sax.EntityResolver2
  31541. * #resolveEntity(String name,String publicId,String baseURI,String systemId)
  31542. * #resolveEntity(publicId, systemId)
  31543. * #getExternalSubset(name, baseURI)
  31544. * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
  31545. * IGNORED method of org.xml.sax.DTDHandler
  31546. * #notationDecl(name, publicId, systemId) {};
  31547. * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
  31548. */
  31549. "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g, function (key) {
  31550. DOMHandler.prototype[key] = function () {
  31551. return null;
  31552. };
  31553. });
  31554. /* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */
  31555. function appendElement(hander, node) {
  31556. if (!hander.currentElement) {
  31557. hander.doc.appendChild(node);
  31558. } else {
  31559. hander.currentElement.appendChild(node);
  31560. }
  31561. } //appendChild and setAttributeNS are preformance key
  31562. var __DOMHandler = DOMHandler;
  31563. var normalizeLineEndings_1 = normalizeLineEndings;
  31564. var DOMParser_1 = DOMParser$1;
  31565. var domParser = {
  31566. __DOMHandler: __DOMHandler,
  31567. normalizeLineEndings: normalizeLineEndings_1,
  31568. DOMParser: DOMParser_1
  31569. };
  31570. var DOMParser = domParser.DOMParser;
  31571. /*! @name mpd-parser @version 0.22.1 @license Apache-2.0 */
  31572. var isObject = function isObject(obj) {
  31573. return !!obj && typeof obj === 'object';
  31574. };
  31575. var merge = function merge() {
  31576. for (var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++) {
  31577. objects[_key] = arguments[_key];
  31578. }
  31579. return objects.reduce(function (result, source) {
  31580. if (typeof source !== 'object') {
  31581. return result;
  31582. }
  31583. Object.keys(source).forEach(function (key) {
  31584. if (Array.isArray(result[key]) && Array.isArray(source[key])) {
  31585. result[key] = result[key].concat(source[key]);
  31586. } else if (isObject(result[key]) && isObject(source[key])) {
  31587. result[key] = merge(result[key], source[key]);
  31588. } else {
  31589. result[key] = source[key];
  31590. }
  31591. });
  31592. return result;
  31593. }, {});
  31594. };
  31595. var values = function values(o) {
  31596. return Object.keys(o).map(function (k) {
  31597. return o[k];
  31598. });
  31599. };
  31600. var range = function range(start, end) {
  31601. var result = [];
  31602. for (var i = start; i < end; i++) {
  31603. result.push(i);
  31604. }
  31605. return result;
  31606. };
  31607. var flatten = function flatten(lists) {
  31608. return lists.reduce(function (x, y) {
  31609. return x.concat(y);
  31610. }, []);
  31611. };
  31612. var from = function from(list) {
  31613. if (!list.length) {
  31614. return [];
  31615. }
  31616. var result = [];
  31617. for (var i = 0; i < list.length; i++) {
  31618. result.push(list[i]);
  31619. }
  31620. return result;
  31621. };
  31622. var findIndexes = function findIndexes(l, key) {
  31623. return l.reduce(function (a, e, i) {
  31624. if (e[key]) {
  31625. a.push(i);
  31626. }
  31627. return a;
  31628. }, []);
  31629. };
  31630. /**
  31631. * Returns the first index that satisfies the matching function, or -1 if not found.
  31632. *
  31633. * Only necessary because of IE11 support.
  31634. *
  31635. * @param {Array} list - the list to search through
  31636. * @param {Function} matchingFunction - the matching function
  31637. *
  31638. * @return {number} the matching index or -1 if not found
  31639. */
  31640. var findIndex = function findIndex(list, matchingFunction) {
  31641. for (var i = 0; i < list.length; i++) {
  31642. if (matchingFunction(list[i])) {
  31643. return i;
  31644. }
  31645. }
  31646. return -1;
  31647. };
  31648. /**
  31649. * Returns a union of the included lists provided each element can be identified by a key.
  31650. *
  31651. * @param {Array} list - list of lists to get the union of
  31652. * @param {Function} keyFunction - the function to use as a key for each element
  31653. *
  31654. * @return {Array} the union of the arrays
  31655. */
  31656. var union = function union(lists, keyFunction) {
  31657. return values(lists.reduce(function (acc, list) {
  31658. list.forEach(function (el) {
  31659. acc[keyFunction(el)] = el;
  31660. });
  31661. return acc;
  31662. }, {}));
  31663. };
  31664. var errors = {
  31665. INVALID_NUMBER_OF_PERIOD: 'INVALID_NUMBER_OF_PERIOD',
  31666. DASH_EMPTY_MANIFEST: 'DASH_EMPTY_MANIFEST',
  31667. DASH_INVALID_XML: 'DASH_INVALID_XML',
  31668. NO_BASE_URL: 'NO_BASE_URL',
  31669. MISSING_SEGMENT_INFORMATION: 'MISSING_SEGMENT_INFORMATION',
  31670. SEGMENT_TIME_UNSPECIFIED: 'SEGMENT_TIME_UNSPECIFIED',
  31671. UNSUPPORTED_UTC_TIMING_SCHEME: 'UNSUPPORTED_UTC_TIMING_SCHEME'
  31672. };
  31673. /**
  31674. * @typedef {Object} SingleUri
  31675. * @property {string} uri - relative location of segment
  31676. * @property {string} resolvedUri - resolved location of segment
  31677. * @property {Object} byterange - Object containing information on how to make byte range
  31678. * requests following byte-range-spec per RFC2616.
  31679. * @property {String} byterange.length - length of range request
  31680. * @property {String} byterange.offset - byte offset of range request
  31681. *
  31682. * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.1
  31683. */
  31684. /**
  31685. * Converts a URLType node (5.3.9.2.3 Table 13) to a segment object
  31686. * that conforms to how m3u8-parser is structured
  31687. *
  31688. * @see https://github.com/videojs/m3u8-parser
  31689. *
  31690. * @param {string} baseUrl - baseUrl provided by <BaseUrl> nodes
  31691. * @param {string} source - source url for segment
  31692. * @param {string} range - optional range used for range calls,
  31693. * follows RFC 2616, Clause 14.35.1
  31694. * @return {SingleUri} full segment information transformed into a format similar
  31695. * to m3u8-parser
  31696. */
  31697. var urlTypeToSegment = function urlTypeToSegment(_ref) {
  31698. var _ref$baseUrl = _ref.baseUrl,
  31699. baseUrl = _ref$baseUrl === void 0 ? '' : _ref$baseUrl,
  31700. _ref$source = _ref.source,
  31701. source = _ref$source === void 0 ? '' : _ref$source,
  31702. _ref$range = _ref.range,
  31703. range = _ref$range === void 0 ? '' : _ref$range,
  31704. _ref$indexRange = _ref.indexRange,
  31705. indexRange = _ref$indexRange === void 0 ? '' : _ref$indexRange;
  31706. var segment = {
  31707. uri: source,
  31708. resolvedUri: resolveUrl$1(baseUrl || '', source)
  31709. };
  31710. if (range || indexRange) {
  31711. var rangeStr = range ? range : indexRange;
  31712. var ranges = rangeStr.split('-'); // default to parsing this as a BigInt if possible
  31713. var startRange = window.BigInt ? window.BigInt(ranges[0]) : parseInt(ranges[0], 10);
  31714. var endRange = window.BigInt ? window.BigInt(ranges[1]) : parseInt(ranges[1], 10); // convert back to a number if less than MAX_SAFE_INTEGER
  31715. if (startRange < Number.MAX_SAFE_INTEGER && typeof startRange === 'bigint') {
  31716. startRange = Number(startRange);
  31717. }
  31718. if (endRange < Number.MAX_SAFE_INTEGER && typeof endRange === 'bigint') {
  31719. endRange = Number(endRange);
  31720. }
  31721. var length;
  31722. if (typeof endRange === 'bigint' || typeof startRange === 'bigint') {
  31723. length = window.BigInt(endRange) - window.BigInt(startRange) + window.BigInt(1);
  31724. } else {
  31725. length = endRange - startRange + 1;
  31726. }
  31727. if (typeof length === 'bigint' && length < Number.MAX_SAFE_INTEGER) {
  31728. length = Number(length);
  31729. } // byterange should be inclusive according to
  31730. // RFC 2616, Clause 14.35.1
  31731. segment.byterange = {
  31732. length: length,
  31733. offset: startRange
  31734. };
  31735. }
  31736. return segment;
  31737. };
  31738. var byteRangeToString = function byteRangeToString(byterange) {
  31739. // `endRange` is one less than `offset + length` because the HTTP range
  31740. // header uses inclusive ranges
  31741. var endRange;
  31742. if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {
  31743. endRange = window.BigInt(byterange.offset) + window.BigInt(byterange.length) - window.BigInt(1);
  31744. } else {
  31745. endRange = byterange.offset + byterange.length - 1;
  31746. }
  31747. return byterange.offset + "-" + endRange;
  31748. };
  31749. /**
  31750. * parse the end number attribue that can be a string
  31751. * number, or undefined.
  31752. *
  31753. * @param {string|number|undefined} endNumber
  31754. * The end number attribute.
  31755. *
  31756. * @return {number|null}
  31757. * The result of parsing the end number.
  31758. */
  31759. var parseEndNumber = function parseEndNumber(endNumber) {
  31760. if (endNumber && typeof endNumber !== 'number') {
  31761. endNumber = parseInt(endNumber, 10);
  31762. }
  31763. if (isNaN(endNumber)) {
  31764. return null;
  31765. }
  31766. return endNumber;
  31767. };
  31768. /**
  31769. * Functions for calculating the range of available segments in static and dynamic
  31770. * manifests.
  31771. */
  31772. var segmentRange = {
  31773. /**
  31774. * Returns the entire range of available segments for a static MPD
  31775. *
  31776. * @param {Object} attributes
  31777. * Inheritied MPD attributes
  31778. * @return {{ start: number, end: number }}
  31779. * The start and end numbers for available segments
  31780. */
  31781. "static": function _static(attributes) {
  31782. var duration = attributes.duration,
  31783. _attributes$timescale = attributes.timescale,
  31784. timescale = _attributes$timescale === void 0 ? 1 : _attributes$timescale,
  31785. sourceDuration = attributes.sourceDuration,
  31786. periodDuration = attributes.periodDuration;
  31787. var endNumber = parseEndNumber(attributes.endNumber);
  31788. var segmentDuration = duration / timescale;
  31789. if (typeof endNumber === 'number') {
  31790. return {
  31791. start: 0,
  31792. end: endNumber
  31793. };
  31794. }
  31795. if (typeof periodDuration === 'number') {
  31796. return {
  31797. start: 0,
  31798. end: periodDuration / segmentDuration
  31799. };
  31800. }
  31801. return {
  31802. start: 0,
  31803. end: sourceDuration / segmentDuration
  31804. };
  31805. },
  31806. /**
  31807. * Returns the current live window range of available segments for a dynamic MPD
  31808. *
  31809. * @param {Object} attributes
  31810. * Inheritied MPD attributes
  31811. * @return {{ start: number, end: number }}
  31812. * The start and end numbers for available segments
  31813. */
  31814. dynamic: function dynamic(attributes) {
  31815. var NOW = attributes.NOW,
  31816. clientOffset = attributes.clientOffset,
  31817. availabilityStartTime = attributes.availabilityStartTime,
  31818. _attributes$timescale2 = attributes.timescale,
  31819. timescale = _attributes$timescale2 === void 0 ? 1 : _attributes$timescale2,
  31820. duration = attributes.duration,
  31821. _attributes$periodSta = attributes.periodStart,
  31822. periodStart = _attributes$periodSta === void 0 ? 0 : _attributes$periodSta,
  31823. _attributes$minimumUp = attributes.minimumUpdatePeriod,
  31824. minimumUpdatePeriod = _attributes$minimumUp === void 0 ? 0 : _attributes$minimumUp,
  31825. _attributes$timeShift = attributes.timeShiftBufferDepth,
  31826. timeShiftBufferDepth = _attributes$timeShift === void 0 ? Infinity : _attributes$timeShift;
  31827. var endNumber = parseEndNumber(attributes.endNumber); // clientOffset is passed in at the top level of mpd-parser and is an offset calculated
  31828. // after retrieving UTC server time.
  31829. var now = (NOW + clientOffset) / 1000; // WC stands for Wall Clock.
  31830. // Convert the period start time to EPOCH.
  31831. var periodStartWC = availabilityStartTime + periodStart; // Period end in EPOCH is manifest's retrieval time + time until next update.
  31832. var periodEndWC = now + minimumUpdatePeriod;
  31833. var periodDuration = periodEndWC - periodStartWC;
  31834. var segmentCount = Math.ceil(periodDuration * timescale / duration);
  31835. var availableStart = Math.floor((now - periodStartWC - timeShiftBufferDepth) * timescale / duration);
  31836. var availableEnd = Math.floor((now - periodStartWC) * timescale / duration);
  31837. return {
  31838. start: Math.max(0, availableStart),
  31839. end: typeof endNumber === 'number' ? endNumber : Math.min(segmentCount, availableEnd)
  31840. };
  31841. }
  31842. };
  31843. /**
  31844. * Maps a range of numbers to objects with information needed to build the corresponding
  31845. * segment list
  31846. *
  31847. * @name toSegmentsCallback
  31848. * @function
  31849. * @param {number} number
  31850. * Number of the segment
  31851. * @param {number} index
  31852. * Index of the number in the range list
  31853. * @return {{ number: Number, duration: Number, timeline: Number, time: Number }}
  31854. * Object with segment timing and duration info
  31855. */
  31856. /**
  31857. * Returns a callback for Array.prototype.map for mapping a range of numbers to
  31858. * information needed to build the segment list.
  31859. *
  31860. * @param {Object} attributes
  31861. * Inherited MPD attributes
  31862. * @return {toSegmentsCallback}
  31863. * Callback map function
  31864. */
  31865. var toSegments = function toSegments(attributes) {
  31866. return function (number) {
  31867. var duration = attributes.duration,
  31868. _attributes$timescale3 = attributes.timescale,
  31869. timescale = _attributes$timescale3 === void 0 ? 1 : _attributes$timescale3,
  31870. periodStart = attributes.periodStart,
  31871. _attributes$startNumb = attributes.startNumber,
  31872. startNumber = _attributes$startNumb === void 0 ? 1 : _attributes$startNumb;
  31873. return {
  31874. number: startNumber + number,
  31875. duration: duration / timescale,
  31876. timeline: periodStart,
  31877. time: number * duration
  31878. };
  31879. };
  31880. };
  31881. /**
  31882. * Returns a list of objects containing segment timing and duration info used for
  31883. * building the list of segments. This uses the @duration attribute specified
  31884. * in the MPD manifest to derive the range of segments.
  31885. *
  31886. * @param {Object} attributes
  31887. * Inherited MPD attributes
  31888. * @return {{number: number, duration: number, time: number, timeline: number}[]}
  31889. * List of Objects with segment timing and duration info
  31890. */
  31891. var parseByDuration = function parseByDuration(attributes) {
  31892. var type = attributes.type,
  31893. duration = attributes.duration,
  31894. _attributes$timescale4 = attributes.timescale,
  31895. timescale = _attributes$timescale4 === void 0 ? 1 : _attributes$timescale4,
  31896. periodDuration = attributes.periodDuration,
  31897. sourceDuration = attributes.sourceDuration;
  31898. var _segmentRange$type = segmentRange[type](attributes),
  31899. start = _segmentRange$type.start,
  31900. end = _segmentRange$type.end;
  31901. var segments = range(start, end).map(toSegments(attributes));
  31902. if (type === 'static') {
  31903. var index = segments.length - 1; // section is either a period or the full source
  31904. var sectionDuration = typeof periodDuration === 'number' ? periodDuration : sourceDuration; // final segment may be less than full segment duration
  31905. segments[index].duration = sectionDuration - duration / timescale * index;
  31906. }
  31907. return segments;
  31908. };
  31909. /**
  31910. * Translates SegmentBase into a set of segments.
  31911. * (DASH SPEC Section 5.3.9.3.2) contains a set of <SegmentURL> nodes. Each
  31912. * node should be translated into segment.
  31913. *
  31914. * @param {Object} attributes
  31915. * Object containing all inherited attributes from parent elements with attribute
  31916. * names as keys
  31917. * @return {Object.<Array>} list of segments
  31918. */
  31919. var segmentsFromBase = function segmentsFromBase(attributes) {
  31920. var baseUrl = attributes.baseUrl,
  31921. _attributes$initializ = attributes.initialization,
  31922. initialization = _attributes$initializ === void 0 ? {} : _attributes$initializ,
  31923. sourceDuration = attributes.sourceDuration,
  31924. _attributes$indexRang = attributes.indexRange,
  31925. indexRange = _attributes$indexRang === void 0 ? '' : _attributes$indexRang,
  31926. periodStart = attributes.periodStart,
  31927. presentationTime = attributes.presentationTime,
  31928. _attributes$number = attributes.number,
  31929. number = _attributes$number === void 0 ? 0 : _attributes$number,
  31930. duration = attributes.duration; // base url is required for SegmentBase to work, per spec (Section 5.3.9.2.1)
  31931. if (!baseUrl) {
  31932. throw new Error(errors.NO_BASE_URL);
  31933. }
  31934. var initSegment = urlTypeToSegment({
  31935. baseUrl: baseUrl,
  31936. source: initialization.sourceURL,
  31937. range: initialization.range
  31938. });
  31939. var segment = urlTypeToSegment({
  31940. baseUrl: baseUrl,
  31941. source: baseUrl,
  31942. indexRange: indexRange
  31943. });
  31944. segment.map = initSegment; // If there is a duration, use it, otherwise use the given duration of the source
  31945. // (since SegmentBase is only for one total segment)
  31946. if (duration) {
  31947. var segmentTimeInfo = parseByDuration(attributes);
  31948. if (segmentTimeInfo.length) {
  31949. segment.duration = segmentTimeInfo[0].duration;
  31950. segment.timeline = segmentTimeInfo[0].timeline;
  31951. }
  31952. } else if (sourceDuration) {
  31953. segment.duration = sourceDuration;
  31954. segment.timeline = periodStart;
  31955. } // If presentation time is provided, these segments are being generated by SIDX
  31956. // references, and should use the time provided. For the general case of SegmentBase,
  31957. // there should only be one segment in the period, so its presentation time is the same
  31958. // as its period start.
  31959. segment.presentationTime = presentationTime || periodStart;
  31960. segment.number = number;
  31961. return [segment];
  31962. };
  31963. /**
  31964. * Given a playlist, a sidx box, and a baseUrl, update the segment list of the playlist
  31965. * according to the sidx information given.
  31966. *
  31967. * playlist.sidx has metadadata about the sidx where-as the sidx param
  31968. * is the parsed sidx box itself.
  31969. *
  31970. * @param {Object} playlist the playlist to update the sidx information for
  31971. * @param {Object} sidx the parsed sidx box
  31972. * @return {Object} the playlist object with the updated sidx information
  31973. */
  31974. var addSidxSegmentsToPlaylist$1 = function addSidxSegmentsToPlaylist(playlist, sidx, baseUrl) {
  31975. // Retain init segment information
  31976. var initSegment = playlist.sidx.map ? playlist.sidx.map : null; // Retain source duration from initial main manifest parsing
  31977. var sourceDuration = playlist.sidx.duration; // Retain source timeline
  31978. var timeline = playlist.timeline || 0;
  31979. var sidxByteRange = playlist.sidx.byterange;
  31980. var sidxEnd = sidxByteRange.offset + sidxByteRange.length; // Retain timescale of the parsed sidx
  31981. var timescale = sidx.timescale; // referenceType 1 refers to other sidx boxes
  31982. var mediaReferences = sidx.references.filter(function (r) {
  31983. return r.referenceType !== 1;
  31984. });
  31985. var segments = [];
  31986. var type = playlist.endList ? 'static' : 'dynamic';
  31987. var periodStart = playlist.sidx.timeline;
  31988. var presentationTime = periodStart;
  31989. var number = playlist.mediaSequence || 0; // firstOffset is the offset from the end of the sidx box
  31990. var startIndex; // eslint-disable-next-line
  31991. if (typeof sidx.firstOffset === 'bigint') {
  31992. startIndex = window.BigInt(sidxEnd) + sidx.firstOffset;
  31993. } else {
  31994. startIndex = sidxEnd + sidx.firstOffset;
  31995. }
  31996. for (var i = 0; i < mediaReferences.length; i++) {
  31997. var reference = sidx.references[i]; // size of the referenced (sub)segment
  31998. var size = reference.referencedSize; // duration of the referenced (sub)segment, in the timescale
  31999. // this will be converted to seconds when generating segments
  32000. var duration = reference.subsegmentDuration; // should be an inclusive range
  32001. var endIndex = void 0; // eslint-disable-next-line
  32002. if (typeof startIndex === 'bigint') {
  32003. endIndex = startIndex + window.BigInt(size) - window.BigInt(1);
  32004. } else {
  32005. endIndex = startIndex + size - 1;
  32006. }
  32007. var indexRange = startIndex + "-" + endIndex;
  32008. var attributes = {
  32009. baseUrl: baseUrl,
  32010. timescale: timescale,
  32011. timeline: timeline,
  32012. periodStart: periodStart,
  32013. presentationTime: presentationTime,
  32014. number: number,
  32015. duration: duration,
  32016. sourceDuration: sourceDuration,
  32017. indexRange: indexRange,
  32018. type: type
  32019. };
  32020. var segment = segmentsFromBase(attributes)[0];
  32021. if (initSegment) {
  32022. segment.map = initSegment;
  32023. }
  32024. segments.push(segment);
  32025. if (typeof startIndex === 'bigint') {
  32026. startIndex += window.BigInt(size);
  32027. } else {
  32028. startIndex += size;
  32029. }
  32030. presentationTime += duration / timescale;
  32031. number++;
  32032. }
  32033. playlist.segments = segments;
  32034. return playlist;
  32035. };
  32036. var SUPPORTED_MEDIA_TYPES = ['AUDIO', 'SUBTITLES']; // allow one 60fps frame as leniency (arbitrarily chosen)
  32037. var TIME_FUDGE = 1 / 60;
  32038. /**
  32039. * Given a list of timelineStarts, combines, dedupes, and sorts them.
  32040. *
  32041. * @param {TimelineStart[]} timelineStarts - list of timeline starts
  32042. *
  32043. * @return {TimelineStart[]} the combined and deduped timeline starts
  32044. */
  32045. var getUniqueTimelineStarts = function getUniqueTimelineStarts(timelineStarts) {
  32046. return union(timelineStarts, function (_ref) {
  32047. var timeline = _ref.timeline;
  32048. return timeline;
  32049. }).sort(function (a, b) {
  32050. return a.timeline > b.timeline ? 1 : -1;
  32051. });
  32052. };
  32053. /**
  32054. * Finds the playlist with the matching NAME attribute.
  32055. *
  32056. * @param {Array} playlists - playlists to search through
  32057. * @param {string} name - the NAME attribute to search for
  32058. *
  32059. * @return {Object|null} the matching playlist object, or null
  32060. */
  32061. var findPlaylistWithName = function findPlaylistWithName(playlists, name) {
  32062. for (var i = 0; i < playlists.length; i++) {
  32063. if (playlists[i].attributes.NAME === name) {
  32064. return playlists[i];
  32065. }
  32066. }
  32067. return null;
  32068. };
  32069. /**
  32070. * Gets a flattened array of media group playlists.
  32071. *
  32072. * @param {Object} manifest - the main manifest object
  32073. *
  32074. * @return {Array} the media group playlists
  32075. */
  32076. var getMediaGroupPlaylists = function getMediaGroupPlaylists(manifest) {
  32077. var mediaGroupPlaylists = [];
  32078. forEachMediaGroup$1(manifest, SUPPORTED_MEDIA_TYPES, function (properties, type, group, label) {
  32079. mediaGroupPlaylists = mediaGroupPlaylists.concat(properties.playlists || []);
  32080. });
  32081. return mediaGroupPlaylists;
  32082. };
  32083. /**
  32084. * Updates the playlist's media sequence numbers.
  32085. *
  32086. * @param {Object} config - options object
  32087. * @param {Object} config.playlist - the playlist to update
  32088. * @param {number} config.mediaSequence - the mediaSequence number to start with
  32089. */
  32090. var updateMediaSequenceForPlaylist = function updateMediaSequenceForPlaylist(_ref2) {
  32091. var playlist = _ref2.playlist,
  32092. mediaSequence = _ref2.mediaSequence;
  32093. playlist.mediaSequence = mediaSequence;
  32094. playlist.segments.forEach(function (segment, index) {
  32095. segment.number = playlist.mediaSequence + index;
  32096. });
  32097. };
  32098. /**
  32099. * Updates the media and discontinuity sequence numbers of newPlaylists given oldPlaylists
  32100. * and a complete list of timeline starts.
  32101. *
  32102. * If no matching playlist is found, only the discontinuity sequence number of the playlist
  32103. * will be updated.
  32104. *
  32105. * Since early available timelines are not supported, at least one segment must be present.
  32106. *
  32107. * @param {Object} config - options object
  32108. * @param {Object[]} oldPlaylists - the old playlists to use as a reference
  32109. * @param {Object[]} newPlaylists - the new playlists to update
  32110. * @param {Object} timelineStarts - all timelineStarts seen in the stream to this point
  32111. */
  32112. var updateSequenceNumbers = function updateSequenceNumbers(_ref3) {
  32113. var oldPlaylists = _ref3.oldPlaylists,
  32114. newPlaylists = _ref3.newPlaylists,
  32115. timelineStarts = _ref3.timelineStarts;
  32116. newPlaylists.forEach(function (playlist) {
  32117. playlist.discontinuitySequence = findIndex(timelineStarts, function (_ref4) {
  32118. var timeline = _ref4.timeline;
  32119. return timeline === playlist.timeline;
  32120. }); // Playlists NAMEs come from DASH Representation IDs, which are mandatory
  32121. // (see ISO_23009-1-2012 5.3.5.2).
  32122. //
  32123. // If the same Representation existed in a prior Period, it will retain the same NAME.
  32124. var oldPlaylist = findPlaylistWithName(oldPlaylists, playlist.attributes.NAME);
  32125. if (!oldPlaylist) {
  32126. // Since this is a new playlist, the media sequence values can start from 0 without
  32127. // consequence.
  32128. return;
  32129. } // TODO better support for live SIDX
  32130. //
  32131. // As of this writing, mpd-parser does not support multiperiod SIDX (in live or VOD).
  32132. // This is evident by a playlist only having a single SIDX reference. In a multiperiod
  32133. // playlist there would need to be multiple SIDX references. In addition, live SIDX is
  32134. // not supported when the SIDX properties change on refreshes.
  32135. //
  32136. // In the future, if support needs to be added, the merging logic here can be called
  32137. // after SIDX references are resolved. For now, exit early to prevent exceptions being
  32138. // thrown due to undefined references.
  32139. if (playlist.sidx) {
  32140. return;
  32141. } // Since we don't yet support early available timelines, we don't need to support
  32142. // playlists with no segments.
  32143. var firstNewSegment = playlist.segments[0];
  32144. var oldMatchingSegmentIndex = findIndex(oldPlaylist.segments, function (oldSegment) {
  32145. return Math.abs(oldSegment.presentationTime - firstNewSegment.presentationTime) < TIME_FUDGE;
  32146. }); // No matching segment from the old playlist means the entire playlist was refreshed.
  32147. // In this case the media sequence should account for this update, and the new segments
  32148. // should be marked as discontinuous from the prior content, since the last prior
  32149. // timeline was removed.
  32150. if (oldMatchingSegmentIndex === -1) {
  32151. updateMediaSequenceForPlaylist({
  32152. playlist: playlist,
  32153. mediaSequence: oldPlaylist.mediaSequence + oldPlaylist.segments.length
  32154. });
  32155. playlist.segments[0].discontinuity = true;
  32156. playlist.discontinuityStarts.unshift(0); // No matching segment does not necessarily mean there's missing content.
  32157. //
  32158. // If the new playlist's timeline is the same as the last seen segment's timeline,
  32159. // then a discontinuity can be added to identify that there's potentially missing
  32160. // content. If there's no missing content, the discontinuity should still be rather
  32161. // harmless. It's possible that if segment durations are accurate enough, that the
  32162. // existence of a gap can be determined using the presentation times and durations,
  32163. // but if the segment timing info is off, it may introduce more problems than simply
  32164. // adding the discontinuity.
  32165. //
  32166. // If the new playlist's timeline is different from the last seen segment's timeline,
  32167. // then a discontinuity can be added to identify that this is the first seen segment
  32168. // of a new timeline. However, the logic at the start of this function that
  32169. // determined the disconinuity sequence by timeline index is now off by one (the
  32170. // discontinuity of the newest timeline hasn't yet fallen off the manifest...since
  32171. // we added it), so the disconinuity sequence must be decremented.
  32172. //
  32173. // A period may also have a duration of zero, so the case of no segments is handled
  32174. // here even though we don't yet support early available periods.
  32175. if (!oldPlaylist.segments.length && playlist.timeline > oldPlaylist.timeline || oldPlaylist.segments.length && playlist.timeline > oldPlaylist.segments[oldPlaylist.segments.length - 1].timeline) {
  32176. playlist.discontinuitySequence--;
  32177. }
  32178. return;
  32179. } // If the first segment matched with a prior segment on a discontinuity (it's matching
  32180. // on the first segment of a period), then the discontinuitySequence shouldn't be the
  32181. // timeline's matching one, but instead should be the one prior, and the first segment
  32182. // of the new manifest should be marked with a discontinuity.
  32183. //
  32184. // The reason for this special case is that discontinuity sequence shows how many
  32185. // discontinuities have fallen off of the playlist, and discontinuities are marked on
  32186. // the first segment of a new "timeline." Because of this, while DASH will retain that
  32187. // Period while the "timeline" exists, HLS keeps track of it via the discontinuity
  32188. // sequence, and that first segment is an indicator, but can be removed before that
  32189. // timeline is gone.
  32190. var oldMatchingSegment = oldPlaylist.segments[oldMatchingSegmentIndex];
  32191. if (oldMatchingSegment.discontinuity && !firstNewSegment.discontinuity) {
  32192. firstNewSegment.discontinuity = true;
  32193. playlist.discontinuityStarts.unshift(0);
  32194. playlist.discontinuitySequence--;
  32195. }
  32196. updateMediaSequenceForPlaylist({
  32197. playlist: playlist,
  32198. mediaSequence: oldPlaylist.segments[oldMatchingSegmentIndex].number
  32199. });
  32200. });
  32201. };
  32202. /**
  32203. * Given an old parsed manifest object and a new parsed manifest object, updates the
  32204. * sequence and timing values within the new manifest to ensure that it lines up with the
  32205. * old.
  32206. *
  32207. * @param {Array} oldManifest - the old main manifest object
  32208. * @param {Array} newManifest - the new main manifest object
  32209. *
  32210. * @return {Object} the updated new manifest object
  32211. */
  32212. var positionManifestOnTimeline = function positionManifestOnTimeline(_ref5) {
  32213. var oldManifest = _ref5.oldManifest,
  32214. newManifest = _ref5.newManifest; // Starting from v4.1.2 of the IOP, section 4.4.3.3 states:
  32215. //
  32216. // "MPD@availabilityStartTime and Period@start shall not be changed over MPD updates."
  32217. //
  32218. // This was added from https://github.com/Dash-Industry-Forum/DASH-IF-IOP/issues/160
  32219. //
  32220. // Because of this change, and the difficulty of supporting periods with changing start
  32221. // times, periods with changing start times are not supported. This makes the logic much
  32222. // simpler, since periods with the same start time can be considerred the same period
  32223. // across refreshes.
  32224. //
  32225. // To give an example as to the difficulty of handling periods where the start time may
  32226. // change, if a single period manifest is refreshed with another manifest with a single
  32227. // period, and both the start and end times are increased, then the only way to determine
  32228. // if it's a new period or an old one that has changed is to look through the segments of
  32229. // each playlist and determine the presentation time bounds to find a match. In addition,
  32230. // if the period start changed to exceed the old period end, then there would be no
  32231. // match, and it would not be possible to determine whether the refreshed period is a new
  32232. // one or the old one.
  32233. var oldPlaylists = oldManifest.playlists.concat(getMediaGroupPlaylists(oldManifest));
  32234. var newPlaylists = newManifest.playlists.concat(getMediaGroupPlaylists(newManifest)); // Save all seen timelineStarts to the new manifest. Although this potentially means that
  32235. // there's a "memory leak" in that it will never stop growing, in reality, only a couple
  32236. // of properties are saved for each seen Period. Even long running live streams won't
  32237. // generate too many Periods, unless the stream is watched for decades. In the future,
  32238. // this can be optimized by mapping to discontinuity sequence numbers for each timeline,
  32239. // but it may not become an issue, and the additional info can be useful for debugging.
  32240. newManifest.timelineStarts = getUniqueTimelineStarts([oldManifest.timelineStarts, newManifest.timelineStarts]);
  32241. updateSequenceNumbers({
  32242. oldPlaylists: oldPlaylists,
  32243. newPlaylists: newPlaylists,
  32244. timelineStarts: newManifest.timelineStarts
  32245. });
  32246. return newManifest;
  32247. };
  32248. var generateSidxKey = function generateSidxKey(sidx) {
  32249. return sidx && sidx.uri + '-' + byteRangeToString(sidx.byterange);
  32250. };
  32251. var mergeDiscontiguousPlaylists = function mergeDiscontiguousPlaylists(playlists) {
  32252. var mergedPlaylists = values(playlists.reduce(function (acc, playlist) {
  32253. // assuming playlist IDs are the same across periods
  32254. // TODO: handle multiperiod where representation sets are not the same
  32255. // across periods
  32256. var name = playlist.attributes.id + (playlist.attributes.lang || '');
  32257. if (!acc[name]) {
  32258. // First Period
  32259. acc[name] = playlist;
  32260. acc[name].attributes.timelineStarts = [];
  32261. } else {
  32262. // Subsequent Periods
  32263. if (playlist.segments) {
  32264. var _acc$name$segments; // first segment of subsequent periods signal a discontinuity
  32265. if (playlist.segments[0]) {
  32266. playlist.segments[0].discontinuity = true;
  32267. }
  32268. (_acc$name$segments = acc[name].segments).push.apply(_acc$name$segments, playlist.segments);
  32269. } // bubble up contentProtection, this assumes all DRM content
  32270. // has the same contentProtection
  32271. if (playlist.attributes.contentProtection) {
  32272. acc[name].attributes.contentProtection = playlist.attributes.contentProtection;
  32273. }
  32274. }
  32275. acc[name].attributes.timelineStarts.push({
  32276. // Although they represent the same number, it's important to have both to make it
  32277. // compatible with HLS potentially having a similar attribute.
  32278. start: playlist.attributes.periodStart,
  32279. timeline: playlist.attributes.periodStart
  32280. });
  32281. return acc;
  32282. }, {}));
  32283. return mergedPlaylists.map(function (playlist) {
  32284. playlist.discontinuityStarts = findIndexes(playlist.segments || [], 'discontinuity');
  32285. return playlist;
  32286. });
  32287. };
  32288. var addSidxSegmentsToPlaylist = function addSidxSegmentsToPlaylist(playlist, sidxMapping) {
  32289. var sidxKey = generateSidxKey(playlist.sidx);
  32290. var sidxMatch = sidxKey && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx;
  32291. if (sidxMatch) {
  32292. addSidxSegmentsToPlaylist$1(playlist, sidxMatch, playlist.sidx.resolvedUri);
  32293. }
  32294. return playlist;
  32295. };
  32296. var addSidxSegmentsToPlaylists = function addSidxSegmentsToPlaylists(playlists, sidxMapping) {
  32297. if (sidxMapping === void 0) {
  32298. sidxMapping = {};
  32299. }
  32300. if (!Object.keys(sidxMapping).length) {
  32301. return playlists;
  32302. }
  32303. for (var i in playlists) {
  32304. playlists[i] = addSidxSegmentsToPlaylist(playlists[i], sidxMapping);
  32305. }
  32306. return playlists;
  32307. };
  32308. var formatAudioPlaylist = function formatAudioPlaylist(_ref, isAudioOnly) {
  32309. var _attributes;
  32310. var attributes = _ref.attributes,
  32311. segments = _ref.segments,
  32312. sidx = _ref.sidx,
  32313. mediaSequence = _ref.mediaSequence,
  32314. discontinuitySequence = _ref.discontinuitySequence,
  32315. discontinuityStarts = _ref.discontinuityStarts;
  32316. var playlist = {
  32317. attributes: (_attributes = {
  32318. NAME: attributes.id,
  32319. BANDWIDTH: attributes.bandwidth,
  32320. CODECS: attributes.codecs
  32321. }, _attributes['PROGRAM-ID'] = 1, _attributes),
  32322. uri: '',
  32323. endList: attributes.type === 'static',
  32324. timeline: attributes.periodStart,
  32325. resolvedUri: '',
  32326. targetDuration: attributes.duration,
  32327. discontinuitySequence: discontinuitySequence,
  32328. discontinuityStarts: discontinuityStarts,
  32329. timelineStarts: attributes.timelineStarts,
  32330. mediaSequence: mediaSequence,
  32331. segments: segments
  32332. };
  32333. if (attributes.contentProtection) {
  32334. playlist.contentProtection = attributes.contentProtection;
  32335. }
  32336. if (sidx) {
  32337. playlist.sidx = sidx;
  32338. }
  32339. if (isAudioOnly) {
  32340. playlist.attributes.AUDIO = 'audio';
  32341. playlist.attributes.SUBTITLES = 'subs';
  32342. }
  32343. return playlist;
  32344. };
  32345. var formatVttPlaylist = function formatVttPlaylist(_ref2) {
  32346. var _m3u8Attributes;
  32347. var attributes = _ref2.attributes,
  32348. segments = _ref2.segments,
  32349. mediaSequence = _ref2.mediaSequence,
  32350. discontinuityStarts = _ref2.discontinuityStarts,
  32351. discontinuitySequence = _ref2.discontinuitySequence;
  32352. if (typeof segments === 'undefined') {
  32353. // vtt tracks may use single file in BaseURL
  32354. segments = [{
  32355. uri: attributes.baseUrl,
  32356. timeline: attributes.periodStart,
  32357. resolvedUri: attributes.baseUrl || '',
  32358. duration: attributes.sourceDuration,
  32359. number: 0
  32360. }]; // targetDuration should be the same duration as the only segment
  32361. attributes.duration = attributes.sourceDuration;
  32362. }
  32363. var m3u8Attributes = (_m3u8Attributes = {
  32364. NAME: attributes.id,
  32365. BANDWIDTH: attributes.bandwidth
  32366. }, _m3u8Attributes['PROGRAM-ID'] = 1, _m3u8Attributes);
  32367. if (attributes.codecs) {
  32368. m3u8Attributes.CODECS = attributes.codecs;
  32369. }
  32370. return {
  32371. attributes: m3u8Attributes,
  32372. uri: '',
  32373. endList: attributes.type === 'static',
  32374. timeline: attributes.periodStart,
  32375. resolvedUri: attributes.baseUrl || '',
  32376. targetDuration: attributes.duration,
  32377. timelineStarts: attributes.timelineStarts,
  32378. discontinuityStarts: discontinuityStarts,
  32379. discontinuitySequence: discontinuitySequence,
  32380. mediaSequence: mediaSequence,
  32381. segments: segments
  32382. };
  32383. };
  32384. var organizeAudioPlaylists = function organizeAudioPlaylists(playlists, sidxMapping, isAudioOnly) {
  32385. if (sidxMapping === void 0) {
  32386. sidxMapping = {};
  32387. }
  32388. if (isAudioOnly === void 0) {
  32389. isAudioOnly = false;
  32390. }
  32391. var mainPlaylist;
  32392. var formattedPlaylists = playlists.reduce(function (a, playlist) {
  32393. var role = playlist.attributes.role && playlist.attributes.role.value || '';
  32394. var language = playlist.attributes.lang || '';
  32395. var label = playlist.attributes.label || 'main';
  32396. if (language && !playlist.attributes.label) {
  32397. var roleLabel = role ? " (" + role + ")" : '';
  32398. label = "" + playlist.attributes.lang + roleLabel;
  32399. }
  32400. if (!a[label]) {
  32401. a[label] = {
  32402. language: language,
  32403. autoselect: true,
  32404. "default": role === 'main',
  32405. playlists: [],
  32406. uri: ''
  32407. };
  32408. }
  32409. var formatted = addSidxSegmentsToPlaylist(formatAudioPlaylist(playlist, isAudioOnly), sidxMapping);
  32410. a[label].playlists.push(formatted);
  32411. if (typeof mainPlaylist === 'undefined' && role === 'main') {
  32412. mainPlaylist = playlist;
  32413. mainPlaylist["default"] = true;
  32414. }
  32415. return a;
  32416. }, {}); // if no playlists have role "main", mark the first as main
  32417. if (!mainPlaylist) {
  32418. var firstLabel = Object.keys(formattedPlaylists)[0];
  32419. formattedPlaylists[firstLabel]["default"] = true;
  32420. }
  32421. return formattedPlaylists;
  32422. };
  32423. var organizeVttPlaylists = function organizeVttPlaylists(playlists, sidxMapping) {
  32424. if (sidxMapping === void 0) {
  32425. sidxMapping = {};
  32426. }
  32427. return playlists.reduce(function (a, playlist) {
  32428. var label = playlist.attributes.lang || 'text';
  32429. if (!a[label]) {
  32430. a[label] = {
  32431. language: label,
  32432. "default": false,
  32433. autoselect: false,
  32434. playlists: [],
  32435. uri: ''
  32436. };
  32437. }
  32438. a[label].playlists.push(addSidxSegmentsToPlaylist(formatVttPlaylist(playlist), sidxMapping));
  32439. return a;
  32440. }, {});
  32441. };
  32442. var organizeCaptionServices = function organizeCaptionServices(captionServices) {
  32443. return captionServices.reduce(function (svcObj, svc) {
  32444. if (!svc) {
  32445. return svcObj;
  32446. }
  32447. svc.forEach(function (service) {
  32448. var channel = service.channel,
  32449. language = service.language;
  32450. svcObj[language] = {
  32451. autoselect: false,
  32452. "default": false,
  32453. instreamId: channel,
  32454. language: language
  32455. };
  32456. if (service.hasOwnProperty('aspectRatio')) {
  32457. svcObj[language].aspectRatio = service.aspectRatio;
  32458. }
  32459. if (service.hasOwnProperty('easyReader')) {
  32460. svcObj[language].easyReader = service.easyReader;
  32461. }
  32462. if (service.hasOwnProperty('3D')) {
  32463. svcObj[language]['3D'] = service['3D'];
  32464. }
  32465. });
  32466. return svcObj;
  32467. }, {});
  32468. };
  32469. var formatVideoPlaylist = function formatVideoPlaylist(_ref3) {
  32470. var _attributes2;
  32471. var attributes = _ref3.attributes,
  32472. segments = _ref3.segments,
  32473. sidx = _ref3.sidx,
  32474. discontinuityStarts = _ref3.discontinuityStarts;
  32475. var playlist = {
  32476. attributes: (_attributes2 = {
  32477. NAME: attributes.id,
  32478. AUDIO: 'audio',
  32479. SUBTITLES: 'subs',
  32480. RESOLUTION: {
  32481. width: attributes.width,
  32482. height: attributes.height
  32483. },
  32484. CODECS: attributes.codecs,
  32485. BANDWIDTH: attributes.bandwidth
  32486. }, _attributes2['PROGRAM-ID'] = 1, _attributes2),
  32487. uri: '',
  32488. endList: attributes.type === 'static',
  32489. timeline: attributes.periodStart,
  32490. resolvedUri: '',
  32491. targetDuration: attributes.duration,
  32492. discontinuityStarts: discontinuityStarts,
  32493. timelineStarts: attributes.timelineStarts,
  32494. segments: segments
  32495. };
  32496. if (attributes.frameRate) {
  32497. playlist.attributes['FRAME-RATE'] = attributes.frameRate;
  32498. }
  32499. if (attributes.contentProtection) {
  32500. playlist.contentProtection = attributes.contentProtection;
  32501. }
  32502. if (sidx) {
  32503. playlist.sidx = sidx;
  32504. }
  32505. return playlist;
  32506. };
  32507. var videoOnly = function videoOnly(_ref4) {
  32508. var attributes = _ref4.attributes;
  32509. return attributes.mimeType === 'video/mp4' || attributes.mimeType === 'video/webm' || attributes.contentType === 'video';
  32510. };
  32511. var audioOnly = function audioOnly(_ref5) {
  32512. var attributes = _ref5.attributes;
  32513. return attributes.mimeType === 'audio/mp4' || attributes.mimeType === 'audio/webm' || attributes.contentType === 'audio';
  32514. };
  32515. var vttOnly = function vttOnly(_ref6) {
  32516. var attributes = _ref6.attributes;
  32517. return attributes.mimeType === 'text/vtt' || attributes.contentType === 'text';
  32518. };
  32519. /**
  32520. * Contains start and timeline properties denoting a timeline start. For DASH, these will
  32521. * be the same number.
  32522. *
  32523. * @typedef {Object} TimelineStart
  32524. * @property {number} start - the start time of the timeline
  32525. * @property {number} timeline - the timeline number
  32526. */
  32527. /**
  32528. * Adds appropriate media and discontinuity sequence values to the segments and playlists.
  32529. *
  32530. * Throughout mpd-parser, the `number` attribute is used in relation to `startNumber`, a
  32531. * DASH specific attribute used in constructing segment URI's from templates. However, from
  32532. * an HLS perspective, the `number` attribute on a segment would be its `mediaSequence`
  32533. * value, which should start at the original media sequence value (or 0) and increment by 1
  32534. * for each segment thereafter. Since DASH's `startNumber` values are independent per
  32535. * period, it doesn't make sense to use it for `number`. Instead, assume everything starts
  32536. * from a 0 mediaSequence value and increment from there.
  32537. *
  32538. * Note that VHS currently doesn't use the `number` property, but it can be helpful for
  32539. * debugging and making sense of the manifest.
  32540. *
  32541. * For live playlists, to account for values increasing in manifests when periods are
  32542. * removed on refreshes, merging logic should be used to update the numbers to their
  32543. * appropriate values (to ensure they're sequential and increasing).
  32544. *
  32545. * @param {Object[]} playlists - the playlists to update
  32546. * @param {TimelineStart[]} timelineStarts - the timeline starts for the manifest
  32547. */
  32548. var addMediaSequenceValues = function addMediaSequenceValues(playlists, timelineStarts) {
  32549. // increment all segments sequentially
  32550. playlists.forEach(function (playlist) {
  32551. playlist.mediaSequence = 0;
  32552. playlist.discontinuitySequence = findIndex(timelineStarts, function (_ref7) {
  32553. var timeline = _ref7.timeline;
  32554. return timeline === playlist.timeline;
  32555. });
  32556. if (!playlist.segments) {
  32557. return;
  32558. }
  32559. playlist.segments.forEach(function (segment, index) {
  32560. segment.number = index;
  32561. });
  32562. });
  32563. };
  32564. /**
  32565. * Given a media group object, flattens all playlists within the media group into a single
  32566. * array.
  32567. *
  32568. * @param {Object} mediaGroupObject - the media group object
  32569. *
  32570. * @return {Object[]}
  32571. * The media group playlists
  32572. */
  32573. var flattenMediaGroupPlaylists = function flattenMediaGroupPlaylists(mediaGroupObject) {
  32574. if (!mediaGroupObject) {
  32575. return [];
  32576. }
  32577. return Object.keys(mediaGroupObject).reduce(function (acc, label) {
  32578. var labelContents = mediaGroupObject[label];
  32579. return acc.concat(labelContents.playlists);
  32580. }, []);
  32581. };
  32582. var toM3u8 = function toM3u8(_ref8) {
  32583. var _mediaGroups;
  32584. var dashPlaylists = _ref8.dashPlaylists,
  32585. locations = _ref8.locations,
  32586. _ref8$sidxMapping = _ref8.sidxMapping,
  32587. sidxMapping = _ref8$sidxMapping === void 0 ? {} : _ref8$sidxMapping,
  32588. previousManifest = _ref8.previousManifest;
  32589. if (!dashPlaylists.length) {
  32590. return {};
  32591. } // grab all main manifest attributes
  32592. var _dashPlaylists$0$attr = dashPlaylists[0].attributes,
  32593. duration = _dashPlaylists$0$attr.sourceDuration,
  32594. type = _dashPlaylists$0$attr.type,
  32595. suggestedPresentationDelay = _dashPlaylists$0$attr.suggestedPresentationDelay,
  32596. minimumUpdatePeriod = _dashPlaylists$0$attr.minimumUpdatePeriod;
  32597. var videoPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(videoOnly)).map(formatVideoPlaylist);
  32598. var audioPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(audioOnly));
  32599. var vttPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(vttOnly));
  32600. var captions = dashPlaylists.map(function (playlist) {
  32601. return playlist.attributes.captionServices;
  32602. }).filter(Boolean);
  32603. var manifest = {
  32604. allowCache: true,
  32605. discontinuityStarts: [],
  32606. segments: [],
  32607. endList: true,
  32608. mediaGroups: (_mediaGroups = {
  32609. AUDIO: {},
  32610. VIDEO: {}
  32611. }, _mediaGroups['CLOSED-CAPTIONS'] = {}, _mediaGroups.SUBTITLES = {}, _mediaGroups),
  32612. uri: '',
  32613. duration: duration,
  32614. playlists: addSidxSegmentsToPlaylists(videoPlaylists, sidxMapping)
  32615. };
  32616. if (minimumUpdatePeriod >= 0) {
  32617. manifest.minimumUpdatePeriod = minimumUpdatePeriod * 1000;
  32618. }
  32619. if (locations) {
  32620. manifest.locations = locations;
  32621. }
  32622. if (type === 'dynamic') {
  32623. manifest.suggestedPresentationDelay = suggestedPresentationDelay;
  32624. }
  32625. var isAudioOnly = manifest.playlists.length === 0;
  32626. var organizedAudioGroup = audioPlaylists.length ? organizeAudioPlaylists(audioPlaylists, sidxMapping, isAudioOnly) : null;
  32627. var organizedVttGroup = vttPlaylists.length ? organizeVttPlaylists(vttPlaylists, sidxMapping) : null;
  32628. var formattedPlaylists = videoPlaylists.concat(flattenMediaGroupPlaylists(organizedAudioGroup), flattenMediaGroupPlaylists(organizedVttGroup));
  32629. var playlistTimelineStarts = formattedPlaylists.map(function (_ref9) {
  32630. var timelineStarts = _ref9.timelineStarts;
  32631. return timelineStarts;
  32632. });
  32633. manifest.timelineStarts = getUniqueTimelineStarts(playlistTimelineStarts);
  32634. addMediaSequenceValues(formattedPlaylists, manifest.timelineStarts);
  32635. if (organizedAudioGroup) {
  32636. manifest.mediaGroups.AUDIO.audio = organizedAudioGroup;
  32637. }
  32638. if (organizedVttGroup) {
  32639. manifest.mediaGroups.SUBTITLES.subs = organizedVttGroup;
  32640. }
  32641. if (captions.length) {
  32642. manifest.mediaGroups['CLOSED-CAPTIONS'].cc = organizeCaptionServices(captions);
  32643. }
  32644. if (previousManifest) {
  32645. return positionManifestOnTimeline({
  32646. oldManifest: previousManifest,
  32647. newManifest: manifest
  32648. });
  32649. }
  32650. return manifest;
  32651. };
  32652. /**
  32653. * Calculates the R (repetition) value for a live stream (for the final segment
  32654. * in a manifest where the r value is negative 1)
  32655. *
  32656. * @param {Object} attributes
  32657. * Object containing all inherited attributes from parent elements with attribute
  32658. * names as keys
  32659. * @param {number} time
  32660. * current time (typically the total time up until the final segment)
  32661. * @param {number} duration
  32662. * duration property for the given <S />
  32663. *
  32664. * @return {number}
  32665. * R value to reach the end of the given period
  32666. */
  32667. var getLiveRValue = function getLiveRValue(attributes, time, duration) {
  32668. var NOW = attributes.NOW,
  32669. clientOffset = attributes.clientOffset,
  32670. availabilityStartTime = attributes.availabilityStartTime,
  32671. _attributes$timescale = attributes.timescale,
  32672. timescale = _attributes$timescale === void 0 ? 1 : _attributes$timescale,
  32673. _attributes$periodSta = attributes.periodStart,
  32674. periodStart = _attributes$periodSta === void 0 ? 0 : _attributes$periodSta,
  32675. _attributes$minimumUp = attributes.minimumUpdatePeriod,
  32676. minimumUpdatePeriod = _attributes$minimumUp === void 0 ? 0 : _attributes$minimumUp;
  32677. var now = (NOW + clientOffset) / 1000;
  32678. var periodStartWC = availabilityStartTime + periodStart;
  32679. var periodEndWC = now + minimumUpdatePeriod;
  32680. var periodDuration = periodEndWC - periodStartWC;
  32681. return Math.ceil((periodDuration * timescale - time) / duration);
  32682. };
  32683. /**
  32684. * Uses information provided by SegmentTemplate.SegmentTimeline to determine segment
  32685. * timing and duration
  32686. *
  32687. * @param {Object} attributes
  32688. * Object containing all inherited attributes from parent elements with attribute
  32689. * names as keys
  32690. * @param {Object[]} segmentTimeline
  32691. * List of objects representing the attributes of each S element contained within
  32692. *
  32693. * @return {{number: number, duration: number, time: number, timeline: number}[]}
  32694. * List of Objects with segment timing and duration info
  32695. */
  32696. var parseByTimeline = function parseByTimeline(attributes, segmentTimeline) {
  32697. var type = attributes.type,
  32698. _attributes$minimumUp2 = attributes.minimumUpdatePeriod,
  32699. minimumUpdatePeriod = _attributes$minimumUp2 === void 0 ? 0 : _attributes$minimumUp2,
  32700. _attributes$media = attributes.media,
  32701. media = _attributes$media === void 0 ? '' : _attributes$media,
  32702. sourceDuration = attributes.sourceDuration,
  32703. _attributes$timescale2 = attributes.timescale,
  32704. timescale = _attributes$timescale2 === void 0 ? 1 : _attributes$timescale2,
  32705. _attributes$startNumb = attributes.startNumber,
  32706. startNumber = _attributes$startNumb === void 0 ? 1 : _attributes$startNumb,
  32707. timeline = attributes.periodStart;
  32708. var segments = [];
  32709. var time = -1;
  32710. for (var sIndex = 0; sIndex < segmentTimeline.length; sIndex++) {
  32711. var S = segmentTimeline[sIndex];
  32712. var duration = S.d;
  32713. var repeat = S.r || 0;
  32714. var segmentTime = S.t || 0;
  32715. if (time < 0) {
  32716. // first segment
  32717. time = segmentTime;
  32718. }
  32719. if (segmentTime && segmentTime > time) {
  32720. // discontinuity
  32721. // TODO: How to handle this type of discontinuity
  32722. // timeline++ here would treat it like HLS discontuity and content would
  32723. // get appended without gap
  32724. // E.G.
  32725. // <S t="0" d="1" />
  32726. // <S d="1" />
  32727. // <S d="1" />
  32728. // <S t="5" d="1" />
  32729. // would have $Time$ values of [0, 1, 2, 5]
  32730. // should this be appened at time positions [0, 1, 2, 3],(#EXT-X-DISCONTINUITY)
  32731. // or [0, 1, 2, gap, gap, 5]? (#EXT-X-GAP)
  32732. // does the value of sourceDuration consider this when calculating arbitrary
  32733. // negative @r repeat value?
  32734. // E.G. Same elements as above with this added at the end
  32735. // <S d="1" r="-1" />
  32736. // with a sourceDuration of 10
  32737. // Would the 2 gaps be included in the time duration calculations resulting in
  32738. // 8 segments with $Time$ values of [0, 1, 2, 5, 6, 7, 8, 9] or 10 segments
  32739. // with $Time$ values of [0, 1, 2, 5, 6, 7, 8, 9, 10, 11] ?
  32740. time = segmentTime;
  32741. }
  32742. var count = void 0;
  32743. if (repeat < 0) {
  32744. var nextS = sIndex + 1;
  32745. if (nextS === segmentTimeline.length) {
  32746. // last segment
  32747. if (type === 'dynamic' && minimumUpdatePeriod > 0 && media.indexOf('$Number$') > 0) {
  32748. count = getLiveRValue(attributes, time, duration);
  32749. } else {
  32750. // TODO: This may be incorrect depending on conclusion of TODO above
  32751. count = (sourceDuration * timescale - time) / duration;
  32752. }
  32753. } else {
  32754. count = (segmentTimeline[nextS].t - time) / duration;
  32755. }
  32756. } else {
  32757. count = repeat + 1;
  32758. }
  32759. var end = startNumber + segments.length + count;
  32760. var number = startNumber + segments.length;
  32761. while (number < end) {
  32762. segments.push({
  32763. number: number,
  32764. duration: duration / timescale,
  32765. time: time,
  32766. timeline: timeline
  32767. });
  32768. time += duration;
  32769. number++;
  32770. }
  32771. }
  32772. return segments;
  32773. };
  32774. var identifierPattern = /\$([A-z]*)(?:(%0)([0-9]+)d)?\$/g;
  32775. /**
  32776. * Replaces template identifiers with corresponding values. To be used as the callback
  32777. * for String.prototype.replace
  32778. *
  32779. * @name replaceCallback
  32780. * @function
  32781. * @param {string} match
  32782. * Entire match of identifier
  32783. * @param {string} identifier
  32784. * Name of matched identifier
  32785. * @param {string} format
  32786. * Format tag string. Its presence indicates that padding is expected
  32787. * @param {string} width
  32788. * Desired length of the replaced value. Values less than this width shall be left
  32789. * zero padded
  32790. * @return {string}
  32791. * Replacement for the matched identifier
  32792. */
  32793. /**
  32794. * Returns a function to be used as a callback for String.prototype.replace to replace
  32795. * template identifiers
  32796. *
  32797. * @param {Obect} values
  32798. * Object containing values that shall be used to replace known identifiers
  32799. * @param {number} values.RepresentationID
  32800. * Value of the Representation@id attribute
  32801. * @param {number} values.Number
  32802. * Number of the corresponding segment
  32803. * @param {number} values.Bandwidth
  32804. * Value of the Representation@bandwidth attribute.
  32805. * @param {number} values.Time
  32806. * Timestamp value of the corresponding segment
  32807. * @return {replaceCallback}
  32808. * Callback to be used with String.prototype.replace to replace identifiers
  32809. */
  32810. var identifierReplacement = function identifierReplacement(values) {
  32811. return function (match, identifier, format, width) {
  32812. if (match === '$$') {
  32813. // escape sequence
  32814. return '$';
  32815. }
  32816. if (typeof values[identifier] === 'undefined') {
  32817. return match;
  32818. }
  32819. var value = '' + values[identifier];
  32820. if (identifier === 'RepresentationID') {
  32821. // Format tag shall not be present with RepresentationID
  32822. return value;
  32823. }
  32824. if (!format) {
  32825. width = 1;
  32826. } else {
  32827. width = parseInt(width, 10);
  32828. }
  32829. if (value.length >= width) {
  32830. return value;
  32831. }
  32832. return "" + new Array(width - value.length + 1).join('0') + value;
  32833. };
  32834. };
  32835. /**
  32836. * Constructs a segment url from a template string
  32837. *
  32838. * @param {string} url
  32839. * Template string to construct url from
  32840. * @param {Obect} values
  32841. * Object containing values that shall be used to replace known identifiers
  32842. * @param {number} values.RepresentationID
  32843. * Value of the Representation@id attribute
  32844. * @param {number} values.Number
  32845. * Number of the corresponding segment
  32846. * @param {number} values.Bandwidth
  32847. * Value of the Representation@bandwidth attribute.
  32848. * @param {number} values.Time
  32849. * Timestamp value of the corresponding segment
  32850. * @return {string}
  32851. * Segment url with identifiers replaced
  32852. */
  32853. var constructTemplateUrl = function constructTemplateUrl(url, values) {
  32854. return url.replace(identifierPattern, identifierReplacement(values));
  32855. };
  32856. /**
  32857. * Generates a list of objects containing timing and duration information about each
  32858. * segment needed to generate segment uris and the complete segment object
  32859. *
  32860. * @param {Object} attributes
  32861. * Object containing all inherited attributes from parent elements with attribute
  32862. * names as keys
  32863. * @param {Object[]|undefined} segmentTimeline
  32864. * List of objects representing the attributes of each S element contained within
  32865. * the SegmentTimeline element
  32866. * @return {{number: number, duration: number, time: number, timeline: number}[]}
  32867. * List of Objects with segment timing and duration info
  32868. */
  32869. var parseTemplateInfo = function parseTemplateInfo(attributes, segmentTimeline) {
  32870. if (!attributes.duration && !segmentTimeline) {
  32871. // if neither @duration or SegmentTimeline are present, then there shall be exactly
  32872. // one media segment
  32873. return [{
  32874. number: attributes.startNumber || 1,
  32875. duration: attributes.sourceDuration,
  32876. time: 0,
  32877. timeline: attributes.periodStart
  32878. }];
  32879. }
  32880. if (attributes.duration) {
  32881. return parseByDuration(attributes);
  32882. }
  32883. return parseByTimeline(attributes, segmentTimeline);
  32884. };
  32885. /**
  32886. * Generates a list of segments using information provided by the SegmentTemplate element
  32887. *
  32888. * @param {Object} attributes
  32889. * Object containing all inherited attributes from parent elements with attribute
  32890. * names as keys
  32891. * @param {Object[]|undefined} segmentTimeline
  32892. * List of objects representing the attributes of each S element contained within
  32893. * the SegmentTimeline element
  32894. * @return {Object[]}
  32895. * List of segment objects
  32896. */
  32897. var segmentsFromTemplate = function segmentsFromTemplate(attributes, segmentTimeline) {
  32898. var templateValues = {
  32899. RepresentationID: attributes.id,
  32900. Bandwidth: attributes.bandwidth || 0
  32901. };
  32902. var _attributes$initializ = attributes.initialization,
  32903. initialization = _attributes$initializ === void 0 ? {
  32904. sourceURL: '',
  32905. range: ''
  32906. } : _attributes$initializ;
  32907. var mapSegment = urlTypeToSegment({
  32908. baseUrl: attributes.baseUrl,
  32909. source: constructTemplateUrl(initialization.sourceURL, templateValues),
  32910. range: initialization.range
  32911. });
  32912. var segments = parseTemplateInfo(attributes, segmentTimeline);
  32913. return segments.map(function (segment) {
  32914. templateValues.Number = segment.number;
  32915. templateValues.Time = segment.time;
  32916. var uri = constructTemplateUrl(attributes.media || '', templateValues); // See DASH spec section 5.3.9.2.2
  32917. // - if timescale isn't present on any level, default to 1.
  32918. var timescale = attributes.timescale || 1; // - if presentationTimeOffset isn't present on any level, default to 0
  32919. var presentationTimeOffset = attributes.presentationTimeOffset || 0;
  32920. var presentationTime = // Even if the @t attribute is not specified for the segment, segment.time is
  32921. // calculated in mpd-parser prior to this, so it's assumed to be available.
  32922. attributes.periodStart + (segment.time - presentationTimeOffset) / timescale;
  32923. var map = {
  32924. uri: uri,
  32925. timeline: segment.timeline,
  32926. duration: segment.duration,
  32927. resolvedUri: resolveUrl$1(attributes.baseUrl || '', uri),
  32928. map: mapSegment,
  32929. number: segment.number,
  32930. presentationTime: presentationTime
  32931. };
  32932. return map;
  32933. });
  32934. };
  32935. /**
  32936. * Converts a <SegmentUrl> (of type URLType from the DASH spec 5.3.9.2 Table 14)
  32937. * to an object that matches the output of a segment in videojs/mpd-parser
  32938. *
  32939. * @param {Object} attributes
  32940. * Object containing all inherited attributes from parent elements with attribute
  32941. * names as keys
  32942. * @param {Object} segmentUrl
  32943. * <SegmentURL> node to translate into a segment object
  32944. * @return {Object} translated segment object
  32945. */
  32946. var SegmentURLToSegmentObject = function SegmentURLToSegmentObject(attributes, segmentUrl) {
  32947. var baseUrl = attributes.baseUrl,
  32948. _attributes$initializ = attributes.initialization,
  32949. initialization = _attributes$initializ === void 0 ? {} : _attributes$initializ;
  32950. var initSegment = urlTypeToSegment({
  32951. baseUrl: baseUrl,
  32952. source: initialization.sourceURL,
  32953. range: initialization.range
  32954. });
  32955. var segment = urlTypeToSegment({
  32956. baseUrl: baseUrl,
  32957. source: segmentUrl.media,
  32958. range: segmentUrl.mediaRange
  32959. });
  32960. segment.map = initSegment;
  32961. return segment;
  32962. };
  32963. /**
  32964. * Generates a list of segments using information provided by the SegmentList element
  32965. * SegmentList (DASH SPEC Section 5.3.9.3.2) contains a set of <SegmentURL> nodes. Each
  32966. * node should be translated into segment.
  32967. *
  32968. * @param {Object} attributes
  32969. * Object containing all inherited attributes from parent elements with attribute
  32970. * names as keys
  32971. * @param {Object[]|undefined} segmentTimeline
  32972. * List of objects representing the attributes of each S element contained within
  32973. * the SegmentTimeline element
  32974. * @return {Object.<Array>} list of segments
  32975. */
  32976. var segmentsFromList = function segmentsFromList(attributes, segmentTimeline) {
  32977. var duration = attributes.duration,
  32978. _attributes$segmentUr = attributes.segmentUrls,
  32979. segmentUrls = _attributes$segmentUr === void 0 ? [] : _attributes$segmentUr,
  32980. periodStart = attributes.periodStart; // Per spec (5.3.9.2.1) no way to determine segment duration OR
  32981. // if both SegmentTimeline and @duration are defined, it is outside of spec.
  32982. if (!duration && !segmentTimeline || duration && segmentTimeline) {
  32983. throw new Error(errors.SEGMENT_TIME_UNSPECIFIED);
  32984. }
  32985. var segmentUrlMap = segmentUrls.map(function (segmentUrlObject) {
  32986. return SegmentURLToSegmentObject(attributes, segmentUrlObject);
  32987. });
  32988. var segmentTimeInfo;
  32989. if (duration) {
  32990. segmentTimeInfo = parseByDuration(attributes);
  32991. }
  32992. if (segmentTimeline) {
  32993. segmentTimeInfo = parseByTimeline(attributes, segmentTimeline);
  32994. }
  32995. var segments = segmentTimeInfo.map(function (segmentTime, index) {
  32996. if (segmentUrlMap[index]) {
  32997. var segment = segmentUrlMap[index]; // See DASH spec section 5.3.9.2.2
  32998. // - if timescale isn't present on any level, default to 1.
  32999. var timescale = attributes.timescale || 1; // - if presentationTimeOffset isn't present on any level, default to 0
  33000. var presentationTimeOffset = attributes.presentationTimeOffset || 0;
  33001. segment.timeline = segmentTime.timeline;
  33002. segment.duration = segmentTime.duration;
  33003. segment.number = segmentTime.number;
  33004. segment.presentationTime = periodStart + (segmentTime.time - presentationTimeOffset) / timescale;
  33005. return segment;
  33006. } // Since we're mapping we should get rid of any blank segments (in case
  33007. // the given SegmentTimeline is handling for more elements than we have
  33008. // SegmentURLs for).
  33009. }).filter(function (segment) {
  33010. return segment;
  33011. });
  33012. return segments;
  33013. };
  33014. var generateSegments = function generateSegments(_ref) {
  33015. var attributes = _ref.attributes,
  33016. segmentInfo = _ref.segmentInfo;
  33017. var segmentAttributes;
  33018. var segmentsFn;
  33019. if (segmentInfo.template) {
  33020. segmentsFn = segmentsFromTemplate;
  33021. segmentAttributes = merge(attributes, segmentInfo.template);
  33022. } else if (segmentInfo.base) {
  33023. segmentsFn = segmentsFromBase;
  33024. segmentAttributes = merge(attributes, segmentInfo.base);
  33025. } else if (segmentInfo.list) {
  33026. segmentsFn = segmentsFromList;
  33027. segmentAttributes = merge(attributes, segmentInfo.list);
  33028. }
  33029. var segmentsInfo = {
  33030. attributes: attributes
  33031. };
  33032. if (!segmentsFn) {
  33033. return segmentsInfo;
  33034. }
  33035. var segments = segmentsFn(segmentAttributes, segmentInfo.segmentTimeline); // The @duration attribute will be used to determin the playlist's targetDuration which
  33036. // must be in seconds. Since we've generated the segment list, we no longer need
  33037. // @duration to be in @timescale units, so we can convert it here.
  33038. if (segmentAttributes.duration) {
  33039. var _segmentAttributes = segmentAttributes,
  33040. duration = _segmentAttributes.duration,
  33041. _segmentAttributes$ti = _segmentAttributes.timescale,
  33042. timescale = _segmentAttributes$ti === void 0 ? 1 : _segmentAttributes$ti;
  33043. segmentAttributes.duration = duration / timescale;
  33044. } else if (segments.length) {
  33045. // if there is no @duration attribute, use the largest segment duration as
  33046. // as target duration
  33047. segmentAttributes.duration = segments.reduce(function (max, segment) {
  33048. return Math.max(max, Math.ceil(segment.duration));
  33049. }, 0);
  33050. } else {
  33051. segmentAttributes.duration = 0;
  33052. }
  33053. segmentsInfo.attributes = segmentAttributes;
  33054. segmentsInfo.segments = segments; // This is a sidx box without actual segment information
  33055. if (segmentInfo.base && segmentAttributes.indexRange) {
  33056. segmentsInfo.sidx = segments[0];
  33057. segmentsInfo.segments = [];
  33058. }
  33059. return segmentsInfo;
  33060. };
  33061. var toPlaylists = function toPlaylists(representations) {
  33062. return representations.map(generateSegments);
  33063. };
  33064. var findChildren = function findChildren(element, name) {
  33065. return from(element.childNodes).filter(function (_ref) {
  33066. var tagName = _ref.tagName;
  33067. return tagName === name;
  33068. });
  33069. };
  33070. var getContent = function getContent(element) {
  33071. return element.textContent.trim();
  33072. };
  33073. /**
  33074. * Converts the provided string that may contain a division operation to a number.
  33075. *
  33076. * @param {string} value - the provided string value
  33077. *
  33078. * @return {number} the parsed string value
  33079. */
  33080. var parseDivisionValue = function parseDivisionValue(value) {
  33081. return parseFloat(value.split('/').reduce(function (prev, current) {
  33082. return prev / current;
  33083. }));
  33084. };
  33085. var parseDuration = function parseDuration(str) {
  33086. var SECONDS_IN_YEAR = 365 * 24 * 60 * 60;
  33087. var SECONDS_IN_MONTH = 30 * 24 * 60 * 60;
  33088. var SECONDS_IN_DAY = 24 * 60 * 60;
  33089. var SECONDS_IN_HOUR = 60 * 60;
  33090. var SECONDS_IN_MIN = 60; // P10Y10M10DT10H10M10.1S
  33091. var durationRegex = /P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/;
  33092. var match = durationRegex.exec(str);
  33093. if (!match) {
  33094. return 0;
  33095. }
  33096. var _match$slice = match.slice(1),
  33097. year = _match$slice[0],
  33098. month = _match$slice[1],
  33099. day = _match$slice[2],
  33100. hour = _match$slice[3],
  33101. minute = _match$slice[4],
  33102. second = _match$slice[5];
  33103. return parseFloat(year || 0) * SECONDS_IN_YEAR + parseFloat(month || 0) * SECONDS_IN_MONTH + parseFloat(day || 0) * SECONDS_IN_DAY + parseFloat(hour || 0) * SECONDS_IN_HOUR + parseFloat(minute || 0) * SECONDS_IN_MIN + parseFloat(second || 0);
  33104. };
  33105. var parseDate = function parseDate(str) {
  33106. // Date format without timezone according to ISO 8601
  33107. // YYY-MM-DDThh:mm:ss.ssssss
  33108. var dateRegex = /^\d+-\d+-\d+T\d+:\d+:\d+(\.\d+)?$/; // If the date string does not specifiy a timezone, we must specifiy UTC. This is
  33109. // expressed by ending with 'Z'
  33110. if (dateRegex.test(str)) {
  33111. str += 'Z';
  33112. }
  33113. return Date.parse(str);
  33114. };
  33115. var parsers = {
  33116. /**
  33117. * Specifies the duration of the entire Media Presentation. Format is a duration string
  33118. * as specified in ISO 8601
  33119. *
  33120. * @param {string} value
  33121. * value of attribute as a string
  33122. * @return {number}
  33123. * The duration in seconds
  33124. */
  33125. mediaPresentationDuration: function mediaPresentationDuration(value) {
  33126. return parseDuration(value);
  33127. },
  33128. /**
  33129. * Specifies the Segment availability start time for all Segments referred to in this
  33130. * MPD. For a dynamic manifest, it specifies the anchor for the earliest availability
  33131. * time. Format is a date string as specified in ISO 8601
  33132. *
  33133. * @param {string} value
  33134. * value of attribute as a string
  33135. * @return {number}
  33136. * The date as seconds from unix epoch
  33137. */
  33138. availabilityStartTime: function availabilityStartTime(value) {
  33139. return parseDate(value) / 1000;
  33140. },
  33141. /**
  33142. * Specifies the smallest period between potential changes to the MPD. Format is a
  33143. * duration string as specified in ISO 8601
  33144. *
  33145. * @param {string} value
  33146. * value of attribute as a string
  33147. * @return {number}
  33148. * The duration in seconds
  33149. */
  33150. minimumUpdatePeriod: function minimumUpdatePeriod(value) {
  33151. return parseDuration(value);
  33152. },
  33153. /**
  33154. * Specifies the suggested presentation delay. Format is a
  33155. * duration string as specified in ISO 8601
  33156. *
  33157. * @param {string} value
  33158. * value of attribute as a string
  33159. * @return {number}
  33160. * The duration in seconds
  33161. */
  33162. suggestedPresentationDelay: function suggestedPresentationDelay(value) {
  33163. return parseDuration(value);
  33164. },
  33165. /**
  33166. * specifices the type of mpd. Can be either "static" or "dynamic"
  33167. *
  33168. * @param {string} value
  33169. * value of attribute as a string
  33170. *
  33171. * @return {string}
  33172. * The type as a string
  33173. */
  33174. type: function type(value) {
  33175. return value;
  33176. },
  33177. /**
  33178. * Specifies the duration of the smallest time shifting buffer for any Representation
  33179. * in the MPD. Format is a duration string as specified in ISO 8601
  33180. *
  33181. * @param {string} value
  33182. * value of attribute as a string
  33183. * @return {number}
  33184. * The duration in seconds
  33185. */
  33186. timeShiftBufferDepth: function timeShiftBufferDepth(value) {
  33187. return parseDuration(value);
  33188. },
  33189. /**
  33190. * Specifies the PeriodStart time of the Period relative to the availabilityStarttime.
  33191. * Format is a duration string as specified in ISO 8601
  33192. *
  33193. * @param {string} value
  33194. * value of attribute as a string
  33195. * @return {number}
  33196. * The duration in seconds
  33197. */
  33198. start: function start(value) {
  33199. return parseDuration(value);
  33200. },
  33201. /**
  33202. * Specifies the width of the visual presentation
  33203. *
  33204. * @param {string} value
  33205. * value of attribute as a string
  33206. * @return {number}
  33207. * The parsed width
  33208. */
  33209. width: function width(value) {
  33210. return parseInt(value, 10);
  33211. },
  33212. /**
  33213. * Specifies the height of the visual presentation
  33214. *
  33215. * @param {string} value
  33216. * value of attribute as a string
  33217. * @return {number}
  33218. * The parsed height
  33219. */
  33220. height: function height(value) {
  33221. return parseInt(value, 10);
  33222. },
  33223. /**
  33224. * Specifies the bitrate of the representation
  33225. *
  33226. * @param {string} value
  33227. * value of attribute as a string
  33228. * @return {number}
  33229. * The parsed bandwidth
  33230. */
  33231. bandwidth: function bandwidth(value) {
  33232. return parseInt(value, 10);
  33233. },
  33234. /**
  33235. * Specifies the frame rate of the representation
  33236. *
  33237. * @param {string} value
  33238. * value of attribute as a string
  33239. * @return {number}
  33240. * The parsed frame rate
  33241. */
  33242. frameRate: function frameRate(value) {
  33243. return parseDivisionValue(value);
  33244. },
  33245. /**
  33246. * Specifies the number of the first Media Segment in this Representation in the Period
  33247. *
  33248. * @param {string} value
  33249. * value of attribute as a string
  33250. * @return {number}
  33251. * The parsed number
  33252. */
  33253. startNumber: function startNumber(value) {
  33254. return parseInt(value, 10);
  33255. },
  33256. /**
  33257. * Specifies the timescale in units per seconds
  33258. *
  33259. * @param {string} value
  33260. * value of attribute as a string
  33261. * @return {number}
  33262. * The parsed timescale
  33263. */
  33264. timescale: function timescale(value) {
  33265. return parseInt(value, 10);
  33266. },
  33267. /**
  33268. * Specifies the presentationTimeOffset.
  33269. *
  33270. * @param {string} value
  33271. * value of the attribute as a string
  33272. *
  33273. * @return {number}
  33274. * The parsed presentationTimeOffset
  33275. */
  33276. presentationTimeOffset: function presentationTimeOffset(value) {
  33277. return parseInt(value, 10);
  33278. },
  33279. /**
  33280. * Specifies the constant approximate Segment duration
  33281. * NOTE: The <Period> element also contains an @duration attribute. This duration
  33282. * specifies the duration of the Period. This attribute is currently not
  33283. * supported by the rest of the parser, however we still check for it to prevent
  33284. * errors.
  33285. *
  33286. * @param {string} value
  33287. * value of attribute as a string
  33288. * @return {number}
  33289. * The parsed duration
  33290. */
  33291. duration: function duration(value) {
  33292. var parsedValue = parseInt(value, 10);
  33293. if (isNaN(parsedValue)) {
  33294. return parseDuration(value);
  33295. }
  33296. return parsedValue;
  33297. },
  33298. /**
  33299. * Specifies the Segment duration, in units of the value of the @timescale.
  33300. *
  33301. * @param {string} value
  33302. * value of attribute as a string
  33303. * @return {number}
  33304. * The parsed duration
  33305. */
  33306. d: function d(value) {
  33307. return parseInt(value, 10);
  33308. },
  33309. /**
  33310. * Specifies the MPD start time, in @timescale units, the first Segment in the series
  33311. * starts relative to the beginning of the Period
  33312. *
  33313. * @param {string} value
  33314. * value of attribute as a string
  33315. * @return {number}
  33316. * The parsed time
  33317. */
  33318. t: function t(value) {
  33319. return parseInt(value, 10);
  33320. },
  33321. /**
  33322. * Specifies the repeat count of the number of following contiguous Segments with the
  33323. * same duration expressed by the value of @d
  33324. *
  33325. * @param {string} value
  33326. * value of attribute as a string
  33327. * @return {number}
  33328. * The parsed number
  33329. */
  33330. r: function r(value) {
  33331. return parseInt(value, 10);
  33332. },
  33333. /**
  33334. * Default parser for all other attributes. Acts as a no-op and just returns the value
  33335. * as a string
  33336. *
  33337. * @param {string} value
  33338. * value of attribute as a string
  33339. * @return {string}
  33340. * Unparsed value
  33341. */
  33342. DEFAULT: function DEFAULT(value) {
  33343. return value;
  33344. }
  33345. };
  33346. /**
  33347. * Gets all the attributes and values of the provided node, parses attributes with known
  33348. * types, and returns an object with attribute names mapped to values.
  33349. *
  33350. * @param {Node} el
  33351. * The node to parse attributes from
  33352. * @return {Object}
  33353. * Object with all attributes of el parsed
  33354. */
  33355. var parseAttributes = function parseAttributes(el) {
  33356. if (!(el && el.attributes)) {
  33357. return {};
  33358. }
  33359. return from(el.attributes).reduce(function (a, e) {
  33360. var parseFn = parsers[e.name] || parsers.DEFAULT;
  33361. a[e.name] = parseFn(e.value);
  33362. return a;
  33363. }, {});
  33364. };
  33365. var keySystemsMap = {
  33366. 'urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b': 'org.w3.clearkey',
  33367. 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed': 'com.widevine.alpha',
  33368. 'urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95': 'com.microsoft.playready',
  33369. 'urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb': 'com.adobe.primetime'
  33370. };
  33371. /**
  33372. * Builds a list of urls that is the product of the reference urls and BaseURL values
  33373. *
  33374. * @param {string[]} referenceUrls
  33375. * List of reference urls to resolve to
  33376. * @param {Node[]} baseUrlElements
  33377. * List of BaseURL nodes from the mpd
  33378. * @return {string[]}
  33379. * List of resolved urls
  33380. */
  33381. var buildBaseUrls = function buildBaseUrls(referenceUrls, baseUrlElements) {
  33382. if (!baseUrlElements.length) {
  33383. return referenceUrls;
  33384. }
  33385. return flatten(referenceUrls.map(function (reference) {
  33386. return baseUrlElements.map(function (baseUrlElement) {
  33387. return resolveUrl$1(reference, getContent(baseUrlElement));
  33388. });
  33389. }));
  33390. };
  33391. /**
  33392. * Contains all Segment information for its containing AdaptationSet
  33393. *
  33394. * @typedef {Object} SegmentInformation
  33395. * @property {Object|undefined} template
  33396. * Contains the attributes for the SegmentTemplate node
  33397. * @property {Object[]|undefined} segmentTimeline
  33398. * Contains a list of atrributes for each S node within the SegmentTimeline node
  33399. * @property {Object|undefined} list
  33400. * Contains the attributes for the SegmentList node
  33401. * @property {Object|undefined} base
  33402. * Contains the attributes for the SegmentBase node
  33403. */
  33404. /**
  33405. * Returns all available Segment information contained within the AdaptationSet node
  33406. *
  33407. * @param {Node} adaptationSet
  33408. * The AdaptationSet node to get Segment information from
  33409. * @return {SegmentInformation}
  33410. * The Segment information contained within the provided AdaptationSet
  33411. */
  33412. var getSegmentInformation = function getSegmentInformation(adaptationSet) {
  33413. var segmentTemplate = findChildren(adaptationSet, 'SegmentTemplate')[0];
  33414. var segmentList = findChildren(adaptationSet, 'SegmentList')[0];
  33415. var segmentUrls = segmentList && findChildren(segmentList, 'SegmentURL').map(function (s) {
  33416. return merge({
  33417. tag: 'SegmentURL'
  33418. }, parseAttributes(s));
  33419. });
  33420. var segmentBase = findChildren(adaptationSet, 'SegmentBase')[0];
  33421. var segmentTimelineParentNode = segmentList || segmentTemplate;
  33422. var segmentTimeline = segmentTimelineParentNode && findChildren(segmentTimelineParentNode, 'SegmentTimeline')[0];
  33423. var segmentInitializationParentNode = segmentList || segmentBase || segmentTemplate;
  33424. var segmentInitialization = segmentInitializationParentNode && findChildren(segmentInitializationParentNode, 'Initialization')[0]; // SegmentTemplate is handled slightly differently, since it can have both
  33425. // @initialization and an <Initialization> node. @initialization can be templated,
  33426. // while the node can have a url and range specified. If the <SegmentTemplate> has
  33427. // both @initialization and an <Initialization> subelement we opt to override with
  33428. // the node, as this interaction is not defined in the spec.
  33429. var template = segmentTemplate && parseAttributes(segmentTemplate);
  33430. if (template && segmentInitialization) {
  33431. template.initialization = segmentInitialization && parseAttributes(segmentInitialization);
  33432. } else if (template && template.initialization) {
  33433. // If it is @initialization we convert it to an object since this is the format that
  33434. // later functions will rely on for the initialization segment. This is only valid
  33435. // for <SegmentTemplate>
  33436. template.initialization = {
  33437. sourceURL: template.initialization
  33438. };
  33439. }
  33440. var segmentInfo = {
  33441. template: template,
  33442. segmentTimeline: segmentTimeline && findChildren(segmentTimeline, 'S').map(function (s) {
  33443. return parseAttributes(s);
  33444. }),
  33445. list: segmentList && merge(parseAttributes(segmentList), {
  33446. segmentUrls: segmentUrls,
  33447. initialization: parseAttributes(segmentInitialization)
  33448. }),
  33449. base: segmentBase && merge(parseAttributes(segmentBase), {
  33450. initialization: parseAttributes(segmentInitialization)
  33451. })
  33452. };
  33453. Object.keys(segmentInfo).forEach(function (key) {
  33454. if (!segmentInfo[key]) {
  33455. delete segmentInfo[key];
  33456. }
  33457. });
  33458. return segmentInfo;
  33459. };
  33460. /**
  33461. * Contains Segment information and attributes needed to construct a Playlist object
  33462. * from a Representation
  33463. *
  33464. * @typedef {Object} RepresentationInformation
  33465. * @property {SegmentInformation} segmentInfo
  33466. * Segment information for this Representation
  33467. * @property {Object} attributes
  33468. * Inherited attributes for this Representation
  33469. */
  33470. /**
  33471. * Maps a Representation node to an object containing Segment information and attributes
  33472. *
  33473. * @name inheritBaseUrlsCallback
  33474. * @function
  33475. * @param {Node} representation
  33476. * Representation node from the mpd
  33477. * @return {RepresentationInformation}
  33478. * Representation information needed to construct a Playlist object
  33479. */
  33480. /**
  33481. * Returns a callback for Array.prototype.map for mapping Representation nodes to
  33482. * Segment information and attributes using inherited BaseURL nodes.
  33483. *
  33484. * @param {Object} adaptationSetAttributes
  33485. * Contains attributes inherited by the AdaptationSet
  33486. * @param {string[]} adaptationSetBaseUrls
  33487. * Contains list of resolved base urls inherited by the AdaptationSet
  33488. * @param {SegmentInformation} adaptationSetSegmentInfo
  33489. * Contains Segment information for the AdaptationSet
  33490. * @return {inheritBaseUrlsCallback}
  33491. * Callback map function
  33492. */
  33493. var inheritBaseUrls = function inheritBaseUrls(adaptationSetAttributes, adaptationSetBaseUrls, adaptationSetSegmentInfo) {
  33494. return function (representation) {
  33495. var repBaseUrlElements = findChildren(representation, 'BaseURL');
  33496. var repBaseUrls = buildBaseUrls(adaptationSetBaseUrls, repBaseUrlElements);
  33497. var attributes = merge(adaptationSetAttributes, parseAttributes(representation));
  33498. var representationSegmentInfo = getSegmentInformation(representation);
  33499. return repBaseUrls.map(function (baseUrl) {
  33500. return {
  33501. segmentInfo: merge(adaptationSetSegmentInfo, representationSegmentInfo),
  33502. attributes: merge(attributes, {
  33503. baseUrl: baseUrl
  33504. })
  33505. };
  33506. });
  33507. };
  33508. };
  33509. /**
  33510. * Tranforms a series of content protection nodes to
  33511. * an object containing pssh data by key system
  33512. *
  33513. * @param {Node[]} contentProtectionNodes
  33514. * Content protection nodes
  33515. * @return {Object}
  33516. * Object containing pssh data by key system
  33517. */
  33518. var generateKeySystemInformation = function generateKeySystemInformation(contentProtectionNodes) {
  33519. return contentProtectionNodes.reduce(function (acc, node) {
  33520. var attributes = parseAttributes(node); // Although it could be argued that according to the UUID RFC spec the UUID string (a-f chars) should be generated
  33521. // as a lowercase string it also mentions it should be treated as case-insensitive on input. Since the key system
  33522. // UUIDs in the keySystemsMap are hardcoded as lowercase in the codebase there isn't any reason not to do
  33523. // .toLowerCase() on the input UUID string from the manifest (at least I could not think of one).
  33524. if (attributes.schemeIdUri) {
  33525. attributes.schemeIdUri = attributes.schemeIdUri.toLowerCase();
  33526. }
  33527. var keySystem = keySystemsMap[attributes.schemeIdUri];
  33528. if (keySystem) {
  33529. acc[keySystem] = {
  33530. attributes: attributes
  33531. };
  33532. var psshNode = findChildren(node, 'cenc:pssh')[0];
  33533. if (psshNode) {
  33534. var pssh = getContent(psshNode);
  33535. acc[keySystem].pssh = pssh && decodeB64ToUint8Array(pssh);
  33536. }
  33537. }
  33538. return acc;
  33539. }, {});
  33540. }; // defined in ANSI_SCTE 214-1 2016
  33541. var parseCaptionServiceMetadata = function parseCaptionServiceMetadata(service) {
  33542. // 608 captions
  33543. if (service.schemeIdUri === 'urn:scte:dash:cc:cea-608:2015') {
  33544. var values = typeof service.value !== 'string' ? [] : service.value.split(';');
  33545. return values.map(function (value) {
  33546. var channel;
  33547. var language; // default language to value
  33548. language = value;
  33549. if (/^CC\d=/.test(value)) {
  33550. var _value$split = value.split('=');
  33551. channel = _value$split[0];
  33552. language = _value$split[1];
  33553. } else if (/^CC\d$/.test(value)) {
  33554. channel = value;
  33555. }
  33556. return {
  33557. channel: channel,
  33558. language: language
  33559. };
  33560. });
  33561. } else if (service.schemeIdUri === 'urn:scte:dash:cc:cea-708:2015') {
  33562. var _values = typeof service.value !== 'string' ? [] : service.value.split(';');
  33563. return _values.map(function (value) {
  33564. var flags = {
  33565. // service or channel number 1-63
  33566. 'channel': undefined,
  33567. // language is a 3ALPHA per ISO 639.2/B
  33568. // field is required
  33569. 'language': undefined,
  33570. // BIT 1/0 or ?
  33571. // default value is 1, meaning 16:9 aspect ratio, 0 is 4:3, ? is unknown
  33572. 'aspectRatio': 1,
  33573. // BIT 1/0
  33574. // easy reader flag indicated the text is tailed to the needs of beginning readers
  33575. // default 0, or off
  33576. 'easyReader': 0,
  33577. // BIT 1/0
  33578. // If 3d metadata is present (CEA-708.1) then 1
  33579. // default 0
  33580. '3D': 0
  33581. };
  33582. if (/=/.test(value)) {
  33583. var _value$split2 = value.split('='),
  33584. channel = _value$split2[0],
  33585. _value$split2$ = _value$split2[1],
  33586. opts = _value$split2$ === void 0 ? '' : _value$split2$;
  33587. flags.channel = channel;
  33588. flags.language = value;
  33589. opts.split(',').forEach(function (opt) {
  33590. var _opt$split = opt.split(':'),
  33591. name = _opt$split[0],
  33592. val = _opt$split[1];
  33593. if (name === 'lang') {
  33594. flags.language = val; // er for easyReadery
  33595. } else if (name === 'er') {
  33596. flags.easyReader = Number(val); // war for wide aspect ratio
  33597. } else if (name === 'war') {
  33598. flags.aspectRatio = Number(val);
  33599. } else if (name === '3D') {
  33600. flags['3D'] = Number(val);
  33601. }
  33602. });
  33603. } else {
  33604. flags.language = value;
  33605. }
  33606. if (flags.channel) {
  33607. flags.channel = 'SERVICE' + flags.channel;
  33608. }
  33609. return flags;
  33610. });
  33611. }
  33612. };
  33613. /**
  33614. * Maps an AdaptationSet node to a list of Representation information objects
  33615. *
  33616. * @name toRepresentationsCallback
  33617. * @function
  33618. * @param {Node} adaptationSet
  33619. * AdaptationSet node from the mpd
  33620. * @return {RepresentationInformation[]}
  33621. * List of objects containing Representaion information
  33622. */
  33623. /**
  33624. * Returns a callback for Array.prototype.map for mapping AdaptationSet nodes to a list of
  33625. * Representation information objects
  33626. *
  33627. * @param {Object} periodAttributes
  33628. * Contains attributes inherited by the Period
  33629. * @param {string[]} periodBaseUrls
  33630. * Contains list of resolved base urls inherited by the Period
  33631. * @param {string[]} periodSegmentInfo
  33632. * Contains Segment Information at the period level
  33633. * @return {toRepresentationsCallback}
  33634. * Callback map function
  33635. */
  33636. var toRepresentations = function toRepresentations(periodAttributes, periodBaseUrls, periodSegmentInfo) {
  33637. return function (adaptationSet) {
  33638. var adaptationSetAttributes = parseAttributes(adaptationSet);
  33639. var adaptationSetBaseUrls = buildBaseUrls(periodBaseUrls, findChildren(adaptationSet, 'BaseURL'));
  33640. var role = findChildren(adaptationSet, 'Role')[0];
  33641. var roleAttributes = {
  33642. role: parseAttributes(role)
  33643. };
  33644. var attrs = merge(periodAttributes, adaptationSetAttributes, roleAttributes);
  33645. var accessibility = findChildren(adaptationSet, 'Accessibility')[0];
  33646. var captionServices = parseCaptionServiceMetadata(parseAttributes(accessibility));
  33647. if (captionServices) {
  33648. attrs = merge(attrs, {
  33649. captionServices: captionServices
  33650. });
  33651. }
  33652. var label = findChildren(adaptationSet, 'Label')[0];
  33653. if (label && label.childNodes.length) {
  33654. var labelVal = label.childNodes[0].nodeValue.trim();
  33655. attrs = merge(attrs, {
  33656. label: labelVal
  33657. });
  33658. }
  33659. var contentProtection = generateKeySystemInformation(findChildren(adaptationSet, 'ContentProtection'));
  33660. if (Object.keys(contentProtection).length) {
  33661. attrs = merge(attrs, {
  33662. contentProtection: contentProtection
  33663. });
  33664. }
  33665. var segmentInfo = getSegmentInformation(adaptationSet);
  33666. var representations = findChildren(adaptationSet, 'Representation');
  33667. var adaptationSetSegmentInfo = merge(periodSegmentInfo, segmentInfo);
  33668. return flatten(representations.map(inheritBaseUrls(attrs, adaptationSetBaseUrls, adaptationSetSegmentInfo)));
  33669. };
  33670. };
  33671. /**
  33672. * Contains all period information for mapping nodes onto adaptation sets.
  33673. *
  33674. * @typedef {Object} PeriodInformation
  33675. * @property {Node} period.node
  33676. * Period node from the mpd
  33677. * @property {Object} period.attributes
  33678. * Parsed period attributes from node plus any added
  33679. */
  33680. /**
  33681. * Maps a PeriodInformation object to a list of Representation information objects for all
  33682. * AdaptationSet nodes contained within the Period.
  33683. *
  33684. * @name toAdaptationSetsCallback
  33685. * @function
  33686. * @param {PeriodInformation} period
  33687. * Period object containing necessary period information
  33688. * @param {number} periodStart
  33689. * Start time of the Period within the mpd
  33690. * @return {RepresentationInformation[]}
  33691. * List of objects containing Representaion information
  33692. */
  33693. /**
  33694. * Returns a callback for Array.prototype.map for mapping Period nodes to a list of
  33695. * Representation information objects
  33696. *
  33697. * @param {Object} mpdAttributes
  33698. * Contains attributes inherited by the mpd
  33699. * @param {string[]} mpdBaseUrls
  33700. * Contains list of resolved base urls inherited by the mpd
  33701. * @return {toAdaptationSetsCallback}
  33702. * Callback map function
  33703. */
  33704. var toAdaptationSets = function toAdaptationSets(mpdAttributes, mpdBaseUrls) {
  33705. return function (period, index) {
  33706. var periodBaseUrls = buildBaseUrls(mpdBaseUrls, findChildren(period.node, 'BaseURL'));
  33707. var periodAttributes = merge(mpdAttributes, {
  33708. periodStart: period.attributes.start
  33709. });
  33710. if (typeof period.attributes.duration === 'number') {
  33711. periodAttributes.periodDuration = period.attributes.duration;
  33712. }
  33713. var adaptationSets = findChildren(period.node, 'AdaptationSet');
  33714. var periodSegmentInfo = getSegmentInformation(period.node);
  33715. return flatten(adaptationSets.map(toRepresentations(periodAttributes, periodBaseUrls, periodSegmentInfo)));
  33716. };
  33717. };
  33718. /**
  33719. * Gets Period@start property for a given period.
  33720. *
  33721. * @param {Object} options
  33722. * Options object
  33723. * @param {Object} options.attributes
  33724. * Period attributes
  33725. * @param {Object} [options.priorPeriodAttributes]
  33726. * Prior period attributes (if prior period is available)
  33727. * @param {string} options.mpdType
  33728. * The MPD@type these periods came from
  33729. * @return {number|null}
  33730. * The period start, or null if it's an early available period or error
  33731. */
  33732. var getPeriodStart = function getPeriodStart(_ref) {
  33733. var attributes = _ref.attributes,
  33734. priorPeriodAttributes = _ref.priorPeriodAttributes,
  33735. mpdType = _ref.mpdType; // Summary of period start time calculation from DASH spec section 5.3.2.1
  33736. //
  33737. // A period's start is the first period's start + time elapsed after playing all
  33738. // prior periods to this one. Periods continue one after the other in time (without
  33739. // gaps) until the end of the presentation.
  33740. //
  33741. // The value of Period@start should be:
  33742. // 1. if Period@start is present: value of Period@start
  33743. // 2. if previous period exists and it has @duration: previous Period@start +
  33744. // previous Period@duration
  33745. // 3. if this is first period and MPD@type is 'static': 0
  33746. // 4. in all other cases, consider the period an "early available period" (note: not
  33747. // currently supported)
  33748. // (1)
  33749. if (typeof attributes.start === 'number') {
  33750. return attributes.start;
  33751. } // (2)
  33752. if (priorPeriodAttributes && typeof priorPeriodAttributes.start === 'number' && typeof priorPeriodAttributes.duration === 'number') {
  33753. return priorPeriodAttributes.start + priorPeriodAttributes.duration;
  33754. } // (3)
  33755. if (!priorPeriodAttributes && mpdType === 'static') {
  33756. return 0;
  33757. } // (4)
  33758. // There is currently no logic for calculating the Period@start value if there is
  33759. // no Period@start or prior Period@start and Period@duration available. This is not made
  33760. // explicit by the DASH interop guidelines or the DASH spec, however, since there's
  33761. // nothing about any other resolution strategies, it's implied. Thus, this case should
  33762. // be considered an early available period, or error, and null should suffice for both
  33763. // of those cases.
  33764. return null;
  33765. };
  33766. /**
  33767. * Traverses the mpd xml tree to generate a list of Representation information objects
  33768. * that have inherited attributes from parent nodes
  33769. *
  33770. * @param {Node} mpd
  33771. * The root node of the mpd
  33772. * @param {Object} options
  33773. * Available options for inheritAttributes
  33774. * @param {string} options.manifestUri
  33775. * The uri source of the mpd
  33776. * @param {number} options.NOW
  33777. * Current time per DASH IOP. Default is current time in ms since epoch
  33778. * @param {number} options.clientOffset
  33779. * Client time difference from NOW (in milliseconds)
  33780. * @return {RepresentationInformation[]}
  33781. * List of objects containing Representation information
  33782. */
  33783. var inheritAttributes = function inheritAttributes(mpd, options) {
  33784. if (options === void 0) {
  33785. options = {};
  33786. }
  33787. var _options = options,
  33788. _options$manifestUri = _options.manifestUri,
  33789. manifestUri = _options$manifestUri === void 0 ? '' : _options$manifestUri,
  33790. _options$NOW = _options.NOW,
  33791. NOW = _options$NOW === void 0 ? Date.now() : _options$NOW,
  33792. _options$clientOffset = _options.clientOffset,
  33793. clientOffset = _options$clientOffset === void 0 ? 0 : _options$clientOffset;
  33794. var periodNodes = findChildren(mpd, 'Period');
  33795. if (!periodNodes.length) {
  33796. throw new Error(errors.INVALID_NUMBER_OF_PERIOD);
  33797. }
  33798. var locations = findChildren(mpd, 'Location');
  33799. var mpdAttributes = parseAttributes(mpd);
  33800. var mpdBaseUrls = buildBaseUrls([manifestUri], findChildren(mpd, 'BaseURL')); // See DASH spec section 5.3.1.2, Semantics of MPD element. Default type to 'static'.
  33801. mpdAttributes.type = mpdAttributes.type || 'static';
  33802. mpdAttributes.sourceDuration = mpdAttributes.mediaPresentationDuration || 0;
  33803. mpdAttributes.NOW = NOW;
  33804. mpdAttributes.clientOffset = clientOffset;
  33805. if (locations.length) {
  33806. mpdAttributes.locations = locations.map(getContent);
  33807. }
  33808. var periods = []; // Since toAdaptationSets acts on individual periods right now, the simplest approach to
  33809. // adding properties that require looking at prior periods is to parse attributes and add
  33810. // missing ones before toAdaptationSets is called. If more such properties are added, it
  33811. // may be better to refactor toAdaptationSets.
  33812. periodNodes.forEach(function (node, index) {
  33813. var attributes = parseAttributes(node); // Use the last modified prior period, as it may contain added information necessary
  33814. // for this period.
  33815. var priorPeriod = periods[index - 1];
  33816. attributes.start = getPeriodStart({
  33817. attributes: attributes,
  33818. priorPeriodAttributes: priorPeriod ? priorPeriod.attributes : null,
  33819. mpdType: mpdAttributes.type
  33820. });
  33821. periods.push({
  33822. node: node,
  33823. attributes: attributes
  33824. });
  33825. });
  33826. return {
  33827. locations: mpdAttributes.locations,
  33828. representationInfo: flatten(periods.map(toAdaptationSets(mpdAttributes, mpdBaseUrls)))
  33829. };
  33830. };
  33831. var stringToMpdXml = function stringToMpdXml(manifestString) {
  33832. if (manifestString === '') {
  33833. throw new Error(errors.DASH_EMPTY_MANIFEST);
  33834. }
  33835. var parser = new DOMParser();
  33836. var xml;
  33837. var mpd;
  33838. try {
  33839. xml = parser.parseFromString(manifestString, 'application/xml');
  33840. mpd = xml && xml.documentElement.tagName === 'MPD' ? xml.documentElement : null;
  33841. } catch (e) {// ie 11 throwsw on invalid xml
  33842. }
  33843. if (!mpd || mpd && mpd.getElementsByTagName('parsererror').length > 0) {
  33844. throw new Error(errors.DASH_INVALID_XML);
  33845. }
  33846. return mpd;
  33847. };
  33848. /**
  33849. * Parses the manifest for a UTCTiming node, returning the nodes attributes if found
  33850. *
  33851. * @param {string} mpd
  33852. * XML string of the MPD manifest
  33853. * @return {Object|null}
  33854. * Attributes of UTCTiming node specified in the manifest. Null if none found
  33855. */
  33856. var parseUTCTimingScheme = function parseUTCTimingScheme(mpd) {
  33857. var UTCTimingNode = findChildren(mpd, 'UTCTiming')[0];
  33858. if (!UTCTimingNode) {
  33859. return null;
  33860. }
  33861. var attributes = parseAttributes(UTCTimingNode);
  33862. switch (attributes.schemeIdUri) {
  33863. case 'urn:mpeg:dash:utc:http-head:2014':
  33864. case 'urn:mpeg:dash:utc:http-head:2012':
  33865. attributes.method = 'HEAD';
  33866. break;
  33867. case 'urn:mpeg:dash:utc:http-xsdate:2014':
  33868. case 'urn:mpeg:dash:utc:http-iso:2014':
  33869. case 'urn:mpeg:dash:utc:http-xsdate:2012':
  33870. case 'urn:mpeg:dash:utc:http-iso:2012':
  33871. attributes.method = 'GET';
  33872. break;
  33873. case 'urn:mpeg:dash:utc:direct:2014':
  33874. case 'urn:mpeg:dash:utc:direct:2012':
  33875. attributes.method = 'DIRECT';
  33876. attributes.value = Date.parse(attributes.value);
  33877. break;
  33878. case 'urn:mpeg:dash:utc:http-ntp:2014':
  33879. case 'urn:mpeg:dash:utc:ntp:2014':
  33880. case 'urn:mpeg:dash:utc:sntp:2014':
  33881. default:
  33882. throw new Error(errors.UNSUPPORTED_UTC_TIMING_SCHEME);
  33883. }
  33884. return attributes;
  33885. };
  33886. /*
  33887. * Given a DASH manifest string and options, parses the DASH manifest into an object in the
  33888. * form outputed by m3u8-parser and accepted by videojs/http-streaming.
  33889. *
  33890. * For live DASH manifests, if `previousManifest` is provided in options, then the newly
  33891. * parsed DASH manifest will have its media sequence and discontinuity sequence values
  33892. * updated to reflect its position relative to the prior manifest.
  33893. *
  33894. * @param {string} manifestString - the DASH manifest as a string
  33895. * @param {options} [options] - any options
  33896. *
  33897. * @return {Object} the manifest object
  33898. */
  33899. var parse = function parse(manifestString, options) {
  33900. if (options === void 0) {
  33901. options = {};
  33902. }
  33903. var parsedManifestInfo = inheritAttributes(stringToMpdXml(manifestString), options);
  33904. var playlists = toPlaylists(parsedManifestInfo.representationInfo);
  33905. return toM3u8({
  33906. dashPlaylists: playlists,
  33907. locations: parsedManifestInfo.locations,
  33908. sidxMapping: options.sidxMapping,
  33909. previousManifest: options.previousManifest
  33910. });
  33911. };
  33912. /**
  33913. * Parses the manifest for a UTCTiming node, returning the nodes attributes if found
  33914. *
  33915. * @param {string} manifestString
  33916. * XML string of the MPD manifest
  33917. * @return {Object|null}
  33918. * Attributes of UTCTiming node specified in the manifest. Null if none found
  33919. */
  33920. var parseUTCTiming = function parseUTCTiming(manifestString) {
  33921. return parseUTCTimingScheme(stringToMpdXml(manifestString));
  33922. };
  33923. var MAX_UINT32 = Math.pow(2, 32);
  33924. var getUint64$1 = function getUint64(uint8) {
  33925. var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
  33926. var value;
  33927. if (dv.getBigUint64) {
  33928. value = dv.getBigUint64(0);
  33929. if (value < Number.MAX_SAFE_INTEGER) {
  33930. return Number(value);
  33931. }
  33932. return value;
  33933. }
  33934. return dv.getUint32(0) * MAX_UINT32 + dv.getUint32(4);
  33935. };
  33936. var numbers = {
  33937. getUint64: getUint64$1,
  33938. MAX_UINT32: MAX_UINT32
  33939. };
  33940. var getUint64 = numbers.getUint64;
  33941. var parseSidx = function parseSidx(data) {
  33942. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  33943. result = {
  33944. version: data[0],
  33945. flags: new Uint8Array(data.subarray(1, 4)),
  33946. references: [],
  33947. referenceId: view.getUint32(4),
  33948. timescale: view.getUint32(8)
  33949. },
  33950. i = 12;
  33951. if (result.version === 0) {
  33952. result.earliestPresentationTime = view.getUint32(i);
  33953. result.firstOffset = view.getUint32(i + 4);
  33954. i += 8;
  33955. } else {
  33956. // read 64 bits
  33957. result.earliestPresentationTime = getUint64(data.subarray(i));
  33958. result.firstOffset = getUint64(data.subarray(i + 8));
  33959. i += 16;
  33960. }
  33961. i += 2; // reserved
  33962. var referenceCount = view.getUint16(i);
  33963. i += 2; // start of references
  33964. for (; referenceCount > 0; i += 12, referenceCount--) {
  33965. result.references.push({
  33966. referenceType: (data[i] & 0x80) >>> 7,
  33967. referencedSize: view.getUint32(i) & 0x7FFFFFFF,
  33968. subsegmentDuration: view.getUint32(i + 4),
  33969. startsWithSap: !!(data[i + 8] & 0x80),
  33970. sapType: (data[i + 8] & 0x70) >>> 4,
  33971. sapDeltaTime: view.getUint32(i + 8) & 0x0FFFFFFF
  33972. });
  33973. }
  33974. return result;
  33975. };
  33976. var parseSidx_1 = parseSidx;
  33977. var ID3 = toUint8([0x49, 0x44, 0x33]);
  33978. var getId3Size = function getId3Size(bytes, offset) {
  33979. if (offset === void 0) {
  33980. offset = 0;
  33981. }
  33982. bytes = toUint8(bytes);
  33983. var flags = bytes[offset + 5];
  33984. var returnSize = bytes[offset + 6] << 21 | bytes[offset + 7] << 14 | bytes[offset + 8] << 7 | bytes[offset + 9];
  33985. var footerPresent = (flags & 16) >> 4;
  33986. if (footerPresent) {
  33987. return returnSize + 20;
  33988. }
  33989. return returnSize + 10;
  33990. };
  33991. var getId3Offset = function getId3Offset(bytes, offset) {
  33992. if (offset === void 0) {
  33993. offset = 0;
  33994. }
  33995. bytes = toUint8(bytes);
  33996. if (bytes.length - offset < 10 || !bytesMatch(bytes, ID3, {
  33997. offset: offset
  33998. })) {
  33999. return offset;
  34000. }
  34001. offset += getId3Size(bytes, offset); // recursive check for id3 tags as some files
  34002. // have multiple ID3 tag sections even though
  34003. // they should not.
  34004. return getId3Offset(bytes, offset);
  34005. };
  34006. var normalizePath$1 = function normalizePath(path) {
  34007. if (typeof path === 'string') {
  34008. return stringToBytes(path);
  34009. }
  34010. if (typeof path === 'number') {
  34011. return path;
  34012. }
  34013. return path;
  34014. };
  34015. var normalizePaths$1 = function normalizePaths(paths) {
  34016. if (!Array.isArray(paths)) {
  34017. return [normalizePath$1(paths)];
  34018. }
  34019. return paths.map(function (p) {
  34020. return normalizePath$1(p);
  34021. });
  34022. };
  34023. /**
  34024. * find any number of boxes by name given a path to it in an iso bmff
  34025. * such as mp4.
  34026. *
  34027. * @param {TypedArray} bytes
  34028. * bytes for the iso bmff to search for boxes in
  34029. *
  34030. * @param {Uint8Array[]|string[]|string|Uint8Array} name
  34031. * An array of paths or a single path representing the name
  34032. * of boxes to search through in bytes. Paths may be
  34033. * uint8 (character codes) or strings.
  34034. *
  34035. * @param {boolean} [complete=false]
  34036. * Should we search only for complete boxes on the final path.
  34037. * This is very useful when you do not want to get back partial boxes
  34038. * in the case of streaming files.
  34039. *
  34040. * @return {Uint8Array[]}
  34041. * An array of the end paths that we found.
  34042. */
  34043. var findBox = function findBox(bytes, paths, complete) {
  34044. if (complete === void 0) {
  34045. complete = false;
  34046. }
  34047. paths = normalizePaths$1(paths);
  34048. bytes = toUint8(bytes);
  34049. var results = [];
  34050. if (!paths.length) {
  34051. // short-circuit the search for empty paths
  34052. return results;
  34053. }
  34054. var i = 0;
  34055. while (i < bytes.length) {
  34056. var size = (bytes[i] << 24 | bytes[i + 1] << 16 | bytes[i + 2] << 8 | bytes[i + 3]) >>> 0;
  34057. var type = bytes.subarray(i + 4, i + 8); // invalid box format.
  34058. if (size === 0) {
  34059. break;
  34060. }
  34061. var end = i + size;
  34062. if (end > bytes.length) {
  34063. // this box is bigger than the number of bytes we have
  34064. // and complete is set, we cannot find any more boxes.
  34065. if (complete) {
  34066. break;
  34067. }
  34068. end = bytes.length;
  34069. }
  34070. var data = bytes.subarray(i + 8, end);
  34071. if (bytesMatch(type, paths[0])) {
  34072. if (paths.length === 1) {
  34073. // this is the end of the path and we've found the box we were
  34074. // looking for
  34075. results.push(data);
  34076. } else {
  34077. // recursively search for the next box along the path
  34078. results.push.apply(results, findBox(data, paths.slice(1), complete));
  34079. }
  34080. }
  34081. i = end;
  34082. } // we've finished searching all of bytes
  34083. return results;
  34084. };
  34085. // https://matroska-org.github.io/libebml/specs.html
  34086. // https://www.matroska.org/technical/elements.html
  34087. // https://www.webmproject.org/docs/container/
  34088. var EBML_TAGS = {
  34089. EBML: toUint8([0x1A, 0x45, 0xDF, 0xA3]),
  34090. DocType: toUint8([0x42, 0x82]),
  34091. Segment: toUint8([0x18, 0x53, 0x80, 0x67]),
  34092. SegmentInfo: toUint8([0x15, 0x49, 0xA9, 0x66]),
  34093. Tracks: toUint8([0x16, 0x54, 0xAE, 0x6B]),
  34094. Track: toUint8([0xAE]),
  34095. TrackNumber: toUint8([0xd7]),
  34096. DefaultDuration: toUint8([0x23, 0xe3, 0x83]),
  34097. TrackEntry: toUint8([0xAE]),
  34098. TrackType: toUint8([0x83]),
  34099. FlagDefault: toUint8([0x88]),
  34100. CodecID: toUint8([0x86]),
  34101. CodecPrivate: toUint8([0x63, 0xA2]),
  34102. VideoTrack: toUint8([0xe0]),
  34103. AudioTrack: toUint8([0xe1]),
  34104. // Not used yet, but will be used for live webm/mkv
  34105. // see https://www.matroska.org/technical/basics.html#block-structure
  34106. // see https://www.matroska.org/technical/basics.html#simpleblock-structure
  34107. Cluster: toUint8([0x1F, 0x43, 0xB6, 0x75]),
  34108. Timestamp: toUint8([0xE7]),
  34109. TimestampScale: toUint8([0x2A, 0xD7, 0xB1]),
  34110. BlockGroup: toUint8([0xA0]),
  34111. BlockDuration: toUint8([0x9B]),
  34112. Block: toUint8([0xA1]),
  34113. SimpleBlock: toUint8([0xA3])
  34114. };
  34115. /**
  34116. * This is a simple table to determine the length
  34117. * of things in ebml. The length is one based (starts at 1,
  34118. * rather than zero) and for every zero bit before a one bit
  34119. * we add one to length. We also need this table because in some
  34120. * case we have to xor all the length bits from another value.
  34121. */
  34122. var LENGTH_TABLE = [128, 64, 32, 16, 8, 4, 2, 1];
  34123. var getLength = function getLength(_byte) {
  34124. var len = 1;
  34125. for (var i = 0; i < LENGTH_TABLE.length; i++) {
  34126. if (_byte & LENGTH_TABLE[i]) {
  34127. break;
  34128. }
  34129. len++;
  34130. }
  34131. return len;
  34132. }; // length in ebml is stored in the first 4 to 8 bits
  34133. // of the first byte. 4 for the id length and 8 for the
  34134. // data size length. Length is measured by converting the number to binary
  34135. // then 1 + the number of zeros before a 1 is encountered starting
  34136. // from the left.
  34137. var getvint = function getvint(bytes, offset, removeLength, signed) {
  34138. if (removeLength === void 0) {
  34139. removeLength = true;
  34140. }
  34141. if (signed === void 0) {
  34142. signed = false;
  34143. }
  34144. var length = getLength(bytes[offset]);
  34145. var valueBytes = bytes.subarray(offset, offset + length); // NOTE that we do **not** subarray here because we need to copy these bytes
  34146. // as they will be modified below to remove the dataSizeLen bits and we do not
  34147. // want to modify the original data. normally we could just call slice on
  34148. // uint8array but ie 11 does not support that...
  34149. if (removeLength) {
  34150. valueBytes = Array.prototype.slice.call(bytes, offset, offset + length);
  34151. valueBytes[0] ^= LENGTH_TABLE[length - 1];
  34152. }
  34153. return {
  34154. length: length,
  34155. value: bytesToNumber(valueBytes, {
  34156. signed: signed
  34157. }),
  34158. bytes: valueBytes
  34159. };
  34160. };
  34161. var normalizePath = function normalizePath(path) {
  34162. if (typeof path === 'string') {
  34163. return path.match(/.{1,2}/g).map(function (p) {
  34164. return normalizePath(p);
  34165. });
  34166. }
  34167. if (typeof path === 'number') {
  34168. return numberToBytes(path);
  34169. }
  34170. return path;
  34171. };
  34172. var normalizePaths = function normalizePaths(paths) {
  34173. if (!Array.isArray(paths)) {
  34174. return [normalizePath(paths)];
  34175. }
  34176. return paths.map(function (p) {
  34177. return normalizePath(p);
  34178. });
  34179. };
  34180. var getInfinityDataSize = function getInfinityDataSize(id, bytes, offset) {
  34181. if (offset >= bytes.length) {
  34182. return bytes.length;
  34183. }
  34184. var innerid = getvint(bytes, offset, false);
  34185. if (bytesMatch(id.bytes, innerid.bytes)) {
  34186. return offset;
  34187. }
  34188. var dataHeader = getvint(bytes, offset + innerid.length);
  34189. return getInfinityDataSize(id, bytes, offset + dataHeader.length + dataHeader.value + innerid.length);
  34190. };
  34191. /**
  34192. * Notes on the EBLM format.
  34193. *
  34194. * EBLM uses "vints" tags. Every vint tag contains
  34195. * two parts
  34196. *
  34197. * 1. The length from the first byte. You get this by
  34198. * converting the byte to binary and counting the zeros
  34199. * before a 1. Then you add 1 to that. Examples
  34200. * 00011111 = length 4 because there are 3 zeros before a 1.
  34201. * 00100000 = length 3 because there are 2 zeros before a 1.
  34202. * 00000011 = length 7 because there are 6 zeros before a 1.
  34203. *
  34204. * 2. The bits used for length are removed from the first byte
  34205. * Then all the bytes are merged into a value. NOTE: this
  34206. * is not the case for id ebml tags as there id includes
  34207. * length bits.
  34208. *
  34209. */
  34210. var findEbml = function findEbml(bytes, paths) {
  34211. paths = normalizePaths(paths);
  34212. bytes = toUint8(bytes);
  34213. var results = [];
  34214. if (!paths.length) {
  34215. return results;
  34216. }
  34217. var i = 0;
  34218. while (i < bytes.length) {
  34219. var id = getvint(bytes, i, false);
  34220. var dataHeader = getvint(bytes, i + id.length);
  34221. var dataStart = i + id.length + dataHeader.length; // dataSize is unknown or this is a live stream
  34222. if (dataHeader.value === 0x7f) {
  34223. dataHeader.value = getInfinityDataSize(id, bytes, dataStart);
  34224. if (dataHeader.value !== bytes.length) {
  34225. dataHeader.value -= dataStart;
  34226. }
  34227. }
  34228. var dataEnd = dataStart + dataHeader.value > bytes.length ? bytes.length : dataStart + dataHeader.value;
  34229. var data = bytes.subarray(dataStart, dataEnd);
  34230. if (bytesMatch(paths[0], id.bytes)) {
  34231. if (paths.length === 1) {
  34232. // this is the end of the paths and we've found the tag we were
  34233. // looking for
  34234. results.push(data);
  34235. } else {
  34236. // recursively search for the next tag inside of the data
  34237. // of this one
  34238. results = results.concat(findEbml(data, paths.slice(1)));
  34239. }
  34240. }
  34241. var totalLength = id.length + dataHeader.length + data.length; // move past this tag entirely, we are not looking for it
  34242. i += totalLength;
  34243. }
  34244. return results;
  34245. }; // see https://www.matroska.org/technical/basics.html#block-structure
  34246. var NAL_TYPE_ONE = toUint8([0x00, 0x00, 0x00, 0x01]);
  34247. var NAL_TYPE_TWO = toUint8([0x00, 0x00, 0x01]);
  34248. var EMULATION_PREVENTION = toUint8([0x00, 0x00, 0x03]);
  34249. /**
  34250. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  34251. * Sequence Payload"
  34252. *
  34253. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  34254. * unit
  34255. * @return {Uint8Array} the RBSP without any Emulation
  34256. * Prevention Bytes
  34257. */
  34258. var discardEmulationPreventionBytes = function discardEmulationPreventionBytes(bytes) {
  34259. var positions = [];
  34260. var i = 1; // Find all `Emulation Prevention Bytes`
  34261. while (i < bytes.length - 2) {
  34262. if (bytesMatch(bytes.subarray(i, i + 3), EMULATION_PREVENTION)) {
  34263. positions.push(i + 2);
  34264. i++;
  34265. }
  34266. i++;
  34267. } // If no Emulation Prevention Bytes were found just return the original
  34268. // array
  34269. if (positions.length === 0) {
  34270. return bytes;
  34271. } // Create a new array to hold the NAL unit data
  34272. var newLength = bytes.length - positions.length;
  34273. var newData = new Uint8Array(newLength);
  34274. var sourceIndex = 0;
  34275. for (i = 0; i < newLength; sourceIndex++, i++) {
  34276. if (sourceIndex === positions[0]) {
  34277. // Skip this byte
  34278. sourceIndex++; // Remove this position index
  34279. positions.shift();
  34280. }
  34281. newData[i] = bytes[sourceIndex];
  34282. }
  34283. return newData;
  34284. };
  34285. var findNal = function findNal(bytes, dataType, types, nalLimit) {
  34286. if (nalLimit === void 0) {
  34287. nalLimit = Infinity;
  34288. }
  34289. bytes = toUint8(bytes);
  34290. types = [].concat(types);
  34291. var i = 0;
  34292. var nalStart;
  34293. var nalsFound = 0; // keep searching until:
  34294. // we reach the end of bytes
  34295. // we reach the maximum number of nals they want to seach
  34296. // NOTE: that we disregard nalLimit when we have found the start
  34297. // of the nal we want so that we can find the end of the nal we want.
  34298. while (i < bytes.length && (nalsFound < nalLimit || nalStart)) {
  34299. var nalOffset = void 0;
  34300. if (bytesMatch(bytes.subarray(i), NAL_TYPE_ONE)) {
  34301. nalOffset = 4;
  34302. } else if (bytesMatch(bytes.subarray(i), NAL_TYPE_TWO)) {
  34303. nalOffset = 3;
  34304. } // we are unsynced,
  34305. // find the next nal unit
  34306. if (!nalOffset) {
  34307. i++;
  34308. continue;
  34309. }
  34310. nalsFound++;
  34311. if (nalStart) {
  34312. return discardEmulationPreventionBytes(bytes.subarray(nalStart, i));
  34313. }
  34314. var nalType = void 0;
  34315. if (dataType === 'h264') {
  34316. nalType = bytes[i + nalOffset] & 0x1f;
  34317. } else if (dataType === 'h265') {
  34318. nalType = bytes[i + nalOffset] >> 1 & 0x3f;
  34319. }
  34320. if (types.indexOf(nalType) !== -1) {
  34321. nalStart = i + nalOffset;
  34322. } // nal header is 1 length for h264, and 2 for h265
  34323. i += nalOffset + (dataType === 'h264' ? 1 : 2);
  34324. }
  34325. return bytes.subarray(0, 0);
  34326. };
  34327. var findH264Nal = function findH264Nal(bytes, type, nalLimit) {
  34328. return findNal(bytes, 'h264', type, nalLimit);
  34329. };
  34330. var findH265Nal = function findH265Nal(bytes, type, nalLimit) {
  34331. return findNal(bytes, 'h265', type, nalLimit);
  34332. };
  34333. var CONSTANTS = {
  34334. // "webm" string literal in hex
  34335. 'webm': toUint8([0x77, 0x65, 0x62, 0x6d]),
  34336. // "matroska" string literal in hex
  34337. 'matroska': toUint8([0x6d, 0x61, 0x74, 0x72, 0x6f, 0x73, 0x6b, 0x61]),
  34338. // "fLaC" string literal in hex
  34339. 'flac': toUint8([0x66, 0x4c, 0x61, 0x43]),
  34340. // "OggS" string literal in hex
  34341. 'ogg': toUint8([0x4f, 0x67, 0x67, 0x53]),
  34342. // ac-3 sync byte, also works for ec-3 as that is simply a codec
  34343. // of ac-3
  34344. 'ac3': toUint8([0x0b, 0x77]),
  34345. // "RIFF" string literal in hex used for wav and avi
  34346. 'riff': toUint8([0x52, 0x49, 0x46, 0x46]),
  34347. // "AVI" string literal in hex
  34348. 'avi': toUint8([0x41, 0x56, 0x49]),
  34349. // "WAVE" string literal in hex
  34350. 'wav': toUint8([0x57, 0x41, 0x56, 0x45]),
  34351. // "ftyp3g" string literal in hex
  34352. '3gp': toUint8([0x66, 0x74, 0x79, 0x70, 0x33, 0x67]),
  34353. // "ftyp" string literal in hex
  34354. 'mp4': toUint8([0x66, 0x74, 0x79, 0x70]),
  34355. // "styp" string literal in hex
  34356. 'fmp4': toUint8([0x73, 0x74, 0x79, 0x70]),
  34357. // "ftypqt" string literal in hex
  34358. 'mov': toUint8([0x66, 0x74, 0x79, 0x70, 0x71, 0x74]),
  34359. // moov string literal in hex
  34360. 'moov': toUint8([0x6D, 0x6F, 0x6F, 0x76]),
  34361. // moof string literal in hex
  34362. 'moof': toUint8([0x6D, 0x6F, 0x6F, 0x66])
  34363. };
  34364. var _isLikely = {
  34365. aac: function aac(bytes) {
  34366. var offset = getId3Offset(bytes);
  34367. return bytesMatch(bytes, [0xFF, 0x10], {
  34368. offset: offset,
  34369. mask: [0xFF, 0x16]
  34370. });
  34371. },
  34372. mp3: function mp3(bytes) {
  34373. var offset = getId3Offset(bytes);
  34374. return bytesMatch(bytes, [0xFF, 0x02], {
  34375. offset: offset,
  34376. mask: [0xFF, 0x06]
  34377. });
  34378. },
  34379. webm: function webm(bytes) {
  34380. var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is webm
  34381. return bytesMatch(docType, CONSTANTS.webm);
  34382. },
  34383. mkv: function mkv(bytes) {
  34384. var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is matroska
  34385. return bytesMatch(docType, CONSTANTS.matroska);
  34386. },
  34387. mp4: function mp4(bytes) {
  34388. // if this file is another base media file format, it is not mp4
  34389. if (_isLikely['3gp'](bytes) || _isLikely.mov(bytes)) {
  34390. return false;
  34391. } // if this file starts with a ftyp or styp box its mp4
  34392. if (bytesMatch(bytes, CONSTANTS.mp4, {
  34393. offset: 4
  34394. }) || bytesMatch(bytes, CONSTANTS.fmp4, {
  34395. offset: 4
  34396. })) {
  34397. return true;
  34398. } // if this file starts with a moof/moov box its mp4
  34399. if (bytesMatch(bytes, CONSTANTS.moof, {
  34400. offset: 4
  34401. }) || bytesMatch(bytes, CONSTANTS.moov, {
  34402. offset: 4
  34403. })) {
  34404. return true;
  34405. }
  34406. },
  34407. mov: function mov(bytes) {
  34408. return bytesMatch(bytes, CONSTANTS.mov, {
  34409. offset: 4
  34410. });
  34411. },
  34412. '3gp': function gp(bytes) {
  34413. return bytesMatch(bytes, CONSTANTS['3gp'], {
  34414. offset: 4
  34415. });
  34416. },
  34417. ac3: function ac3(bytes) {
  34418. var offset = getId3Offset(bytes);
  34419. return bytesMatch(bytes, CONSTANTS.ac3, {
  34420. offset: offset
  34421. });
  34422. },
  34423. ts: function ts(bytes) {
  34424. if (bytes.length < 189 && bytes.length >= 1) {
  34425. return bytes[0] === 0x47;
  34426. }
  34427. var i = 0; // check the first 376 bytes for two matching sync bytes
  34428. while (i + 188 < bytes.length && i < 188) {
  34429. if (bytes[i] === 0x47 && bytes[i + 188] === 0x47) {
  34430. return true;
  34431. }
  34432. i += 1;
  34433. }
  34434. return false;
  34435. },
  34436. flac: function flac(bytes) {
  34437. var offset = getId3Offset(bytes);
  34438. return bytesMatch(bytes, CONSTANTS.flac, {
  34439. offset: offset
  34440. });
  34441. },
  34442. ogg: function ogg(bytes) {
  34443. return bytesMatch(bytes, CONSTANTS.ogg);
  34444. },
  34445. avi: function avi(bytes) {
  34446. return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.avi, {
  34447. offset: 8
  34448. });
  34449. },
  34450. wav: function wav(bytes) {
  34451. return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.wav, {
  34452. offset: 8
  34453. });
  34454. },
  34455. 'h264': function h264(bytes) {
  34456. // find seq_parameter_set_rbsp
  34457. return findH264Nal(bytes, 7, 3).length;
  34458. },
  34459. 'h265': function h265(bytes) {
  34460. // find video_parameter_set_rbsp or seq_parameter_set_rbsp
  34461. return findH265Nal(bytes, [32, 33], 3).length;
  34462. }
  34463. }; // get all the isLikely functions
  34464. // but make sure 'ts' is above h264 and h265
  34465. // but below everything else as it is the least specific
  34466. var isLikelyTypes = Object.keys(_isLikely) // remove ts, h264, h265
  34467. .filter(function (t) {
  34468. return t !== 'ts' && t !== 'h264' && t !== 'h265';
  34469. }) // add it back to the bottom
  34470. .concat(['ts', 'h264', 'h265']); // make sure we are dealing with uint8 data.
  34471. isLikelyTypes.forEach(function (type) {
  34472. var isLikelyFn = _isLikely[type];
  34473. _isLikely[type] = function (bytes) {
  34474. return isLikelyFn(toUint8(bytes));
  34475. };
  34476. }); // export after wrapping
  34477. var isLikely = _isLikely; // A useful list of file signatures can be found here
  34478. // https://en.wikipedia.org/wiki/List_of_file_signatures
  34479. var detectContainerForBytes = function detectContainerForBytes(bytes) {
  34480. bytes = toUint8(bytes);
  34481. for (var i = 0; i < isLikelyTypes.length; i++) {
  34482. var type = isLikelyTypes[i];
  34483. if (isLikely[type](bytes)) {
  34484. return type;
  34485. }
  34486. }
  34487. return '';
  34488. }; // fmp4 is not a container
  34489. var isLikelyFmp4MediaSegment = function isLikelyFmp4MediaSegment(bytes) {
  34490. return findBox(bytes, ['moof']).length > 0;
  34491. };
  34492. /**
  34493. * mux.js
  34494. *
  34495. * Copyright (c) Brightcove
  34496. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  34497. */
  34498. var ONE_SECOND_IN_TS = 90000,
  34499. // 90kHz clock
  34500. secondsToVideoTs,
  34501. secondsToAudioTs,
  34502. videoTsToSeconds,
  34503. audioTsToSeconds,
  34504. audioTsToVideoTs,
  34505. videoTsToAudioTs,
  34506. metadataTsToSeconds;
  34507. secondsToVideoTs = function secondsToVideoTs(seconds) {
  34508. return seconds * ONE_SECOND_IN_TS;
  34509. };
  34510. secondsToAudioTs = function secondsToAudioTs(seconds, sampleRate) {
  34511. return seconds * sampleRate;
  34512. };
  34513. videoTsToSeconds = function videoTsToSeconds(timestamp) {
  34514. return timestamp / ONE_SECOND_IN_TS;
  34515. };
  34516. audioTsToSeconds = function audioTsToSeconds(timestamp, sampleRate) {
  34517. return timestamp / sampleRate;
  34518. };
  34519. audioTsToVideoTs = function audioTsToVideoTs(timestamp, sampleRate) {
  34520. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  34521. };
  34522. videoTsToAudioTs = function videoTsToAudioTs(timestamp, sampleRate) {
  34523. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  34524. };
  34525. /**
  34526. * Adjust ID3 tag or caption timing information by the timeline pts values
  34527. * (if keepOriginalTimestamps is false) and convert to seconds
  34528. */
  34529. metadataTsToSeconds = function metadataTsToSeconds(timestamp, timelineStartPts, keepOriginalTimestamps) {
  34530. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  34531. };
  34532. var clock = {
  34533. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS,
  34534. secondsToVideoTs: secondsToVideoTs,
  34535. secondsToAudioTs: secondsToAudioTs,
  34536. videoTsToSeconds: videoTsToSeconds,
  34537. audioTsToSeconds: audioTsToSeconds,
  34538. audioTsToVideoTs: audioTsToVideoTs,
  34539. videoTsToAudioTs: videoTsToAudioTs,
  34540. metadataTsToSeconds: metadataTsToSeconds
  34541. };
  34542. var clock_1 = clock.ONE_SECOND_IN_TS;
  34543. var getPrototypeOf = createCommonjsModule(function (module) {
  34544. function _getPrototypeOf(o) {
  34545. module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  34546. return o.__proto__ || Object.getPrototypeOf(o);
  34547. };
  34548. return _getPrototypeOf(o);
  34549. }
  34550. module.exports = _getPrototypeOf;
  34551. });
  34552. function _isNativeFunction(fn) {
  34553. return Function.toString.call(fn).indexOf("[native code]") !== -1;
  34554. }
  34555. var isNativeFunction = _isNativeFunction;
  34556. var wrapNativeSuper = createCommonjsModule(function (module) {
  34557. function _wrapNativeSuper(Class) {
  34558. var _cache = typeof Map === "function" ? new Map() : undefined;
  34559. module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) {
  34560. if (Class === null || !isNativeFunction(Class)) return Class;
  34561. if (typeof Class !== "function") {
  34562. throw new TypeError("Super expression must either be null or a function");
  34563. }
  34564. if (typeof _cache !== "undefined") {
  34565. if (_cache.has(Class)) return _cache.get(Class);
  34566. _cache.set(Class, Wrapper);
  34567. }
  34568. function Wrapper() {
  34569. return construct(Class, arguments, getPrototypeOf(this).constructor);
  34570. }
  34571. Wrapper.prototype = Object.create(Class.prototype, {
  34572. constructor: {
  34573. value: Wrapper,
  34574. enumerable: false,
  34575. writable: true,
  34576. configurable: true
  34577. }
  34578. });
  34579. return setPrototypeOf(Wrapper, Class);
  34580. };
  34581. return _wrapNativeSuper(Class);
  34582. }
  34583. module.exports = _wrapNativeSuper;
  34584. });
  34585. /*! @name @videojs/http-streaming @version 2.16.2 @license Apache-2.0 */
  34586. /**
  34587. * @file resolve-url.js - Handling how URLs are resolved and manipulated
  34588. */
  34589. var resolveUrl = resolveUrl$2;
  34590. /**
  34591. * Checks whether xhr request was redirected and returns correct url depending
  34592. * on `handleManifestRedirects` option
  34593. *
  34594. * @api private
  34595. *
  34596. * @param {string} url - an url being requested
  34597. * @param {XMLHttpRequest} req - xhr request result
  34598. *
  34599. * @return {string}
  34600. */
  34601. var resolveManifestRedirect = function resolveManifestRedirect(handleManifestRedirect, url, req) {
  34602. // To understand how the responseURL below is set and generated:
  34603. // - https://fetch.spec.whatwg.org/#concept-response-url
  34604. // - https://fetch.spec.whatwg.org/#atomic-http-redirect-handling
  34605. if (handleManifestRedirect && req && req.responseURL && url !== req.responseURL) {
  34606. return req.responseURL;
  34607. }
  34608. return url;
  34609. };
  34610. var logger = function logger(source) {
  34611. if (videojs.log.debug) {
  34612. return videojs.log.debug.bind(videojs, 'VHS:', source + " >");
  34613. }
  34614. return function () {};
  34615. };
  34616. /**
  34617. * ranges
  34618. *
  34619. * Utilities for working with TimeRanges.
  34620. *
  34621. */
  34622. var TIME_FUDGE_FACTOR = 1 / 30; // Comparisons between time values such as current time and the end of the buffered range
  34623. // can be misleading because of precision differences or when the current media has poorly
  34624. // aligned audio and video, which can cause values to be slightly off from what you would
  34625. // expect. This value is what we consider to be safe to use in such comparisons to account
  34626. // for these scenarios.
  34627. var SAFE_TIME_DELTA = TIME_FUDGE_FACTOR * 3;
  34628. var filterRanges = function filterRanges(timeRanges, predicate) {
  34629. var results = [];
  34630. var i;
  34631. if (timeRanges && timeRanges.length) {
  34632. // Search for ranges that match the predicate
  34633. for (i = 0; i < timeRanges.length; i++) {
  34634. if (predicate(timeRanges.start(i), timeRanges.end(i))) {
  34635. results.push([timeRanges.start(i), timeRanges.end(i)]);
  34636. }
  34637. }
  34638. }
  34639. return videojs.createTimeRanges(results);
  34640. };
  34641. /**
  34642. * Attempts to find the buffered TimeRange that contains the specified
  34643. * time.
  34644. *
  34645. * @param {TimeRanges} buffered - the TimeRanges object to query
  34646. * @param {number} time - the time to filter on.
  34647. * @return {TimeRanges} a new TimeRanges object
  34648. */
  34649. var findRange = function findRange(buffered, time) {
  34650. return filterRanges(buffered, function (start, end) {
  34651. return start - SAFE_TIME_DELTA <= time && end + SAFE_TIME_DELTA >= time;
  34652. });
  34653. };
  34654. /**
  34655. * Returns the TimeRanges that begin later than the specified time.
  34656. *
  34657. * @param {TimeRanges} timeRanges - the TimeRanges object to query
  34658. * @param {number} time - the time to filter on.
  34659. * @return {TimeRanges} a new TimeRanges object.
  34660. */
  34661. var findNextRange = function findNextRange(timeRanges, time) {
  34662. return filterRanges(timeRanges, function (start) {
  34663. return start - TIME_FUDGE_FACTOR >= time;
  34664. });
  34665. };
  34666. /**
  34667. * Returns gaps within a list of TimeRanges
  34668. *
  34669. * @param {TimeRanges} buffered - the TimeRanges object
  34670. * @return {TimeRanges} a TimeRanges object of gaps
  34671. */
  34672. var findGaps = function findGaps(buffered) {
  34673. if (buffered.length < 2) {
  34674. return videojs.createTimeRanges();
  34675. }
  34676. var ranges = [];
  34677. for (var i = 1; i < buffered.length; i++) {
  34678. var start = buffered.end(i - 1);
  34679. var end = buffered.start(i);
  34680. ranges.push([start, end]);
  34681. }
  34682. return videojs.createTimeRanges(ranges);
  34683. };
  34684. /**
  34685. * Calculate the intersection of two TimeRanges
  34686. *
  34687. * @param {TimeRanges} bufferA
  34688. * @param {TimeRanges} bufferB
  34689. * @return {TimeRanges} The interesection of `bufferA` with `bufferB`
  34690. */
  34691. var bufferIntersection = function bufferIntersection(bufferA, bufferB) {
  34692. var start = null;
  34693. var end = null;
  34694. var arity = 0;
  34695. var extents = [];
  34696. var ranges = [];
  34697. if (!bufferA || !bufferA.length || !bufferB || !bufferB.length) {
  34698. return videojs.createTimeRange();
  34699. } // Handle the case where we have both buffers and create an
  34700. // intersection of the two
  34701. var count = bufferA.length; // A) Gather up all start and end times
  34702. while (count--) {
  34703. extents.push({
  34704. time: bufferA.start(count),
  34705. type: 'start'
  34706. });
  34707. extents.push({
  34708. time: bufferA.end(count),
  34709. type: 'end'
  34710. });
  34711. }
  34712. count = bufferB.length;
  34713. while (count--) {
  34714. extents.push({
  34715. time: bufferB.start(count),
  34716. type: 'start'
  34717. });
  34718. extents.push({
  34719. time: bufferB.end(count),
  34720. type: 'end'
  34721. });
  34722. } // B) Sort them by time
  34723. extents.sort(function (a, b) {
  34724. return a.time - b.time;
  34725. }); // C) Go along one by one incrementing arity for start and decrementing
  34726. // arity for ends
  34727. for (count = 0; count < extents.length; count++) {
  34728. if (extents[count].type === 'start') {
  34729. arity++; // D) If arity is ever incremented to 2 we are entering an
  34730. // overlapping range
  34731. if (arity === 2) {
  34732. start = extents[count].time;
  34733. }
  34734. } else if (extents[count].type === 'end') {
  34735. arity--; // E) If arity is ever decremented to 1 we leaving an
  34736. // overlapping range
  34737. if (arity === 1) {
  34738. end = extents[count].time;
  34739. }
  34740. } // F) Record overlapping ranges
  34741. if (start !== null && end !== null) {
  34742. ranges.push([start, end]);
  34743. start = null;
  34744. end = null;
  34745. }
  34746. }
  34747. return videojs.createTimeRanges(ranges);
  34748. };
  34749. /**
  34750. * Gets a human readable string for a TimeRange
  34751. *
  34752. * @param {TimeRange} range
  34753. * @return {string} a human readable string
  34754. */
  34755. var printableRange = function printableRange(range) {
  34756. var strArr = [];
  34757. if (!range || !range.length) {
  34758. return '';
  34759. }
  34760. for (var i = 0; i < range.length; i++) {
  34761. strArr.push(range.start(i) + ' => ' + range.end(i));
  34762. }
  34763. return strArr.join(', ');
  34764. };
  34765. /**
  34766. * Calculates the amount of time left in seconds until the player hits the end of the
  34767. * buffer and causes a rebuffer
  34768. *
  34769. * @param {TimeRange} buffered
  34770. * The state of the buffer
  34771. * @param {Numnber} currentTime
  34772. * The current time of the player
  34773. * @param {number} playbackRate
  34774. * The current playback rate of the player. Defaults to 1.
  34775. * @return {number}
  34776. * Time until the player has to start rebuffering in seconds.
  34777. * @function timeUntilRebuffer
  34778. */
  34779. var timeUntilRebuffer = function timeUntilRebuffer(buffered, currentTime, playbackRate) {
  34780. if (playbackRate === void 0) {
  34781. playbackRate = 1;
  34782. }
  34783. var bufferedEnd = buffered.length ? buffered.end(buffered.length - 1) : 0;
  34784. return (bufferedEnd - currentTime) / playbackRate;
  34785. };
  34786. /**
  34787. * Converts a TimeRanges object into an array representation
  34788. *
  34789. * @param {TimeRanges} timeRanges
  34790. * @return {Array}
  34791. */
  34792. var timeRangesToArray = function timeRangesToArray(timeRanges) {
  34793. var timeRangesList = [];
  34794. for (var i = 0; i < timeRanges.length; i++) {
  34795. timeRangesList.push({
  34796. start: timeRanges.start(i),
  34797. end: timeRanges.end(i)
  34798. });
  34799. }
  34800. return timeRangesList;
  34801. };
  34802. /**
  34803. * Determines if two time range objects are different.
  34804. *
  34805. * @param {TimeRange} a
  34806. * the first time range object to check
  34807. *
  34808. * @param {TimeRange} b
  34809. * the second time range object to check
  34810. *
  34811. * @return {Boolean}
  34812. * Whether the time range objects differ
  34813. */
  34814. var isRangeDifferent = function isRangeDifferent(a, b) {
  34815. // same object
  34816. if (a === b) {
  34817. return false;
  34818. } // one or the other is undefined
  34819. if (!a && b || !b && a) {
  34820. return true;
  34821. } // length is different
  34822. if (a.length !== b.length) {
  34823. return true;
  34824. } // see if any start/end pair is different
  34825. for (var i = 0; i < a.length; i++) {
  34826. if (a.start(i) !== b.start(i) || a.end(i) !== b.end(i)) {
  34827. return true;
  34828. }
  34829. } // if the length and every pair is the same
  34830. // this is the same time range
  34831. return false;
  34832. };
  34833. var lastBufferedEnd = function lastBufferedEnd(a) {
  34834. if (!a || !a.length || !a.end) {
  34835. return;
  34836. }
  34837. return a.end(a.length - 1);
  34838. };
  34839. /**
  34840. * A utility function to add up the amount of time in a timeRange
  34841. * after a specified startTime.
  34842. * ie:[[0, 10], [20, 40], [50, 60]] with a startTime 0
  34843. * would return 40 as there are 40s seconds after 0 in the timeRange
  34844. *
  34845. * @param {TimeRange} range
  34846. * The range to check against
  34847. * @param {number} startTime
  34848. * The time in the time range that you should start counting from
  34849. *
  34850. * @return {number}
  34851. * The number of seconds in the buffer passed the specified time.
  34852. */
  34853. var timeAheadOf = function timeAheadOf(range, startTime) {
  34854. var time = 0;
  34855. if (!range || !range.length) {
  34856. return time;
  34857. }
  34858. for (var i = 0; i < range.length; i++) {
  34859. var start = range.start(i);
  34860. var end = range.end(i); // startTime is after this range entirely
  34861. if (startTime > end) {
  34862. continue;
  34863. } // startTime is within this range
  34864. if (startTime > start && startTime <= end) {
  34865. time += end - startTime;
  34866. continue;
  34867. } // startTime is before this range.
  34868. time += end - start;
  34869. }
  34870. return time;
  34871. };
  34872. /**
  34873. * @file playlist.js
  34874. *
  34875. * Playlist related utilities.
  34876. */
  34877. var createTimeRange = videojs.createTimeRange;
  34878. /**
  34879. * Get the duration of a segment, with special cases for
  34880. * llhls segments that do not have a duration yet.
  34881. *
  34882. * @param {Object} playlist
  34883. * the playlist that the segment belongs to.
  34884. * @param {Object} segment
  34885. * the segment to get a duration for.
  34886. *
  34887. * @return {number}
  34888. * the segment duration
  34889. */
  34890. var segmentDurationWithParts = function segmentDurationWithParts(playlist, segment) {
  34891. // if this isn't a preload segment
  34892. // then we will have a segment duration that is accurate.
  34893. if (!segment.preload) {
  34894. return segment.duration;
  34895. } // otherwise we have to add up parts and preload hints
  34896. // to get an up to date duration.
  34897. var result = 0;
  34898. (segment.parts || []).forEach(function (p) {
  34899. result += p.duration;
  34900. }); // for preload hints we have to use partTargetDuration
  34901. // as they won't even have a duration yet.
  34902. (segment.preloadHints || []).forEach(function (p) {
  34903. if (p.type === 'PART') {
  34904. result += playlist.partTargetDuration;
  34905. }
  34906. });
  34907. return result;
  34908. };
  34909. /**
  34910. * A function to get a combined list of parts and segments with durations
  34911. * and indexes.
  34912. *
  34913. * @param {Playlist} playlist the playlist to get the list for.
  34914. *
  34915. * @return {Array} The part/segment list.
  34916. */
  34917. var getPartsAndSegments = function getPartsAndSegments(playlist) {
  34918. return (playlist.segments || []).reduce(function (acc, segment, si) {
  34919. if (segment.parts) {
  34920. segment.parts.forEach(function (part, pi) {
  34921. acc.push({
  34922. duration: part.duration,
  34923. segmentIndex: si,
  34924. partIndex: pi,
  34925. part: part,
  34926. segment: segment
  34927. });
  34928. });
  34929. } else {
  34930. acc.push({
  34931. duration: segment.duration,
  34932. segmentIndex: si,
  34933. partIndex: null,
  34934. segment: segment,
  34935. part: null
  34936. });
  34937. }
  34938. return acc;
  34939. }, []);
  34940. };
  34941. var getLastParts = function getLastParts(media) {
  34942. var lastSegment = media.segments && media.segments.length && media.segments[media.segments.length - 1];
  34943. return lastSegment && lastSegment.parts || [];
  34944. };
  34945. var getKnownPartCount = function getKnownPartCount(_ref) {
  34946. var preloadSegment = _ref.preloadSegment;
  34947. if (!preloadSegment) {
  34948. return;
  34949. }
  34950. var parts = preloadSegment.parts,
  34951. preloadHints = preloadSegment.preloadHints;
  34952. var partCount = (preloadHints || []).reduce(function (count, hint) {
  34953. return count + (hint.type === 'PART' ? 1 : 0);
  34954. }, 0);
  34955. partCount += parts && parts.length ? parts.length : 0;
  34956. return partCount;
  34957. };
  34958. /**
  34959. * Get the number of seconds to delay from the end of a
  34960. * live playlist.
  34961. *
  34962. * @param {Playlist} master the master playlist
  34963. * @param {Playlist} media the media playlist
  34964. * @return {number} the hold back in seconds.
  34965. */
  34966. var liveEdgeDelay = function liveEdgeDelay(master, media) {
  34967. if (media.endList) {
  34968. return 0;
  34969. } // dash suggestedPresentationDelay trumps everything
  34970. if (master && master.suggestedPresentationDelay) {
  34971. return master.suggestedPresentationDelay;
  34972. }
  34973. var hasParts = getLastParts(media).length > 0; // look for "part" delays from ll-hls first
  34974. if (hasParts && media.serverControl && media.serverControl.partHoldBack) {
  34975. return media.serverControl.partHoldBack;
  34976. } else if (hasParts && media.partTargetDuration) {
  34977. return media.partTargetDuration * 3; // finally look for full segment delays
  34978. } else if (media.serverControl && media.serverControl.holdBack) {
  34979. return media.serverControl.holdBack;
  34980. } else if (media.targetDuration) {
  34981. return media.targetDuration * 3;
  34982. }
  34983. return 0;
  34984. };
  34985. /**
  34986. * walk backward until we find a duration we can use
  34987. * or return a failure
  34988. *
  34989. * @param {Playlist} playlist the playlist to walk through
  34990. * @param {Number} endSequence the mediaSequence to stop walking on
  34991. */
  34992. var backwardDuration = function backwardDuration(playlist, endSequence) {
  34993. var result = 0;
  34994. var i = endSequence - playlist.mediaSequence; // if a start time is available for segment immediately following
  34995. // the interval, use it
  34996. var segment = playlist.segments[i]; // Walk backward until we find the latest segment with timeline
  34997. // information that is earlier than endSequence
  34998. if (segment) {
  34999. if (typeof segment.start !== 'undefined') {
  35000. return {
  35001. result: segment.start,
  35002. precise: true
  35003. };
  35004. }
  35005. if (typeof segment.end !== 'undefined') {
  35006. return {
  35007. result: segment.end - segment.duration,
  35008. precise: true
  35009. };
  35010. }
  35011. }
  35012. while (i--) {
  35013. segment = playlist.segments[i];
  35014. if (typeof segment.end !== 'undefined') {
  35015. return {
  35016. result: result + segment.end,
  35017. precise: true
  35018. };
  35019. }
  35020. result += segmentDurationWithParts(playlist, segment);
  35021. if (typeof segment.start !== 'undefined') {
  35022. return {
  35023. result: result + segment.start,
  35024. precise: true
  35025. };
  35026. }
  35027. }
  35028. return {
  35029. result: result,
  35030. precise: false
  35031. };
  35032. };
  35033. /**
  35034. * walk forward until we find a duration we can use
  35035. * or return a failure
  35036. *
  35037. * @param {Playlist} playlist the playlist to walk through
  35038. * @param {number} endSequence the mediaSequence to stop walking on
  35039. */
  35040. var forwardDuration = function forwardDuration(playlist, endSequence) {
  35041. var result = 0;
  35042. var segment;
  35043. var i = endSequence - playlist.mediaSequence; // Walk forward until we find the earliest segment with timeline
  35044. // information
  35045. for (; i < playlist.segments.length; i++) {
  35046. segment = playlist.segments[i];
  35047. if (typeof segment.start !== 'undefined') {
  35048. return {
  35049. result: segment.start - result,
  35050. precise: true
  35051. };
  35052. }
  35053. result += segmentDurationWithParts(playlist, segment);
  35054. if (typeof segment.end !== 'undefined') {
  35055. return {
  35056. result: segment.end - result,
  35057. precise: true
  35058. };
  35059. }
  35060. } // indicate we didn't find a useful duration estimate
  35061. return {
  35062. result: -1,
  35063. precise: false
  35064. };
  35065. };
  35066. /**
  35067. * Calculate the media duration from the segments associated with a
  35068. * playlist. The duration of a subinterval of the available segments
  35069. * may be calculated by specifying an end index.
  35070. *
  35071. * @param {Object} playlist a media playlist object
  35072. * @param {number=} endSequence an exclusive upper boundary
  35073. * for the playlist. Defaults to playlist length.
  35074. * @param {number} expired the amount of time that has dropped
  35075. * off the front of the playlist in a live scenario
  35076. * @return {number} the duration between the first available segment
  35077. * and end index.
  35078. */
  35079. var intervalDuration = function intervalDuration(playlist, endSequence, expired) {
  35080. if (typeof endSequence === 'undefined') {
  35081. endSequence = playlist.mediaSequence + playlist.segments.length;
  35082. }
  35083. if (endSequence < playlist.mediaSequence) {
  35084. return 0;
  35085. } // do a backward walk to estimate the duration
  35086. var backward = backwardDuration(playlist, endSequence);
  35087. if (backward.precise) {
  35088. // if we were able to base our duration estimate on timing
  35089. // information provided directly from the Media Source, return
  35090. // it
  35091. return backward.result;
  35092. } // walk forward to see if a precise duration estimate can be made
  35093. // that way
  35094. var forward = forwardDuration(playlist, endSequence);
  35095. if (forward.precise) {
  35096. // we found a segment that has been buffered and so it's
  35097. // position is known precisely
  35098. return forward.result;
  35099. } // return the less-precise, playlist-based duration estimate
  35100. return backward.result + expired;
  35101. };
  35102. /**
  35103. * Calculates the duration of a playlist. If a start and end index
  35104. * are specified, the duration will be for the subset of the media
  35105. * timeline between those two indices. The total duration for live
  35106. * playlists is always Infinity.
  35107. *
  35108. * @param {Object} playlist a media playlist object
  35109. * @param {number=} endSequence an exclusive upper
  35110. * boundary for the playlist. Defaults to the playlist media
  35111. * sequence number plus its length.
  35112. * @param {number=} expired the amount of time that has
  35113. * dropped off the front of the playlist in a live scenario
  35114. * @return {number} the duration between the start index and end
  35115. * index.
  35116. */
  35117. var duration = function duration(playlist, endSequence, expired) {
  35118. if (!playlist) {
  35119. return 0;
  35120. }
  35121. if (typeof expired !== 'number') {
  35122. expired = 0;
  35123. } // if a slice of the total duration is not requested, use
  35124. // playlist-level duration indicators when they're present
  35125. if (typeof endSequence === 'undefined') {
  35126. // if present, use the duration specified in the playlist
  35127. if (playlist.totalDuration) {
  35128. return playlist.totalDuration;
  35129. } // duration should be Infinity for live playlists
  35130. if (!playlist.endList) {
  35131. return window.Infinity;
  35132. }
  35133. } // calculate the total duration based on the segment durations
  35134. return intervalDuration(playlist, endSequence, expired);
  35135. };
  35136. /**
  35137. * Calculate the time between two indexes in the current playlist
  35138. * neight the start- nor the end-index need to be within the current
  35139. * playlist in which case, the targetDuration of the playlist is used
  35140. * to approximate the durations of the segments
  35141. *
  35142. * @param {Array} options.durationList list to iterate over for durations.
  35143. * @param {number} options.defaultDuration duration to use for elements before or after the durationList
  35144. * @param {number} options.startIndex partsAndSegments index to start
  35145. * @param {number} options.endIndex partsAndSegments index to end.
  35146. * @return {number} the number of seconds between startIndex and endIndex
  35147. */
  35148. var sumDurations = function sumDurations(_ref2) {
  35149. var defaultDuration = _ref2.defaultDuration,
  35150. durationList = _ref2.durationList,
  35151. startIndex = _ref2.startIndex,
  35152. endIndex = _ref2.endIndex;
  35153. var durations = 0;
  35154. if (startIndex > endIndex) {
  35155. var _ref3 = [endIndex, startIndex];
  35156. startIndex = _ref3[0];
  35157. endIndex = _ref3[1];
  35158. }
  35159. if (startIndex < 0) {
  35160. for (var i = startIndex; i < Math.min(0, endIndex); i++) {
  35161. durations += defaultDuration;
  35162. }
  35163. startIndex = 0;
  35164. }
  35165. for (var _i = startIndex; _i < endIndex; _i++) {
  35166. durations += durationList[_i].duration;
  35167. }
  35168. return durations;
  35169. };
  35170. /**
  35171. * Calculates the playlist end time
  35172. *
  35173. * @param {Object} playlist a media playlist object
  35174. * @param {number=} expired the amount of time that has
  35175. * dropped off the front of the playlist in a live scenario
  35176. * @param {boolean|false} useSafeLiveEnd a boolean value indicating whether or not the
  35177. * playlist end calculation should consider the safe live end
  35178. * (truncate the playlist end by three segments). This is normally
  35179. * used for calculating the end of the playlist's seekable range.
  35180. * This takes into account the value of liveEdgePadding.
  35181. * Setting liveEdgePadding to 0 is equivalent to setting this to false.
  35182. * @param {number} liveEdgePadding a number indicating how far from the end of the playlist we should be in seconds.
  35183. * If this is provided, it is used in the safe live end calculation.
  35184. * Setting useSafeLiveEnd=false or liveEdgePadding=0 are equivalent.
  35185. * Corresponds to suggestedPresentationDelay in DASH manifests.
  35186. * @return {number} the end time of playlist
  35187. * @function playlistEnd
  35188. */
  35189. var playlistEnd = function playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding) {
  35190. if (!playlist || !playlist.segments) {
  35191. return null;
  35192. }
  35193. if (playlist.endList) {
  35194. return duration(playlist);
  35195. }
  35196. if (expired === null) {
  35197. return null;
  35198. }
  35199. expired = expired || 0;
  35200. var lastSegmentEndTime = intervalDuration(playlist, playlist.mediaSequence + playlist.segments.length, expired);
  35201. if (useSafeLiveEnd) {
  35202. liveEdgePadding = typeof liveEdgePadding === 'number' ? liveEdgePadding : liveEdgeDelay(null, playlist);
  35203. lastSegmentEndTime -= liveEdgePadding;
  35204. } // don't return a time less than zero
  35205. return Math.max(0, lastSegmentEndTime);
  35206. };
  35207. /**
  35208. * Calculates the interval of time that is currently seekable in a
  35209. * playlist. The returned time ranges are relative to the earliest
  35210. * moment in the specified playlist that is still available. A full
  35211. * seekable implementation for live streams would need to offset
  35212. * these values by the duration of content that has expired from the
  35213. * stream.
  35214. *
  35215. * @param {Object} playlist a media playlist object
  35216. * dropped off the front of the playlist in a live scenario
  35217. * @param {number=} expired the amount of time that has
  35218. * dropped off the front of the playlist in a live scenario
  35219. * @param {number} liveEdgePadding how far from the end of the playlist we should be in seconds.
  35220. * Corresponds to suggestedPresentationDelay in DASH manifests.
  35221. * @return {TimeRanges} the periods of time that are valid targets
  35222. * for seeking
  35223. */
  35224. var seekable = function seekable(playlist, expired, liveEdgePadding) {
  35225. var useSafeLiveEnd = true;
  35226. var seekableStart = expired || 0;
  35227. var seekableEnd = playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding);
  35228. if (seekableEnd === null) {
  35229. return createTimeRange();
  35230. }
  35231. return createTimeRange(seekableStart, seekableEnd);
  35232. };
  35233. /**
  35234. * Determine the index and estimated starting time of the segment that
  35235. * contains a specified playback position in a media playlist.
  35236. *
  35237. * @param {Object} options.playlist the media playlist to query
  35238. * @param {number} options.currentTime The number of seconds since the earliest
  35239. * possible position to determine the containing segment for
  35240. * @param {number} options.startTime the time when the segment/part starts
  35241. * @param {number} options.startingSegmentIndex the segment index to start looking at.
  35242. * @param {number?} [options.startingPartIndex] the part index to look at within the segment.
  35243. *
  35244. * @return {Object} an object with partIndex, segmentIndex, and startTime.
  35245. */
  35246. var getMediaInfoForTime = function getMediaInfoForTime(_ref4) {
  35247. var playlist = _ref4.playlist,
  35248. currentTime = _ref4.currentTime,
  35249. startingSegmentIndex = _ref4.startingSegmentIndex,
  35250. startingPartIndex = _ref4.startingPartIndex,
  35251. startTime = _ref4.startTime,
  35252. experimentalExactManifestTimings = _ref4.experimentalExactManifestTimings;
  35253. var time = currentTime - startTime;
  35254. var partsAndSegments = getPartsAndSegments(playlist);
  35255. var startIndex = 0;
  35256. for (var i = 0; i < partsAndSegments.length; i++) {
  35257. var partAndSegment = partsAndSegments[i];
  35258. if (startingSegmentIndex !== partAndSegment.segmentIndex) {
  35259. continue;
  35260. } // skip this if part index does not match.
  35261. if (typeof startingPartIndex === 'number' && typeof partAndSegment.partIndex === 'number' && startingPartIndex !== partAndSegment.partIndex) {
  35262. continue;
  35263. }
  35264. startIndex = i;
  35265. break;
  35266. }
  35267. if (time < 0) {
  35268. // Walk backward from startIndex in the playlist, adding durations
  35269. // until we find a segment that contains `time` and return it
  35270. if (startIndex > 0) {
  35271. for (var _i2 = startIndex - 1; _i2 >= 0; _i2--) {
  35272. var _partAndSegment = partsAndSegments[_i2];
  35273. time += _partAndSegment.duration;
  35274. if (experimentalExactManifestTimings) {
  35275. if (time < 0) {
  35276. continue;
  35277. }
  35278. } else if (time + TIME_FUDGE_FACTOR <= 0) {
  35279. continue;
  35280. }
  35281. return {
  35282. partIndex: _partAndSegment.partIndex,
  35283. segmentIndex: _partAndSegment.segmentIndex,
  35284. startTime: startTime - sumDurations({
  35285. defaultDuration: playlist.targetDuration,
  35286. durationList: partsAndSegments,
  35287. startIndex: startIndex,
  35288. endIndex: _i2
  35289. })
  35290. };
  35291. }
  35292. } // We were unable to find a good segment within the playlist
  35293. // so select the first segment
  35294. return {
  35295. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  35296. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  35297. startTime: currentTime
  35298. };
  35299. } // When startIndex is negative, we first walk forward to first segment
  35300. // adding target durations. If we "run out of time" before getting to
  35301. // the first segment, return the first segment
  35302. if (startIndex < 0) {
  35303. for (var _i3 = startIndex; _i3 < 0; _i3++) {
  35304. time -= playlist.targetDuration;
  35305. if (time < 0) {
  35306. return {
  35307. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  35308. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  35309. startTime: currentTime
  35310. };
  35311. }
  35312. }
  35313. startIndex = 0;
  35314. } // Walk forward from startIndex in the playlist, subtracting durations
  35315. // until we find a segment that contains `time` and return it
  35316. for (var _i4 = startIndex; _i4 < partsAndSegments.length; _i4++) {
  35317. var _partAndSegment2 = partsAndSegments[_i4];
  35318. time -= _partAndSegment2.duration;
  35319. if (experimentalExactManifestTimings) {
  35320. if (time > 0) {
  35321. continue;
  35322. }
  35323. } else if (time - TIME_FUDGE_FACTOR >= 0) {
  35324. continue;
  35325. }
  35326. return {
  35327. partIndex: _partAndSegment2.partIndex,
  35328. segmentIndex: _partAndSegment2.segmentIndex,
  35329. startTime: startTime + sumDurations({
  35330. defaultDuration: playlist.targetDuration,
  35331. durationList: partsAndSegments,
  35332. startIndex: startIndex,
  35333. endIndex: _i4
  35334. })
  35335. };
  35336. } // We are out of possible candidates so load the last one...
  35337. return {
  35338. segmentIndex: partsAndSegments[partsAndSegments.length - 1].segmentIndex,
  35339. partIndex: partsAndSegments[partsAndSegments.length - 1].partIndex,
  35340. startTime: currentTime
  35341. };
  35342. };
  35343. /**
  35344. * Check whether the playlist is blacklisted or not.
  35345. *
  35346. * @param {Object} playlist the media playlist object
  35347. * @return {boolean} whether the playlist is blacklisted or not
  35348. * @function isBlacklisted
  35349. */
  35350. var isBlacklisted = function isBlacklisted(playlist) {
  35351. return playlist.excludeUntil && playlist.excludeUntil > Date.now();
  35352. };
  35353. /**
  35354. * Check whether the playlist is compatible with current playback configuration or has
  35355. * been blacklisted permanently for being incompatible.
  35356. *
  35357. * @param {Object} playlist the media playlist object
  35358. * @return {boolean} whether the playlist is incompatible or not
  35359. * @function isIncompatible
  35360. */
  35361. var isIncompatible = function isIncompatible(playlist) {
  35362. return playlist.excludeUntil && playlist.excludeUntil === Infinity;
  35363. };
  35364. /**
  35365. * Check whether the playlist is enabled or not.
  35366. *
  35367. * @param {Object} playlist the media playlist object
  35368. * @return {boolean} whether the playlist is enabled or not
  35369. * @function isEnabled
  35370. */
  35371. var isEnabled = function isEnabled(playlist) {
  35372. var blacklisted = isBlacklisted(playlist);
  35373. return !playlist.disabled && !blacklisted;
  35374. };
  35375. /**
  35376. * Check whether the playlist has been manually disabled through the representations api.
  35377. *
  35378. * @param {Object} playlist the media playlist object
  35379. * @return {boolean} whether the playlist is disabled manually or not
  35380. * @function isDisabled
  35381. */
  35382. var isDisabled = function isDisabled(playlist) {
  35383. return playlist.disabled;
  35384. };
  35385. /**
  35386. * Returns whether the current playlist is an AES encrypted HLS stream
  35387. *
  35388. * @return {boolean} true if it's an AES encrypted HLS stream
  35389. */
  35390. var isAes = function isAes(media) {
  35391. for (var i = 0; i < media.segments.length; i++) {
  35392. if (media.segments[i].key) {
  35393. return true;
  35394. }
  35395. }
  35396. return false;
  35397. };
  35398. /**
  35399. * Checks if the playlist has a value for the specified attribute
  35400. *
  35401. * @param {string} attr
  35402. * Attribute to check for
  35403. * @param {Object} playlist
  35404. * The media playlist object
  35405. * @return {boolean}
  35406. * Whether the playlist contains a value for the attribute or not
  35407. * @function hasAttribute
  35408. */
  35409. var hasAttribute = function hasAttribute(attr, playlist) {
  35410. return playlist.attributes && playlist.attributes[attr];
  35411. };
  35412. /**
  35413. * Estimates the time required to complete a segment download from the specified playlist
  35414. *
  35415. * @param {number} segmentDuration
  35416. * Duration of requested segment
  35417. * @param {number} bandwidth
  35418. * Current measured bandwidth of the player
  35419. * @param {Object} playlist
  35420. * The media playlist object
  35421. * @param {number=} bytesReceived
  35422. * Number of bytes already received for the request. Defaults to 0
  35423. * @return {number|NaN}
  35424. * The estimated time to request the segment. NaN if bandwidth information for
  35425. * the given playlist is unavailable
  35426. * @function estimateSegmentRequestTime
  35427. */
  35428. var estimateSegmentRequestTime = function estimateSegmentRequestTime(segmentDuration, bandwidth, playlist, bytesReceived) {
  35429. if (bytesReceived === void 0) {
  35430. bytesReceived = 0;
  35431. }
  35432. if (!hasAttribute('BANDWIDTH', playlist)) {
  35433. return NaN;
  35434. }
  35435. var size = segmentDuration * playlist.attributes.BANDWIDTH;
  35436. return (size - bytesReceived * 8) / bandwidth;
  35437. };
  35438. /*
  35439. * Returns whether the current playlist is the lowest rendition
  35440. *
  35441. * @return {Boolean} true if on lowest rendition
  35442. */
  35443. var isLowestEnabledRendition = function isLowestEnabledRendition(master, media) {
  35444. if (master.playlists.length === 1) {
  35445. return true;
  35446. }
  35447. var currentBandwidth = media.attributes.BANDWIDTH || Number.MAX_VALUE;
  35448. return master.playlists.filter(function (playlist) {
  35449. if (!isEnabled(playlist)) {
  35450. return false;
  35451. }
  35452. return (playlist.attributes.BANDWIDTH || 0) < currentBandwidth;
  35453. }).length === 0;
  35454. };
  35455. var playlistMatch = function playlistMatch(a, b) {
  35456. // both playlits are null
  35457. // or only one playlist is non-null
  35458. // no match
  35459. if (!a && !b || !a && b || a && !b) {
  35460. return false;
  35461. } // playlist objects are the same, match
  35462. if (a === b) {
  35463. return true;
  35464. } // first try to use id as it should be the most
  35465. // accurate
  35466. if (a.id && b.id && a.id === b.id) {
  35467. return true;
  35468. } // next try to use reslovedUri as it should be the
  35469. // second most accurate.
  35470. if (a.resolvedUri && b.resolvedUri && a.resolvedUri === b.resolvedUri) {
  35471. return true;
  35472. } // finally try to use uri as it should be accurate
  35473. // but might miss a few cases for relative uris
  35474. if (a.uri && b.uri && a.uri === b.uri) {
  35475. return true;
  35476. }
  35477. return false;
  35478. };
  35479. var someAudioVariant = function someAudioVariant(master, callback) {
  35480. var AUDIO = master && master.mediaGroups && master.mediaGroups.AUDIO || {};
  35481. var found = false;
  35482. for (var groupName in AUDIO) {
  35483. for (var label in AUDIO[groupName]) {
  35484. found = callback(AUDIO[groupName][label]);
  35485. if (found) {
  35486. break;
  35487. }
  35488. }
  35489. if (found) {
  35490. break;
  35491. }
  35492. }
  35493. return !!found;
  35494. };
  35495. var isAudioOnly = function isAudioOnly(master) {
  35496. // we are audio only if we have no main playlists but do
  35497. // have media group playlists.
  35498. if (!master || !master.playlists || !master.playlists.length) {
  35499. // without audio variants or playlists this
  35500. // is not an audio only master.
  35501. var found = someAudioVariant(master, function (variant) {
  35502. return variant.playlists && variant.playlists.length || variant.uri;
  35503. });
  35504. return found;
  35505. } // if every playlist has only an audio codec it is audio only
  35506. var _loop = function _loop(i) {
  35507. var playlist = master.playlists[i];
  35508. var CODECS = playlist.attributes && playlist.attributes.CODECS; // all codecs are audio, this is an audio playlist.
  35509. if (CODECS && CODECS.split(',').every(function (c) {
  35510. return isAudioCodec(c);
  35511. })) {
  35512. return "continue";
  35513. } // playlist is in an audio group it is audio only
  35514. var found = someAudioVariant(master, function (variant) {
  35515. return playlistMatch(playlist, variant);
  35516. });
  35517. if (found) {
  35518. return "continue";
  35519. } // if we make it here this playlist isn't audio and we
  35520. // are not audio only
  35521. return {
  35522. v: false
  35523. };
  35524. };
  35525. for (var i = 0; i < master.playlists.length; i++) {
  35526. var _ret = _loop(i);
  35527. if (_ret === "continue") continue;
  35528. if (typeof _ret === "object") return _ret.v;
  35529. } // if we make it past every playlist without returning, then
  35530. // this is an audio only playlist.
  35531. return true;
  35532. }; // exports
  35533. var Playlist = {
  35534. liveEdgeDelay: liveEdgeDelay,
  35535. duration: duration,
  35536. seekable: seekable,
  35537. getMediaInfoForTime: getMediaInfoForTime,
  35538. isEnabled: isEnabled,
  35539. isDisabled: isDisabled,
  35540. isBlacklisted: isBlacklisted,
  35541. isIncompatible: isIncompatible,
  35542. playlistEnd: playlistEnd,
  35543. isAes: isAes,
  35544. hasAttribute: hasAttribute,
  35545. estimateSegmentRequestTime: estimateSegmentRequestTime,
  35546. isLowestEnabledRendition: isLowestEnabledRendition,
  35547. isAudioOnly: isAudioOnly,
  35548. playlistMatch: playlistMatch,
  35549. segmentDurationWithParts: segmentDurationWithParts
  35550. };
  35551. var log = videojs.log;
  35552. var createPlaylistID = function createPlaylistID(index, uri) {
  35553. return index + "-" + uri;
  35554. }; // default function for creating a group id
  35555. var groupID = function groupID(type, group, label) {
  35556. return "placeholder-uri-" + type + "-" + group + "-" + label;
  35557. };
  35558. /**
  35559. * Parses a given m3u8 playlist
  35560. *
  35561. * @param {Function} [onwarn]
  35562. * a function to call when the parser triggers a warning event.
  35563. * @param {Function} [oninfo]
  35564. * a function to call when the parser triggers an info event.
  35565. * @param {string} manifestString
  35566. * The downloaded manifest string
  35567. * @param {Object[]} [customTagParsers]
  35568. * An array of custom tag parsers for the m3u8-parser instance
  35569. * @param {Object[]} [customTagMappers]
  35570. * An array of custom tag mappers for the m3u8-parser instance
  35571. * @param {boolean} [experimentalLLHLS=false]
  35572. * Whether to keep ll-hls features in the manifest after parsing.
  35573. * @return {Object}
  35574. * The manifest object
  35575. */
  35576. var parseManifest = function parseManifest(_ref) {
  35577. var onwarn = _ref.onwarn,
  35578. oninfo = _ref.oninfo,
  35579. manifestString = _ref.manifestString,
  35580. _ref$customTagParsers = _ref.customTagParsers,
  35581. customTagParsers = _ref$customTagParsers === void 0 ? [] : _ref$customTagParsers,
  35582. _ref$customTagMappers = _ref.customTagMappers,
  35583. customTagMappers = _ref$customTagMappers === void 0 ? [] : _ref$customTagMappers,
  35584. experimentalLLHLS = _ref.experimentalLLHLS;
  35585. var parser = new Parser();
  35586. if (onwarn) {
  35587. parser.on('warn', onwarn);
  35588. }
  35589. if (oninfo) {
  35590. parser.on('info', oninfo);
  35591. }
  35592. customTagParsers.forEach(function (customParser) {
  35593. return parser.addParser(customParser);
  35594. });
  35595. customTagMappers.forEach(function (mapper) {
  35596. return parser.addTagMapper(mapper);
  35597. });
  35598. parser.push(manifestString);
  35599. parser.end();
  35600. var manifest = parser.manifest; // remove llhls features from the parsed manifest
  35601. // if we don't want llhls support.
  35602. if (!experimentalLLHLS) {
  35603. ['preloadSegment', 'skip', 'serverControl', 'renditionReports', 'partInf', 'partTargetDuration'].forEach(function (k) {
  35604. if (manifest.hasOwnProperty(k)) {
  35605. delete manifest[k];
  35606. }
  35607. });
  35608. if (manifest.segments) {
  35609. manifest.segments.forEach(function (segment) {
  35610. ['parts', 'preloadHints'].forEach(function (k) {
  35611. if (segment.hasOwnProperty(k)) {
  35612. delete segment[k];
  35613. }
  35614. });
  35615. });
  35616. }
  35617. }
  35618. if (!manifest.targetDuration) {
  35619. var targetDuration = 10;
  35620. if (manifest.segments && manifest.segments.length) {
  35621. targetDuration = manifest.segments.reduce(function (acc, s) {
  35622. return Math.max(acc, s.duration);
  35623. }, 0);
  35624. }
  35625. if (onwarn) {
  35626. onwarn("manifest has no targetDuration defaulting to " + targetDuration);
  35627. }
  35628. manifest.targetDuration = targetDuration;
  35629. }
  35630. var parts = getLastParts(manifest);
  35631. if (parts.length && !manifest.partTargetDuration) {
  35632. var partTargetDuration = parts.reduce(function (acc, p) {
  35633. return Math.max(acc, p.duration);
  35634. }, 0);
  35635. if (onwarn) {
  35636. onwarn("manifest has no partTargetDuration defaulting to " + partTargetDuration);
  35637. log.error('LL-HLS manifest has parts but lacks required #EXT-X-PART-INF:PART-TARGET value. See https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-09#section-4.4.3.7. Playback is not guaranteed.');
  35638. }
  35639. manifest.partTargetDuration = partTargetDuration;
  35640. }
  35641. return manifest;
  35642. };
  35643. /**
  35644. * Loops through all supported media groups in master and calls the provided
  35645. * callback for each group
  35646. *
  35647. * @param {Object} master
  35648. * The parsed master manifest object
  35649. * @param {Function} callback
  35650. * Callback to call for each media group
  35651. */
  35652. var forEachMediaGroup = function forEachMediaGroup(master, callback) {
  35653. if (!master.mediaGroups) {
  35654. return;
  35655. }
  35656. ['AUDIO', 'SUBTITLES'].forEach(function (mediaType) {
  35657. if (!master.mediaGroups[mediaType]) {
  35658. return;
  35659. }
  35660. for (var groupKey in master.mediaGroups[mediaType]) {
  35661. for (var labelKey in master.mediaGroups[mediaType][groupKey]) {
  35662. var mediaProperties = master.mediaGroups[mediaType][groupKey][labelKey];
  35663. callback(mediaProperties, mediaType, groupKey, labelKey);
  35664. }
  35665. }
  35666. });
  35667. };
  35668. /**
  35669. * Adds properties and attributes to the playlist to keep consistent functionality for
  35670. * playlists throughout VHS.
  35671. *
  35672. * @param {Object} config
  35673. * Arguments object
  35674. * @param {Object} config.playlist
  35675. * The media playlist
  35676. * @param {string} [config.uri]
  35677. * The uri to the media playlist (if media playlist is not from within a master
  35678. * playlist)
  35679. * @param {string} id
  35680. * ID to use for the playlist
  35681. */
  35682. var setupMediaPlaylist = function setupMediaPlaylist(_ref2) {
  35683. var playlist = _ref2.playlist,
  35684. uri = _ref2.uri,
  35685. id = _ref2.id;
  35686. playlist.id = id;
  35687. playlist.playlistErrors_ = 0;
  35688. if (uri) {
  35689. // For media playlists, m3u8-parser does not have access to a URI, as HLS media
  35690. // playlists do not contain their own source URI, but one is needed for consistency in
  35691. // VHS.
  35692. playlist.uri = uri;
  35693. } // For HLS master playlists, even though certain attributes MUST be defined, the
  35694. // stream may still be played without them.
  35695. // For HLS media playlists, m3u8-parser does not attach an attributes object to the
  35696. // manifest.
  35697. //
  35698. // To avoid undefined reference errors through the project, and make the code easier
  35699. // to write/read, add an empty attributes object for these cases.
  35700. playlist.attributes = playlist.attributes || {};
  35701. };
  35702. /**
  35703. * Adds ID, resolvedUri, and attributes properties to each playlist of the master, where
  35704. * necessary. In addition, creates playlist IDs for each playlist and adds playlist ID to
  35705. * playlist references to the playlists array.
  35706. *
  35707. * @param {Object} master
  35708. * The master playlist
  35709. */
  35710. var setupMediaPlaylists = function setupMediaPlaylists(master) {
  35711. var i = master.playlists.length;
  35712. while (i--) {
  35713. var playlist = master.playlists[i];
  35714. setupMediaPlaylist({
  35715. playlist: playlist,
  35716. id: createPlaylistID(i, playlist.uri)
  35717. });
  35718. playlist.resolvedUri = resolveUrl(master.uri, playlist.uri);
  35719. master.playlists[playlist.id] = playlist; // URI reference added for backwards compatibility
  35720. master.playlists[playlist.uri] = playlist; // Although the spec states an #EXT-X-STREAM-INF tag MUST have a BANDWIDTH attribute,
  35721. // the stream can be played without it. Although an attributes property may have been
  35722. // added to the playlist to prevent undefined references, issue a warning to fix the
  35723. // manifest.
  35724. if (!playlist.attributes.BANDWIDTH) {
  35725. log.warn('Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.');
  35726. }
  35727. }
  35728. };
  35729. /**
  35730. * Adds resolvedUri properties to each media group.
  35731. *
  35732. * @param {Object} master
  35733. * The master playlist
  35734. */
  35735. var resolveMediaGroupUris = function resolveMediaGroupUris(master) {
  35736. forEachMediaGroup(master, function (properties) {
  35737. if (properties.uri) {
  35738. properties.resolvedUri = resolveUrl(master.uri, properties.uri);
  35739. }
  35740. });
  35741. };
  35742. /**
  35743. * Creates a master playlist wrapper to insert a sole media playlist into.
  35744. *
  35745. * @param {Object} media
  35746. * Media playlist
  35747. * @param {string} uri
  35748. * The media URI
  35749. *
  35750. * @return {Object}
  35751. * Master playlist
  35752. */
  35753. var masterForMedia = function masterForMedia(media, uri) {
  35754. var id = createPlaylistID(0, uri);
  35755. var master = {
  35756. mediaGroups: {
  35757. 'AUDIO': {},
  35758. 'VIDEO': {},
  35759. 'CLOSED-CAPTIONS': {},
  35760. 'SUBTITLES': {}
  35761. },
  35762. uri: window.location.href,
  35763. resolvedUri: window.location.href,
  35764. playlists: [{
  35765. uri: uri,
  35766. id: id,
  35767. resolvedUri: uri,
  35768. // m3u8-parser does not attach an attributes property to media playlists so make
  35769. // sure that the property is attached to avoid undefined reference errors
  35770. attributes: {}
  35771. }]
  35772. }; // set up ID reference
  35773. master.playlists[id] = master.playlists[0]; // URI reference added for backwards compatibility
  35774. master.playlists[uri] = master.playlists[0];
  35775. return master;
  35776. };
  35777. /**
  35778. * Does an in-place update of the master manifest to add updated playlist URI references
  35779. * as well as other properties needed by VHS that aren't included by the parser.
  35780. *
  35781. * @param {Object} master
  35782. * Master manifest object
  35783. * @param {string} uri
  35784. * The source URI
  35785. * @param {function} createGroupID
  35786. * A function to determine how to create the groupID for mediaGroups
  35787. */
  35788. var addPropertiesToMaster = function addPropertiesToMaster(master, uri, createGroupID) {
  35789. if (createGroupID === void 0) {
  35790. createGroupID = groupID;
  35791. }
  35792. master.uri = uri;
  35793. for (var i = 0; i < master.playlists.length; i++) {
  35794. if (!master.playlists[i].uri) {
  35795. // Set up phony URIs for the playlists since playlists are referenced by their URIs
  35796. // throughout VHS, but some formats (e.g., DASH) don't have external URIs
  35797. // TODO: consider adding dummy URIs in mpd-parser
  35798. var phonyUri = "placeholder-uri-" + i;
  35799. master.playlists[i].uri = phonyUri;
  35800. }
  35801. }
  35802. var audioOnlyMaster = isAudioOnly(master);
  35803. forEachMediaGroup(master, function (properties, mediaType, groupKey, labelKey) {
  35804. // add a playlist array under properties
  35805. if (!properties.playlists || !properties.playlists.length) {
  35806. // If the manifest is audio only and this media group does not have a uri, check
  35807. // if the media group is located in the main list of playlists. If it is, don't add
  35808. // placeholder properties as it shouldn't be considered an alternate audio track.
  35809. if (audioOnlyMaster && mediaType === 'AUDIO' && !properties.uri) {
  35810. for (var _i = 0; _i < master.playlists.length; _i++) {
  35811. var p = master.playlists[_i];
  35812. if (p.attributes && p.attributes.AUDIO && p.attributes.AUDIO === groupKey) {
  35813. return;
  35814. }
  35815. }
  35816. }
  35817. properties.playlists = [_extends_1({}, properties)];
  35818. }
  35819. properties.playlists.forEach(function (p, i) {
  35820. var groupId = createGroupID(mediaType, groupKey, labelKey, p);
  35821. var id = createPlaylistID(i, groupId);
  35822. if (p.uri) {
  35823. p.resolvedUri = p.resolvedUri || resolveUrl(master.uri, p.uri);
  35824. } else {
  35825. // DEPRECATED, this has been added to prevent a breaking change.
  35826. // previously we only ever had a single media group playlist, so
  35827. // we mark the first playlist uri without prepending the index as we used to
  35828. // ideally we would do all of the playlists the same way.
  35829. p.uri = i === 0 ? groupId : id; // don't resolve a placeholder uri to an absolute url, just use
  35830. // the placeholder again
  35831. p.resolvedUri = p.uri;
  35832. }
  35833. p.id = p.id || id; // add an empty attributes object, all playlists are
  35834. // expected to have this.
  35835. p.attributes = p.attributes || {}; // setup ID and URI references (URI for backwards compatibility)
  35836. master.playlists[p.id] = p;
  35837. master.playlists[p.uri] = p;
  35838. });
  35839. });
  35840. setupMediaPlaylists(master);
  35841. resolveMediaGroupUris(master);
  35842. };
  35843. var mergeOptions$2 = videojs.mergeOptions,
  35844. EventTarget$1 = videojs.EventTarget;
  35845. var addLLHLSQueryDirectives = function addLLHLSQueryDirectives(uri, media) {
  35846. if (media.endList || !media.serverControl) {
  35847. return uri;
  35848. }
  35849. var parameters = {};
  35850. if (media.serverControl.canBlockReload) {
  35851. var preloadSegment = media.preloadSegment; // next msn is a zero based value, length is not.
  35852. var nextMSN = media.mediaSequence + media.segments.length; // If preload segment has parts then it is likely
  35853. // that we are going to request a part of that preload segment.
  35854. // the logic below is used to determine that.
  35855. if (preloadSegment) {
  35856. var parts = preloadSegment.parts || []; // _HLS_part is a zero based index
  35857. var nextPart = getKnownPartCount(media) - 1; // if nextPart is > -1 and not equal to just the
  35858. // length of parts, then we know we had part preload hints
  35859. // and we need to add the _HLS_part= query
  35860. if (nextPart > -1 && nextPart !== parts.length - 1) {
  35861. // add existing parts to our preload hints
  35862. // eslint-disable-next-line
  35863. parameters._HLS_part = nextPart;
  35864. } // this if statement makes sure that we request the msn
  35865. // of the preload segment if:
  35866. // 1. the preload segment had parts (and was not yet a full segment)
  35867. // but was added to our segments array
  35868. // 2. the preload segment had preload hints for parts that are not in
  35869. // the manifest yet.
  35870. // in all other cases we want the segment after the preload segment
  35871. // which will be given by using media.segments.length because it is 1 based
  35872. // rather than 0 based.
  35873. if (nextPart > -1 || parts.length) {
  35874. nextMSN--;
  35875. }
  35876. } // add _HLS_msn= in front of any _HLS_part query
  35877. // eslint-disable-next-line
  35878. parameters._HLS_msn = nextMSN;
  35879. }
  35880. if (media.serverControl && media.serverControl.canSkipUntil) {
  35881. // add _HLS_skip= infront of all other queries.
  35882. // eslint-disable-next-line
  35883. parameters._HLS_skip = media.serverControl.canSkipDateranges ? 'v2' : 'YES';
  35884. }
  35885. if (Object.keys(parameters).length) {
  35886. var parsedUri = new window.URL(uri);
  35887. ['_HLS_skip', '_HLS_msn', '_HLS_part'].forEach(function (name) {
  35888. if (!parameters.hasOwnProperty(name)) {
  35889. return;
  35890. }
  35891. parsedUri.searchParams.set(name, parameters[name]);
  35892. });
  35893. uri = parsedUri.toString();
  35894. }
  35895. return uri;
  35896. };
  35897. /**
  35898. * Returns a new segment object with properties and
  35899. * the parts array merged.
  35900. *
  35901. * @param {Object} a the old segment
  35902. * @param {Object} b the new segment
  35903. *
  35904. * @return {Object} the merged segment
  35905. */
  35906. var updateSegment = function updateSegment(a, b) {
  35907. if (!a) {
  35908. return b;
  35909. }
  35910. var result = mergeOptions$2(a, b); // if only the old segment has preload hints
  35911. // and the new one does not, remove preload hints.
  35912. if (a.preloadHints && !b.preloadHints) {
  35913. delete result.preloadHints;
  35914. } // if only the old segment has parts
  35915. // then the parts are no longer valid
  35916. if (a.parts && !b.parts) {
  35917. delete result.parts; // if both segments have parts
  35918. // copy part propeties from the old segment
  35919. // to the new one.
  35920. } else if (a.parts && b.parts) {
  35921. for (var i = 0; i < b.parts.length; i++) {
  35922. if (a.parts && a.parts[i]) {
  35923. result.parts[i] = mergeOptions$2(a.parts[i], b.parts[i]);
  35924. }
  35925. }
  35926. } // set skipped to false for segments that have
  35927. // have had information merged from the old segment.
  35928. if (!a.skipped && b.skipped) {
  35929. result.skipped = false;
  35930. } // set preload to false for segments that have
  35931. // had information added in the new segment.
  35932. if (a.preload && !b.preload) {
  35933. result.preload = false;
  35934. }
  35935. return result;
  35936. };
  35937. /**
  35938. * Returns a new array of segments that is the result of merging
  35939. * properties from an older list of segments onto an updated
  35940. * list. No properties on the updated playlist will be ovewritten.
  35941. *
  35942. * @param {Array} original the outdated list of segments
  35943. * @param {Array} update the updated list of segments
  35944. * @param {number=} offset the index of the first update
  35945. * segment in the original segment list. For non-live playlists,
  35946. * this should always be zero and does not need to be
  35947. * specified. For live playlists, it should be the difference
  35948. * between the media sequence numbers in the original and updated
  35949. * playlists.
  35950. * @return {Array} a list of merged segment objects
  35951. */
  35952. var updateSegments = function updateSegments(original, update, offset) {
  35953. var oldSegments = original.slice();
  35954. var newSegments = update.slice();
  35955. offset = offset || 0;
  35956. var result = [];
  35957. var currentMap;
  35958. for (var newIndex = 0; newIndex < newSegments.length; newIndex++) {
  35959. var oldSegment = oldSegments[newIndex + offset];
  35960. var newSegment = newSegments[newIndex];
  35961. if (oldSegment) {
  35962. currentMap = oldSegment.map || currentMap;
  35963. result.push(updateSegment(oldSegment, newSegment));
  35964. } else {
  35965. // carry over map to new segment if it is missing
  35966. if (currentMap && !newSegment.map) {
  35967. newSegment.map = currentMap;
  35968. }
  35969. result.push(newSegment);
  35970. }
  35971. }
  35972. return result;
  35973. };
  35974. var resolveSegmentUris = function resolveSegmentUris(segment, baseUri) {
  35975. // preloadSegment will not have a uri at all
  35976. // as the segment isn't actually in the manifest yet, only parts
  35977. if (!segment.resolvedUri && segment.uri) {
  35978. segment.resolvedUri = resolveUrl(baseUri, segment.uri);
  35979. }
  35980. if (segment.key && !segment.key.resolvedUri) {
  35981. segment.key.resolvedUri = resolveUrl(baseUri, segment.key.uri);
  35982. }
  35983. if (segment.map && !segment.map.resolvedUri) {
  35984. segment.map.resolvedUri = resolveUrl(baseUri, segment.map.uri);
  35985. }
  35986. if (segment.map && segment.map.key && !segment.map.key.resolvedUri) {
  35987. segment.map.key.resolvedUri = resolveUrl(baseUri, segment.map.key.uri);
  35988. }
  35989. if (segment.parts && segment.parts.length) {
  35990. segment.parts.forEach(function (p) {
  35991. if (p.resolvedUri) {
  35992. return;
  35993. }
  35994. p.resolvedUri = resolveUrl(baseUri, p.uri);
  35995. });
  35996. }
  35997. if (segment.preloadHints && segment.preloadHints.length) {
  35998. segment.preloadHints.forEach(function (p) {
  35999. if (p.resolvedUri) {
  36000. return;
  36001. }
  36002. p.resolvedUri = resolveUrl(baseUri, p.uri);
  36003. });
  36004. }
  36005. };
  36006. var getAllSegments = function getAllSegments(media) {
  36007. var segments = media.segments || [];
  36008. var preloadSegment = media.preloadSegment; // a preloadSegment with only preloadHints is not currently
  36009. // a usable segment, only include a preloadSegment that has
  36010. // parts.
  36011. if (preloadSegment && preloadSegment.parts && preloadSegment.parts.length) {
  36012. // if preloadHints has a MAP that means that the
  36013. // init segment is going to change. We cannot use any of the parts
  36014. // from this preload segment.
  36015. if (preloadSegment.preloadHints) {
  36016. for (var i = 0; i < preloadSegment.preloadHints.length; i++) {
  36017. if (preloadSegment.preloadHints[i].type === 'MAP') {
  36018. return segments;
  36019. }
  36020. }
  36021. } // set the duration for our preload segment to target duration.
  36022. preloadSegment.duration = media.targetDuration;
  36023. preloadSegment.preload = true;
  36024. segments.push(preloadSegment);
  36025. }
  36026. return segments;
  36027. }; // consider the playlist unchanged if the playlist object is the same or
  36028. // the number of segments is equal, the media sequence number is unchanged,
  36029. // and this playlist hasn't become the end of the playlist
  36030. var isPlaylistUnchanged = function isPlaylistUnchanged(a, b) {
  36031. return a === b || a.segments && b.segments && a.segments.length === b.segments.length && a.endList === b.endList && a.mediaSequence === b.mediaSequence && a.preloadSegment === b.preloadSegment;
  36032. };
  36033. /**
  36034. * Returns a new master playlist that is the result of merging an
  36035. * updated media playlist into the original version. If the
  36036. * updated media playlist does not match any of the playlist
  36037. * entries in the original master playlist, null is returned.
  36038. *
  36039. * @param {Object} master a parsed master M3U8 object
  36040. * @param {Object} media a parsed media M3U8 object
  36041. * @return {Object} a new object that represents the original
  36042. * master playlist with the updated media playlist merged in, or
  36043. * null if the merge produced no change.
  36044. */
  36045. var updateMaster$1 = function updateMaster(master, newMedia, unchangedCheck) {
  36046. if (unchangedCheck === void 0) {
  36047. unchangedCheck = isPlaylistUnchanged;
  36048. }
  36049. var result = mergeOptions$2(master, {});
  36050. var oldMedia = result.playlists[newMedia.id];
  36051. if (!oldMedia) {
  36052. return null;
  36053. }
  36054. if (unchangedCheck(oldMedia, newMedia)) {
  36055. return null;
  36056. }
  36057. newMedia.segments = getAllSegments(newMedia);
  36058. var mergedPlaylist = mergeOptions$2(oldMedia, newMedia); // always use the new media's preload segment
  36059. if (mergedPlaylist.preloadSegment && !newMedia.preloadSegment) {
  36060. delete mergedPlaylist.preloadSegment;
  36061. } // if the update could overlap existing segment information, merge the two segment lists
  36062. if (oldMedia.segments) {
  36063. if (newMedia.skip) {
  36064. newMedia.segments = newMedia.segments || []; // add back in objects for skipped segments, so that we merge
  36065. // old properties into the new segments
  36066. for (var i = 0; i < newMedia.skip.skippedSegments; i++) {
  36067. newMedia.segments.unshift({
  36068. skipped: true
  36069. });
  36070. }
  36071. }
  36072. mergedPlaylist.segments = updateSegments(oldMedia.segments, newMedia.segments, newMedia.mediaSequence - oldMedia.mediaSequence);
  36073. } // resolve any segment URIs to prevent us from having to do it later
  36074. mergedPlaylist.segments.forEach(function (segment) {
  36075. resolveSegmentUris(segment, mergedPlaylist.resolvedUri);
  36076. }); // TODO Right now in the playlists array there are two references to each playlist, one
  36077. // that is referenced by index, and one by URI. The index reference may no longer be
  36078. // necessary.
  36079. for (var _i = 0; _i < result.playlists.length; _i++) {
  36080. if (result.playlists[_i].id === newMedia.id) {
  36081. result.playlists[_i] = mergedPlaylist;
  36082. }
  36083. }
  36084. result.playlists[newMedia.id] = mergedPlaylist; // URI reference added for backwards compatibility
  36085. result.playlists[newMedia.uri] = mergedPlaylist; // update media group playlist references.
  36086. forEachMediaGroup(master, function (properties, mediaType, groupKey, labelKey) {
  36087. if (!properties.playlists) {
  36088. return;
  36089. }
  36090. for (var _i2 = 0; _i2 < properties.playlists.length; _i2++) {
  36091. if (newMedia.id === properties.playlists[_i2].id) {
  36092. properties.playlists[_i2] = mergedPlaylist;
  36093. }
  36094. }
  36095. });
  36096. return result;
  36097. };
  36098. /**
  36099. * Calculates the time to wait before refreshing a live playlist
  36100. *
  36101. * @param {Object} media
  36102. * The current media
  36103. * @param {boolean} update
  36104. * True if there were any updates from the last refresh, false otherwise
  36105. * @return {number}
  36106. * The time in ms to wait before refreshing the live playlist
  36107. */
  36108. var refreshDelay = function refreshDelay(media, update) {
  36109. var segments = media.segments || [];
  36110. var lastSegment = segments[segments.length - 1];
  36111. var lastPart = lastSegment && lastSegment.parts && lastSegment.parts[lastSegment.parts.length - 1];
  36112. var lastDuration = lastPart && lastPart.duration || lastSegment && lastSegment.duration;
  36113. if (update && lastDuration) {
  36114. return lastDuration * 1000;
  36115. } // if the playlist is unchanged since the last reload or last segment duration
  36116. // cannot be determined, try again after half the target duration
  36117. return (media.partTargetDuration || media.targetDuration || 10) * 500;
  36118. };
  36119. /**
  36120. * Load a playlist from a remote location
  36121. *
  36122. * @class PlaylistLoader
  36123. * @extends Stream
  36124. * @param {string|Object} src url or object of manifest
  36125. * @param {boolean} withCredentials the withCredentials xhr option
  36126. * @class
  36127. */
  36128. var PlaylistLoader = /*#__PURE__*/function (_EventTarget) {
  36129. inheritsLoose(PlaylistLoader, _EventTarget);
  36130. function PlaylistLoader(src, vhs, options) {
  36131. var _this;
  36132. if (options === void 0) {
  36133. options = {};
  36134. }
  36135. _this = _EventTarget.call(this) || this;
  36136. if (!src) {
  36137. throw new Error('A non-empty playlist URL or object is required');
  36138. }
  36139. _this.logger_ = logger('PlaylistLoader');
  36140. var _options = options,
  36141. _options$withCredenti = _options.withCredentials,
  36142. withCredentials = _options$withCredenti === void 0 ? false : _options$withCredenti,
  36143. _options$handleManife = _options.handleManifestRedirects,
  36144. handleManifestRedirects = _options$handleManife === void 0 ? false : _options$handleManife;
  36145. _this.src = src;
  36146. _this.vhs_ = vhs;
  36147. _this.withCredentials = withCredentials;
  36148. _this.handleManifestRedirects = handleManifestRedirects;
  36149. var vhsOptions = vhs.options_;
  36150. _this.customTagParsers = vhsOptions && vhsOptions.customTagParsers || [];
  36151. _this.customTagMappers = vhsOptions && vhsOptions.customTagMappers || [];
  36152. _this.experimentalLLHLS = vhsOptions && vhsOptions.experimentalLLHLS || false; // force experimentalLLHLS for IE 11
  36153. if (videojs.browser.IE_VERSION) {
  36154. _this.experimentalLLHLS = false;
  36155. } // initialize the loader state
  36156. _this.state = 'HAVE_NOTHING'; // live playlist staleness timeout
  36157. _this.handleMediaupdatetimeout_ = _this.handleMediaupdatetimeout_.bind(assertThisInitialized(_this));
  36158. _this.on('mediaupdatetimeout', _this.handleMediaupdatetimeout_);
  36159. return _this;
  36160. }
  36161. var _proto = PlaylistLoader.prototype;
  36162. _proto.handleMediaupdatetimeout_ = function handleMediaupdatetimeout_() {
  36163. var _this2 = this;
  36164. if (this.state !== 'HAVE_METADATA') {
  36165. // only refresh the media playlist if no other activity is going on
  36166. return;
  36167. }
  36168. var media = this.media();
  36169. var uri = resolveUrl(this.master.uri, media.uri);
  36170. if (this.experimentalLLHLS) {
  36171. uri = addLLHLSQueryDirectives(uri, media);
  36172. }
  36173. this.state = 'HAVE_CURRENT_METADATA';
  36174. this.request = this.vhs_.xhr({
  36175. uri: uri,
  36176. withCredentials: this.withCredentials
  36177. }, function (error, req) {
  36178. // disposed
  36179. if (!_this2.request) {
  36180. return;
  36181. }
  36182. if (error) {
  36183. return _this2.playlistRequestError(_this2.request, _this2.media(), 'HAVE_METADATA');
  36184. }
  36185. _this2.haveMetadata({
  36186. playlistString: _this2.request.responseText,
  36187. url: _this2.media().uri,
  36188. id: _this2.media().id
  36189. });
  36190. });
  36191. };
  36192. _proto.playlistRequestError = function playlistRequestError(xhr, playlist, startingState) {
  36193. var uri = playlist.uri,
  36194. id = playlist.id; // any in-flight request is now finished
  36195. this.request = null;
  36196. if (startingState) {
  36197. this.state = startingState;
  36198. }
  36199. this.error = {
  36200. playlist: this.master.playlists[id],
  36201. status: xhr.status,
  36202. message: "HLS playlist request error at URL: " + uri + ".",
  36203. responseText: xhr.responseText,
  36204. code: xhr.status >= 500 ? 4 : 2
  36205. };
  36206. this.trigger('error');
  36207. };
  36208. _proto.parseManifest_ = function parseManifest_(_ref) {
  36209. var _this3 = this;
  36210. var url = _ref.url,
  36211. manifestString = _ref.manifestString;
  36212. return parseManifest({
  36213. onwarn: function onwarn(_ref2) {
  36214. var message = _ref2.message;
  36215. return _this3.logger_("m3u8-parser warn for " + url + ": " + message);
  36216. },
  36217. oninfo: function oninfo(_ref3) {
  36218. var message = _ref3.message;
  36219. return _this3.logger_("m3u8-parser info for " + url + ": " + message);
  36220. },
  36221. manifestString: manifestString,
  36222. customTagParsers: this.customTagParsers,
  36223. customTagMappers: this.customTagMappers,
  36224. experimentalLLHLS: this.experimentalLLHLS
  36225. });
  36226. }
  36227. /**
  36228. * Update the playlist loader's state in response to a new or updated playlist.
  36229. *
  36230. * @param {string} [playlistString]
  36231. * Playlist string (if playlistObject is not provided)
  36232. * @param {Object} [playlistObject]
  36233. * Playlist object (if playlistString is not provided)
  36234. * @param {string} url
  36235. * URL of playlist
  36236. * @param {string} id
  36237. * ID to use for playlist
  36238. */
  36239. ;
  36240. _proto.haveMetadata = function haveMetadata(_ref4) {
  36241. var playlistString = _ref4.playlistString,
  36242. playlistObject = _ref4.playlistObject,
  36243. url = _ref4.url,
  36244. id = _ref4.id; // any in-flight request is now finished
  36245. this.request = null;
  36246. this.state = 'HAVE_METADATA';
  36247. var playlist = playlistObject || this.parseManifest_({
  36248. url: url,
  36249. manifestString: playlistString
  36250. });
  36251. playlist.lastRequest = Date.now();
  36252. setupMediaPlaylist({
  36253. playlist: playlist,
  36254. uri: url,
  36255. id: id
  36256. }); // merge this playlist into the master
  36257. var update = updateMaster$1(this.master, playlist);
  36258. this.targetDuration = playlist.partTargetDuration || playlist.targetDuration;
  36259. this.pendingMedia_ = null;
  36260. if (update) {
  36261. this.master = update;
  36262. this.media_ = this.master.playlists[id];
  36263. } else {
  36264. this.trigger('playlistunchanged');
  36265. }
  36266. this.updateMediaUpdateTimeout_(refreshDelay(this.media(), !!update));
  36267. this.trigger('loadedplaylist');
  36268. }
  36269. /**
  36270. * Abort any outstanding work and clean up.
  36271. */
  36272. ;
  36273. _proto.dispose = function dispose() {
  36274. this.trigger('dispose');
  36275. this.stopRequest();
  36276. window.clearTimeout(this.mediaUpdateTimeout);
  36277. window.clearTimeout(this.finalRenditionTimeout);
  36278. this.off();
  36279. };
  36280. _proto.stopRequest = function stopRequest() {
  36281. if (this.request) {
  36282. var oldRequest = this.request;
  36283. this.request = null;
  36284. oldRequest.onreadystatechange = null;
  36285. oldRequest.abort();
  36286. }
  36287. }
  36288. /**
  36289. * When called without any arguments, returns the currently
  36290. * active media playlist. When called with a single argument,
  36291. * triggers the playlist loader to asynchronously switch to the
  36292. * specified media playlist. Calling this method while the
  36293. * loader is in the HAVE_NOTHING causes an error to be emitted
  36294. * but otherwise has no effect.
  36295. *
  36296. * @param {Object=} playlist the parsed media playlist
  36297. * object to switch to
  36298. * @param {boolean=} shouldDelay whether we should delay the request by half target duration
  36299. *
  36300. * @return {Playlist} the current loaded media
  36301. */
  36302. ;
  36303. _proto.media = function media(playlist, shouldDelay) {
  36304. var _this4 = this; // getter
  36305. if (!playlist) {
  36306. return this.media_;
  36307. } // setter
  36308. if (this.state === 'HAVE_NOTHING') {
  36309. throw new Error('Cannot switch media playlist from ' + this.state);
  36310. } // find the playlist object if the target playlist has been
  36311. // specified by URI
  36312. if (typeof playlist === 'string') {
  36313. if (!this.master.playlists[playlist]) {
  36314. throw new Error('Unknown playlist URI: ' + playlist);
  36315. }
  36316. playlist = this.master.playlists[playlist];
  36317. }
  36318. window.clearTimeout(this.finalRenditionTimeout);
  36319. if (shouldDelay) {
  36320. var delay = (playlist.partTargetDuration || playlist.targetDuration) / 2 * 1000 || 5 * 1000;
  36321. this.finalRenditionTimeout = window.setTimeout(this.media.bind(this, playlist, false), delay);
  36322. return;
  36323. }
  36324. var startingState = this.state;
  36325. var mediaChange = !this.media_ || playlist.id !== this.media_.id;
  36326. var masterPlaylistRef = this.master.playlists[playlist.id]; // switch to fully loaded playlists immediately
  36327. if (masterPlaylistRef && masterPlaylistRef.endList || // handle the case of a playlist object (e.g., if using vhs-json with a resolved
  36328. // media playlist or, for the case of demuxed audio, a resolved audio media group)
  36329. playlist.endList && playlist.segments.length) {
  36330. // abort outstanding playlist requests
  36331. if (this.request) {
  36332. this.request.onreadystatechange = null;
  36333. this.request.abort();
  36334. this.request = null;
  36335. }
  36336. this.state = 'HAVE_METADATA';
  36337. this.media_ = playlist; // trigger media change if the active media has been updated
  36338. if (mediaChange) {
  36339. this.trigger('mediachanging');
  36340. if (startingState === 'HAVE_MASTER') {
  36341. // The initial playlist was a master manifest, and the first media selected was
  36342. // also provided (in the form of a resolved playlist object) as part of the
  36343. // source object (rather than just a URL). Therefore, since the media playlist
  36344. // doesn't need to be requested, loadedmetadata won't trigger as part of the
  36345. // normal flow, and needs an explicit trigger here.
  36346. this.trigger('loadedmetadata');
  36347. } else {
  36348. this.trigger('mediachange');
  36349. }
  36350. }
  36351. return;
  36352. } // We update/set the timeout here so that live playlists
  36353. // that are not a media change will "start" the loader as expected.
  36354. // We expect that this function will start the media update timeout
  36355. // cycle again. This also prevents a playlist switch failure from
  36356. // causing us to stall during live.
  36357. this.updateMediaUpdateTimeout_(refreshDelay(playlist, true)); // switching to the active playlist is a no-op
  36358. if (!mediaChange) {
  36359. return;
  36360. }
  36361. this.state = 'SWITCHING_MEDIA'; // there is already an outstanding playlist request
  36362. if (this.request) {
  36363. if (playlist.resolvedUri === this.request.url) {
  36364. // requesting to switch to the same playlist multiple times
  36365. // has no effect after the first
  36366. return;
  36367. }
  36368. this.request.onreadystatechange = null;
  36369. this.request.abort();
  36370. this.request = null;
  36371. } // request the new playlist
  36372. if (this.media_) {
  36373. this.trigger('mediachanging');
  36374. }
  36375. this.pendingMedia_ = playlist;
  36376. this.request = this.vhs_.xhr({
  36377. uri: playlist.resolvedUri,
  36378. withCredentials: this.withCredentials
  36379. }, function (error, req) {
  36380. // disposed
  36381. if (!_this4.request) {
  36382. return;
  36383. }
  36384. playlist.lastRequest = Date.now();
  36385. playlist.resolvedUri = resolveManifestRedirect(_this4.handleManifestRedirects, playlist.resolvedUri, req);
  36386. if (error) {
  36387. return _this4.playlistRequestError(_this4.request, playlist, startingState);
  36388. }
  36389. _this4.haveMetadata({
  36390. playlistString: req.responseText,
  36391. url: playlist.uri,
  36392. id: playlist.id
  36393. }); // fire loadedmetadata the first time a media playlist is loaded
  36394. if (startingState === 'HAVE_MASTER') {
  36395. _this4.trigger('loadedmetadata');
  36396. } else {
  36397. _this4.trigger('mediachange');
  36398. }
  36399. });
  36400. }
  36401. /**
  36402. * pause loading of the playlist
  36403. */
  36404. ;
  36405. _proto.pause = function pause() {
  36406. if (this.mediaUpdateTimeout) {
  36407. window.clearTimeout(this.mediaUpdateTimeout);
  36408. this.mediaUpdateTimeout = null;
  36409. }
  36410. this.stopRequest();
  36411. if (this.state === 'HAVE_NOTHING') {
  36412. // If we pause the loader before any data has been retrieved, its as if we never
  36413. // started, so reset to an unstarted state.
  36414. this.started = false;
  36415. } // Need to restore state now that no activity is happening
  36416. if (this.state === 'SWITCHING_MEDIA') {
  36417. // if the loader was in the process of switching media, it should either return to
  36418. // HAVE_MASTER or HAVE_METADATA depending on if the loader has loaded a media
  36419. // playlist yet. This is determined by the existence of loader.media_
  36420. if (this.media_) {
  36421. this.state = 'HAVE_METADATA';
  36422. } else {
  36423. this.state = 'HAVE_MASTER';
  36424. }
  36425. } else if (this.state === 'HAVE_CURRENT_METADATA') {
  36426. this.state = 'HAVE_METADATA';
  36427. }
  36428. }
  36429. /**
  36430. * start loading of the playlist
  36431. */
  36432. ;
  36433. _proto.load = function load(shouldDelay) {
  36434. var _this5 = this;
  36435. if (this.mediaUpdateTimeout) {
  36436. window.clearTimeout(this.mediaUpdateTimeout);
  36437. this.mediaUpdateTimeout = null;
  36438. }
  36439. var media = this.media();
  36440. if (shouldDelay) {
  36441. var delay = media ? (media.partTargetDuration || media.targetDuration) / 2 * 1000 : 5 * 1000;
  36442. this.mediaUpdateTimeout = window.setTimeout(function () {
  36443. _this5.mediaUpdateTimeout = null;
  36444. _this5.load();
  36445. }, delay);
  36446. return;
  36447. }
  36448. if (!this.started) {
  36449. this.start();
  36450. return;
  36451. }
  36452. if (media && !media.endList) {
  36453. this.trigger('mediaupdatetimeout');
  36454. } else {
  36455. this.trigger('loadedplaylist');
  36456. }
  36457. };
  36458. _proto.updateMediaUpdateTimeout_ = function updateMediaUpdateTimeout_(delay) {
  36459. var _this6 = this;
  36460. if (this.mediaUpdateTimeout) {
  36461. window.clearTimeout(this.mediaUpdateTimeout);
  36462. this.mediaUpdateTimeout = null;
  36463. } // we only have use mediaupdatetimeout for live playlists.
  36464. if (!this.media() || this.media().endList) {
  36465. return;
  36466. }
  36467. this.mediaUpdateTimeout = window.setTimeout(function () {
  36468. _this6.mediaUpdateTimeout = null;
  36469. _this6.trigger('mediaupdatetimeout');
  36470. _this6.updateMediaUpdateTimeout_(delay);
  36471. }, delay);
  36472. }
  36473. /**
  36474. * start loading of the playlist
  36475. */
  36476. ;
  36477. _proto.start = function start() {
  36478. var _this7 = this;
  36479. this.started = true;
  36480. if (typeof this.src === 'object') {
  36481. // in the case of an entirely constructed manifest object (meaning there's no actual
  36482. // manifest on a server), default the uri to the page's href
  36483. if (!this.src.uri) {
  36484. this.src.uri = window.location.href;
  36485. } // resolvedUri is added on internally after the initial request. Since there's no
  36486. // request for pre-resolved manifests, add on resolvedUri here.
  36487. this.src.resolvedUri = this.src.uri; // Since a manifest object was passed in as the source (instead of a URL), the first
  36488. // request can be skipped (since the top level of the manifest, at a minimum, is
  36489. // already available as a parsed manifest object). However, if the manifest object
  36490. // represents a master playlist, some media playlists may need to be resolved before
  36491. // the starting segment list is available. Therefore, go directly to setup of the
  36492. // initial playlist, and let the normal flow continue from there.
  36493. //
  36494. // Note that the call to setup is asynchronous, as other sections of VHS may assume
  36495. // that the first request is asynchronous.
  36496. setTimeout(function () {
  36497. _this7.setupInitialPlaylist(_this7.src);
  36498. }, 0);
  36499. return;
  36500. } // request the specified URL
  36501. this.request = this.vhs_.xhr({
  36502. uri: this.src,
  36503. withCredentials: this.withCredentials
  36504. }, function (error, req) {
  36505. // disposed
  36506. if (!_this7.request) {
  36507. return;
  36508. } // clear the loader's request reference
  36509. _this7.request = null;
  36510. if (error) {
  36511. _this7.error = {
  36512. status: req.status,
  36513. message: "HLS playlist request error at URL: " + _this7.src + ".",
  36514. responseText: req.responseText,
  36515. // MEDIA_ERR_NETWORK
  36516. code: 2
  36517. };
  36518. if (_this7.state === 'HAVE_NOTHING') {
  36519. _this7.started = false;
  36520. }
  36521. return _this7.trigger('error');
  36522. }
  36523. _this7.src = resolveManifestRedirect(_this7.handleManifestRedirects, _this7.src, req);
  36524. var manifest = _this7.parseManifest_({
  36525. manifestString: req.responseText,
  36526. url: _this7.src
  36527. });
  36528. _this7.setupInitialPlaylist(manifest);
  36529. });
  36530. };
  36531. _proto.srcUri = function srcUri() {
  36532. return typeof this.src === 'string' ? this.src : this.src.uri;
  36533. }
  36534. /**
  36535. * Given a manifest object that's either a master or media playlist, trigger the proper
  36536. * events and set the state of the playlist loader.
  36537. *
  36538. * If the manifest object represents a master playlist, `loadedplaylist` will be
  36539. * triggered to allow listeners to select a playlist. If none is selected, the loader
  36540. * will default to the first one in the playlists array.
  36541. *
  36542. * If the manifest object represents a media playlist, `loadedplaylist` will be
  36543. * triggered followed by `loadedmetadata`, as the only available playlist is loaded.
  36544. *
  36545. * In the case of a media playlist, a master playlist object wrapper with one playlist
  36546. * will be created so that all logic can handle playlists in the same fashion (as an
  36547. * assumed manifest object schema).
  36548. *
  36549. * @param {Object} manifest
  36550. * The parsed manifest object
  36551. */
  36552. ;
  36553. _proto.setupInitialPlaylist = function setupInitialPlaylist(manifest) {
  36554. this.state = 'HAVE_MASTER';
  36555. if (manifest.playlists) {
  36556. this.master = manifest;
  36557. addPropertiesToMaster(this.master, this.srcUri()); // If the initial master playlist has playlists wtih segments already resolved,
  36558. // then resolve URIs in advance, as they are usually done after a playlist request,
  36559. // which may not happen if the playlist is resolved.
  36560. manifest.playlists.forEach(function (playlist) {
  36561. playlist.segments = getAllSegments(playlist);
  36562. playlist.segments.forEach(function (segment) {
  36563. resolveSegmentUris(segment, playlist.resolvedUri);
  36564. });
  36565. });
  36566. this.trigger('loadedplaylist');
  36567. if (!this.request) {
  36568. // no media playlist was specifically selected so start
  36569. // from the first listed one
  36570. this.media(this.master.playlists[0]);
  36571. }
  36572. return;
  36573. } // In order to support media playlists passed in as vhs-json, the case where the uri
  36574. // is not provided as part of the manifest should be considered, and an appropriate
  36575. // default used.
  36576. var uri = this.srcUri() || window.location.href;
  36577. this.master = masterForMedia(manifest, uri);
  36578. this.haveMetadata({
  36579. playlistObject: manifest,
  36580. url: uri,
  36581. id: this.master.playlists[0].id
  36582. });
  36583. this.trigger('loadedmetadata');
  36584. };
  36585. return PlaylistLoader;
  36586. }(EventTarget$1);
  36587. /**
  36588. * @file xhr.js
  36589. */
  36590. var videojsXHR = videojs.xhr,
  36591. mergeOptions$1 = videojs.mergeOptions;
  36592. var callbackWrapper = function callbackWrapper(request, error, response, callback) {
  36593. var reqResponse = request.responseType === 'arraybuffer' ? request.response : request.responseText;
  36594. if (!error && reqResponse) {
  36595. request.responseTime = Date.now();
  36596. request.roundTripTime = request.responseTime - request.requestTime;
  36597. request.bytesReceived = reqResponse.byteLength || reqResponse.length;
  36598. if (!request.bandwidth) {
  36599. request.bandwidth = Math.floor(request.bytesReceived / request.roundTripTime * 8 * 1000);
  36600. }
  36601. }
  36602. if (response.headers) {
  36603. request.responseHeaders = response.headers;
  36604. } // videojs.xhr now uses a specific code on the error
  36605. // object to signal that a request has timed out instead
  36606. // of setting a boolean on the request object
  36607. if (error && error.code === 'ETIMEDOUT') {
  36608. request.timedout = true;
  36609. } // videojs.xhr no longer considers status codes outside of 200 and 0
  36610. // (for file uris) to be errors, but the old XHR did, so emulate that
  36611. // behavior. Status 206 may be used in response to byterange requests.
  36612. if (!error && !request.aborted && response.statusCode !== 200 && response.statusCode !== 206 && response.statusCode !== 0) {
  36613. error = new Error('XHR Failed with a response of: ' + (request && (reqResponse || request.responseText)));
  36614. }
  36615. callback(error, request);
  36616. };
  36617. var xhrFactory = function xhrFactory() {
  36618. var xhr = function XhrFunction(options, callback) {
  36619. // Add a default timeout
  36620. options = mergeOptions$1({
  36621. timeout: 45e3
  36622. }, options); // Allow an optional user-specified function to modify the option
  36623. // object before we construct the xhr request
  36624. var beforeRequest = XhrFunction.beforeRequest || videojs.Vhs.xhr.beforeRequest;
  36625. if (beforeRequest && typeof beforeRequest === 'function') {
  36626. var newOptions = beforeRequest(options);
  36627. if (newOptions) {
  36628. options = newOptions;
  36629. }
  36630. } // Use the standard videojs.xhr() method unless `videojs.Vhs.xhr` has been overriden
  36631. // TODO: switch back to videojs.Vhs.xhr.name === 'XhrFunction' when we drop IE11
  36632. var xhrMethod = videojs.Vhs.xhr.original === true ? videojsXHR : videojs.Vhs.xhr;
  36633. var request = xhrMethod(options, function (error, response) {
  36634. return callbackWrapper(request, error, response, callback);
  36635. });
  36636. var originalAbort = request.abort;
  36637. request.abort = function () {
  36638. request.aborted = true;
  36639. return originalAbort.apply(request, arguments);
  36640. };
  36641. request.uri = options.uri;
  36642. request.requestTime = Date.now();
  36643. return request;
  36644. };
  36645. xhr.original = true;
  36646. return xhr;
  36647. };
  36648. /**
  36649. * Turns segment byterange into a string suitable for use in
  36650. * HTTP Range requests
  36651. *
  36652. * @param {Object} byterange - an object with two values defining the start and end
  36653. * of a byte-range
  36654. */
  36655. var byterangeStr = function byterangeStr(byterange) {
  36656. // `byterangeEnd` is one less than `offset + length` because the HTTP range
  36657. // header uses inclusive ranges
  36658. var byterangeEnd;
  36659. var byterangeStart = byterange.offset;
  36660. if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {
  36661. byterangeEnd = window.BigInt(byterange.offset) + window.BigInt(byterange.length) - window.BigInt(1);
  36662. } else {
  36663. byterangeEnd = byterange.offset + byterange.length - 1;
  36664. }
  36665. return 'bytes=' + byterangeStart + '-' + byterangeEnd;
  36666. };
  36667. /**
  36668. * Defines headers for use in the xhr request for a particular segment.
  36669. *
  36670. * @param {Object} segment - a simplified copy of the segmentInfo object
  36671. * from SegmentLoader
  36672. */
  36673. var segmentXhrHeaders = function segmentXhrHeaders(segment) {
  36674. var headers = {};
  36675. if (segment.byterange) {
  36676. headers.Range = byterangeStr(segment.byterange);
  36677. }
  36678. return headers;
  36679. };
  36680. /**
  36681. * @file bin-utils.js
  36682. */
  36683. /**
  36684. * convert a TimeRange to text
  36685. *
  36686. * @param {TimeRange} range the timerange to use for conversion
  36687. * @param {number} i the iterator on the range to convert
  36688. * @return {string} the range in string format
  36689. */
  36690. var textRange = function textRange(range, i) {
  36691. return range.start(i) + '-' + range.end(i);
  36692. };
  36693. /**
  36694. * format a number as hex string
  36695. *
  36696. * @param {number} e The number
  36697. * @param {number} i the iterator
  36698. * @return {string} the hex formatted number as a string
  36699. */
  36700. var formatHexString = function formatHexString(e, i) {
  36701. var value = e.toString(16);
  36702. return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');
  36703. };
  36704. var formatAsciiString = function formatAsciiString(e) {
  36705. if (e >= 0x20 && e < 0x7e) {
  36706. return String.fromCharCode(e);
  36707. }
  36708. return '.';
  36709. };
  36710. /**
  36711. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  36712. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  36713. *
  36714. * @param {Object} message
  36715. * Object of properties and values to send to the web worker
  36716. * @return {Object}
  36717. * Modified message with TypedArray values expanded
  36718. * @function createTransferableMessage
  36719. */
  36720. var createTransferableMessage = function createTransferableMessage(message) {
  36721. var transferable = {};
  36722. Object.keys(message).forEach(function (key) {
  36723. var value = message[key];
  36724. if (isArrayBufferView(value)) {
  36725. transferable[key] = {
  36726. bytes: value.buffer,
  36727. byteOffset: value.byteOffset,
  36728. byteLength: value.byteLength
  36729. };
  36730. } else {
  36731. transferable[key] = value;
  36732. }
  36733. });
  36734. return transferable;
  36735. };
  36736. /**
  36737. * Returns a unique string identifier for a media initialization
  36738. * segment.
  36739. *
  36740. * @param {Object} initSegment
  36741. * the init segment object.
  36742. *
  36743. * @return {string} the generated init segment id
  36744. */
  36745. var initSegmentId = function initSegmentId(initSegment) {
  36746. var byterange = initSegment.byterange || {
  36747. length: Infinity,
  36748. offset: 0
  36749. };
  36750. return [byterange.length, byterange.offset, initSegment.resolvedUri].join(',');
  36751. };
  36752. /**
  36753. * Returns a unique string identifier for a media segment key.
  36754. *
  36755. * @param {Object} key the encryption key
  36756. * @return {string} the unique id for the media segment key.
  36757. */
  36758. var segmentKeyId = function segmentKeyId(key) {
  36759. return key.resolvedUri;
  36760. };
  36761. /**
  36762. * utils to help dump binary data to the console
  36763. *
  36764. * @param {Array|TypedArray} data
  36765. * data to dump to a string
  36766. *
  36767. * @return {string} the data as a hex string.
  36768. */
  36769. var hexDump = function hexDump(data) {
  36770. var bytes = Array.prototype.slice.call(data);
  36771. var step = 16;
  36772. var result = '';
  36773. var hex;
  36774. var ascii;
  36775. for (var j = 0; j < bytes.length / step; j++) {
  36776. hex = bytes.slice(j * step, j * step + step).map(formatHexString).join('');
  36777. ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join('');
  36778. result += hex + ' ' + ascii + '\n';
  36779. }
  36780. return result;
  36781. };
  36782. var tagDump = function tagDump(_ref) {
  36783. var bytes = _ref.bytes;
  36784. return hexDump(bytes);
  36785. };
  36786. var textRanges = function textRanges(ranges) {
  36787. var result = '';
  36788. var i;
  36789. for (i = 0; i < ranges.length; i++) {
  36790. result += textRange(ranges, i) + ' ';
  36791. }
  36792. return result;
  36793. };
  36794. var utils = /*#__PURE__*/Object.freeze({
  36795. __proto__: null,
  36796. createTransferableMessage: createTransferableMessage,
  36797. initSegmentId: initSegmentId,
  36798. segmentKeyId: segmentKeyId,
  36799. hexDump: hexDump,
  36800. tagDump: tagDump,
  36801. textRanges: textRanges
  36802. }); // TODO handle fmp4 case where the timing info is accurate and doesn't involve transmux
  36803. // 25% was arbitrarily chosen, and may need to be refined over time.
  36804. var SEGMENT_END_FUDGE_PERCENT = 0.25;
  36805. /**
  36806. * Converts a player time (any time that can be gotten/set from player.currentTime(),
  36807. * e.g., any time within player.seekable().start(0) to player.seekable().end(0)) to a
  36808. * program time (any time referencing the real world (e.g., EXT-X-PROGRAM-DATE-TIME)).
  36809. *
  36810. * The containing segment is required as the EXT-X-PROGRAM-DATE-TIME serves as an "anchor
  36811. * point" (a point where we have a mapping from program time to player time, with player
  36812. * time being the post transmux start of the segment).
  36813. *
  36814. * For more details, see [this doc](../../docs/program-time-from-player-time.md).
  36815. *
  36816. * @param {number} playerTime the player time
  36817. * @param {Object} segment the segment which contains the player time
  36818. * @return {Date} program time
  36819. */
  36820. var playerTimeToProgramTime = function playerTimeToProgramTime(playerTime, segment) {
  36821. if (!segment.dateTimeObject) {
  36822. // Can't convert without an "anchor point" for the program time (i.e., a time that can
  36823. // be used to map the start of a segment with a real world time).
  36824. return null;
  36825. }
  36826. var transmuxerPrependedSeconds = segment.videoTimingInfo.transmuxerPrependedSeconds;
  36827. var transmuxedStart = segment.videoTimingInfo.transmuxedPresentationStart; // get the start of the content from before old content is prepended
  36828. var startOfSegment = transmuxedStart + transmuxerPrependedSeconds;
  36829. var offsetFromSegmentStart = playerTime - startOfSegment;
  36830. return new Date(segment.dateTimeObject.getTime() + offsetFromSegmentStart * 1000);
  36831. };
  36832. var originalSegmentVideoDuration = function originalSegmentVideoDuration(videoTimingInfo) {
  36833. return videoTimingInfo.transmuxedPresentationEnd - videoTimingInfo.transmuxedPresentationStart - videoTimingInfo.transmuxerPrependedSeconds;
  36834. };
  36835. /**
  36836. * Finds a segment that contains the time requested given as an ISO-8601 string. The
  36837. * returned segment might be an estimate or an accurate match.
  36838. *
  36839. * @param {string} programTime The ISO-8601 programTime to find a match for
  36840. * @param {Object} playlist A playlist object to search within
  36841. */
  36842. var findSegmentForProgramTime = function findSegmentForProgramTime(programTime, playlist) {
  36843. // Assumptions:
  36844. // - verifyProgramDateTimeTags has already been run
  36845. // - live streams have been started
  36846. var dateTimeObject;
  36847. try {
  36848. dateTimeObject = new Date(programTime);
  36849. } catch (e) {
  36850. return null;
  36851. }
  36852. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  36853. return null;
  36854. }
  36855. var segment = playlist.segments[0];
  36856. if (dateTimeObject < segment.dateTimeObject) {
  36857. // Requested time is before stream start.
  36858. return null;
  36859. }
  36860. for (var i = 0; i < playlist.segments.length - 1; i++) {
  36861. segment = playlist.segments[i];
  36862. var nextSegmentStart = playlist.segments[i + 1].dateTimeObject;
  36863. if (dateTimeObject < nextSegmentStart) {
  36864. break;
  36865. }
  36866. }
  36867. var lastSegment = playlist.segments[playlist.segments.length - 1];
  36868. var lastSegmentStart = lastSegment.dateTimeObject;
  36869. var lastSegmentDuration = lastSegment.videoTimingInfo ? originalSegmentVideoDuration(lastSegment.videoTimingInfo) : lastSegment.duration + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT;
  36870. var lastSegmentEnd = new Date(lastSegmentStart.getTime() + lastSegmentDuration * 1000);
  36871. if (dateTimeObject > lastSegmentEnd) {
  36872. // Beyond the end of the stream, or our best guess of the end of the stream.
  36873. return null;
  36874. }
  36875. if (dateTimeObject > lastSegmentStart) {
  36876. segment = lastSegment;
  36877. }
  36878. return {
  36879. segment: segment,
  36880. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : Playlist.duration(playlist, playlist.mediaSequence + playlist.segments.indexOf(segment)),
  36881. // Although, given that all segments have accurate date time objects, the segment
  36882. // selected should be accurate, unless the video has been transmuxed at some point
  36883. // (determined by the presence of the videoTimingInfo object), the segment's "player
  36884. // time" (the start time in the player) can't be considered accurate.
  36885. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  36886. };
  36887. };
  36888. /**
  36889. * Finds a segment that contains the given player time(in seconds).
  36890. *
  36891. * @param {number} time The player time to find a match for
  36892. * @param {Object} playlist A playlist object to search within
  36893. */
  36894. var findSegmentForPlayerTime = function findSegmentForPlayerTime(time, playlist) {
  36895. // Assumptions:
  36896. // - there will always be a segment.duration
  36897. // - we can start from zero
  36898. // - segments are in time order
  36899. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  36900. return null;
  36901. }
  36902. var segmentEnd = 0;
  36903. var segment;
  36904. for (var i = 0; i < playlist.segments.length; i++) {
  36905. segment = playlist.segments[i]; // videoTimingInfo is set after the segment is downloaded and transmuxed, and
  36906. // should contain the most accurate values we have for the segment's player times.
  36907. //
  36908. // Use the accurate transmuxedPresentationEnd value if it is available, otherwise fall
  36909. // back to an estimate based on the manifest derived (inaccurate) segment.duration, to
  36910. // calculate an end value.
  36911. segmentEnd = segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationEnd : segmentEnd + segment.duration;
  36912. if (time <= segmentEnd) {
  36913. break;
  36914. }
  36915. }
  36916. var lastSegment = playlist.segments[playlist.segments.length - 1];
  36917. if (lastSegment.videoTimingInfo && lastSegment.videoTimingInfo.transmuxedPresentationEnd < time) {
  36918. // The time requested is beyond the stream end.
  36919. return null;
  36920. }
  36921. if (time > segmentEnd) {
  36922. // The time is within or beyond the last segment.
  36923. //
  36924. // Check to see if the time is beyond a reasonable guess of the end of the stream.
  36925. if (time > segmentEnd + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT) {
  36926. // Technically, because the duration value is only an estimate, the time may still
  36927. // exist in the last segment, however, there isn't enough information to make even
  36928. // a reasonable estimate.
  36929. return null;
  36930. }
  36931. segment = lastSegment;
  36932. }
  36933. return {
  36934. segment: segment,
  36935. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : segmentEnd - segment.duration,
  36936. // Because videoTimingInfo is only set after transmux, it is the only way to get
  36937. // accurate timing values.
  36938. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  36939. };
  36940. };
  36941. /**
  36942. * Gives the offset of the comparisonTimestamp from the programTime timestamp in seconds.
  36943. * If the offset returned is positive, the programTime occurs after the
  36944. * comparisonTimestamp.
  36945. * If the offset is negative, the programTime occurs before the comparisonTimestamp.
  36946. *
  36947. * @param {string} comparisonTimeStamp An ISO-8601 timestamp to compare against
  36948. * @param {string} programTime The programTime as an ISO-8601 string
  36949. * @return {number} offset
  36950. */
  36951. var getOffsetFromTimestamp = function getOffsetFromTimestamp(comparisonTimeStamp, programTime) {
  36952. var segmentDateTime;
  36953. var programDateTime;
  36954. try {
  36955. segmentDateTime = new Date(comparisonTimeStamp);
  36956. programDateTime = new Date(programTime);
  36957. } catch (e) {// TODO handle error
  36958. }
  36959. var segmentTimeEpoch = segmentDateTime.getTime();
  36960. var programTimeEpoch = programDateTime.getTime();
  36961. return (programTimeEpoch - segmentTimeEpoch) / 1000;
  36962. };
  36963. /**
  36964. * Checks that all segments in this playlist have programDateTime tags.
  36965. *
  36966. * @param {Object} playlist A playlist object
  36967. */
  36968. var verifyProgramDateTimeTags = function verifyProgramDateTimeTags(playlist) {
  36969. if (!playlist.segments || playlist.segments.length === 0) {
  36970. return false;
  36971. }
  36972. for (var i = 0; i < playlist.segments.length; i++) {
  36973. var segment = playlist.segments[i];
  36974. if (!segment.dateTimeObject) {
  36975. return false;
  36976. }
  36977. }
  36978. return true;
  36979. };
  36980. /**
  36981. * Returns the programTime of the media given a playlist and a playerTime.
  36982. * The playlist must have programDateTime tags for a programDateTime tag to be returned.
  36983. * If the segments containing the time requested have not been buffered yet, an estimate
  36984. * may be returned to the callback.
  36985. *
  36986. * @param {Object} args
  36987. * @param {Object} args.playlist A playlist object to search within
  36988. * @param {number} time A playerTime in seconds
  36989. * @param {Function} callback(err, programTime)
  36990. * @return {string} err.message A detailed error message
  36991. * @return {Object} programTime
  36992. * @return {number} programTime.mediaSeconds The streamTime in seconds
  36993. * @return {string} programTime.programDateTime The programTime as an ISO-8601 String
  36994. */
  36995. var getProgramTime = function getProgramTime(_ref) {
  36996. var playlist = _ref.playlist,
  36997. _ref$time = _ref.time,
  36998. time = _ref$time === void 0 ? undefined : _ref$time,
  36999. callback = _ref.callback;
  37000. if (!callback) {
  37001. throw new Error('getProgramTime: callback must be provided');
  37002. }
  37003. if (!playlist || time === undefined) {
  37004. return callback({
  37005. message: 'getProgramTime: playlist and time must be provided'
  37006. });
  37007. }
  37008. var matchedSegment = findSegmentForPlayerTime(time, playlist);
  37009. if (!matchedSegment) {
  37010. return callback({
  37011. message: 'valid programTime was not found'
  37012. });
  37013. }
  37014. if (matchedSegment.type === 'estimate') {
  37015. return callback({
  37016. message: 'Accurate programTime could not be determined.' + ' Please seek to e.seekTime and try again',
  37017. seekTime: matchedSegment.estimatedStart
  37018. });
  37019. }
  37020. var programTimeObject = {
  37021. mediaSeconds: time
  37022. };
  37023. var programTime = playerTimeToProgramTime(time, matchedSegment.segment);
  37024. if (programTime) {
  37025. programTimeObject.programDateTime = programTime.toISOString();
  37026. }
  37027. return callback(null, programTimeObject);
  37028. };
  37029. /**
  37030. * Seeks in the player to a time that matches the given programTime ISO-8601 string.
  37031. *
  37032. * @param {Object} args
  37033. * @param {string} args.programTime A programTime to seek to as an ISO-8601 String
  37034. * @param {Object} args.playlist A playlist to look within
  37035. * @param {number} args.retryCount The number of times to try for an accurate seek. Default is 2.
  37036. * @param {Function} args.seekTo A method to perform a seek
  37037. * @param {boolean} args.pauseAfterSeek Whether to end in a paused state after seeking. Default is true.
  37038. * @param {Object} args.tech The tech to seek on
  37039. * @param {Function} args.callback(err, newTime) A callback to return the new time to
  37040. * @return {string} err.message A detailed error message
  37041. * @return {number} newTime The exact time that was seeked to in seconds
  37042. */
  37043. var seekToProgramTime = function seekToProgramTime(_ref2) {
  37044. var programTime = _ref2.programTime,
  37045. playlist = _ref2.playlist,
  37046. _ref2$retryCount = _ref2.retryCount,
  37047. retryCount = _ref2$retryCount === void 0 ? 2 : _ref2$retryCount,
  37048. seekTo = _ref2.seekTo,
  37049. _ref2$pauseAfterSeek = _ref2.pauseAfterSeek,
  37050. pauseAfterSeek = _ref2$pauseAfterSeek === void 0 ? true : _ref2$pauseAfterSeek,
  37051. tech = _ref2.tech,
  37052. callback = _ref2.callback;
  37053. if (!callback) {
  37054. throw new Error('seekToProgramTime: callback must be provided');
  37055. }
  37056. if (typeof programTime === 'undefined' || !playlist || !seekTo) {
  37057. return callback({
  37058. message: 'seekToProgramTime: programTime, seekTo and playlist must be provided'
  37059. });
  37060. }
  37061. if (!playlist.endList && !tech.hasStarted_) {
  37062. return callback({
  37063. message: 'player must be playing a live stream to start buffering'
  37064. });
  37065. }
  37066. if (!verifyProgramDateTimeTags(playlist)) {
  37067. return callback({
  37068. message: 'programDateTime tags must be provided in the manifest ' + playlist.resolvedUri
  37069. });
  37070. }
  37071. var matchedSegment = findSegmentForProgramTime(programTime, playlist); // no match
  37072. if (!matchedSegment) {
  37073. return callback({
  37074. message: programTime + " was not found in the stream"
  37075. });
  37076. }
  37077. var segment = matchedSegment.segment;
  37078. var mediaOffset = getOffsetFromTimestamp(segment.dateTimeObject, programTime);
  37079. if (matchedSegment.type === 'estimate') {
  37080. // we've run out of retries
  37081. if (retryCount === 0) {
  37082. return callback({
  37083. message: programTime + " is not buffered yet. Try again"
  37084. });
  37085. }
  37086. seekTo(matchedSegment.estimatedStart + mediaOffset);
  37087. tech.one('seeked', function () {
  37088. seekToProgramTime({
  37089. programTime: programTime,
  37090. playlist: playlist,
  37091. retryCount: retryCount - 1,
  37092. seekTo: seekTo,
  37093. pauseAfterSeek: pauseAfterSeek,
  37094. tech: tech,
  37095. callback: callback
  37096. });
  37097. });
  37098. return;
  37099. } // Since the segment.start value is determined from the buffered end or ending time
  37100. // of the prior segment, the seekToTime doesn't need to account for any transmuxer
  37101. // modifications.
  37102. var seekToTime = segment.start + mediaOffset;
  37103. var seekedCallback = function seekedCallback() {
  37104. return callback(null, tech.currentTime());
  37105. }; // listen for seeked event
  37106. tech.one('seeked', seekedCallback); // pause before seeking as video.js will restore this state
  37107. if (pauseAfterSeek) {
  37108. tech.pause();
  37109. }
  37110. seekTo(seekToTime);
  37111. }; // which will only happen if the request is complete.
  37112. var callbackOnCompleted = function callbackOnCompleted(request, cb) {
  37113. if (request.readyState === 4) {
  37114. return cb();
  37115. }
  37116. return;
  37117. };
  37118. var containerRequest = function containerRequest(uri, xhr, cb) {
  37119. var bytes = [];
  37120. var id3Offset;
  37121. var finished = false;
  37122. var endRequestAndCallback = function endRequestAndCallback(err, req, type, _bytes) {
  37123. req.abort();
  37124. finished = true;
  37125. return cb(err, req, type, _bytes);
  37126. };
  37127. var progressListener = function progressListener(error, request) {
  37128. if (finished) {
  37129. return;
  37130. }
  37131. if (error) {
  37132. return endRequestAndCallback(error, request, '', bytes);
  37133. } // grap the new part of content that was just downloaded
  37134. var newPart = request.responseText.substring(bytes && bytes.byteLength || 0, request.responseText.length); // add that onto bytes
  37135. bytes = concatTypedArrays(bytes, stringToBytes(newPart, true));
  37136. id3Offset = id3Offset || getId3Offset(bytes); // we need at least 10 bytes to determine a type
  37137. // or we need at least two bytes after an id3Offset
  37138. if (bytes.length < 10 || id3Offset && bytes.length < id3Offset + 2) {
  37139. return callbackOnCompleted(request, function () {
  37140. return endRequestAndCallback(error, request, '', bytes);
  37141. });
  37142. }
  37143. var type = detectContainerForBytes(bytes); // if this looks like a ts segment but we don't have enough data
  37144. // to see the second sync byte, wait until we have enough data
  37145. // before declaring it ts
  37146. if (type === 'ts' && bytes.length < 188) {
  37147. return callbackOnCompleted(request, function () {
  37148. return endRequestAndCallback(error, request, '', bytes);
  37149. });
  37150. } // this may be an unsynced ts segment
  37151. // wait for 376 bytes before detecting no container
  37152. if (!type && bytes.length < 376) {
  37153. return callbackOnCompleted(request, function () {
  37154. return endRequestAndCallback(error, request, '', bytes);
  37155. });
  37156. }
  37157. return endRequestAndCallback(null, request, type, bytes);
  37158. };
  37159. var options = {
  37160. uri: uri,
  37161. beforeSend: function beforeSend(request) {
  37162. // this forces the browser to pass the bytes to us unprocessed
  37163. request.overrideMimeType('text/plain; charset=x-user-defined');
  37164. request.addEventListener('progress', function (_ref) {
  37165. _ref.total;
  37166. _ref.loaded;
  37167. return callbackWrapper(request, null, {
  37168. statusCode: request.status
  37169. }, progressListener);
  37170. });
  37171. }
  37172. };
  37173. var request = xhr(options, function (error, response) {
  37174. return callbackWrapper(request, error, response, progressListener);
  37175. });
  37176. return request;
  37177. };
  37178. var EventTarget = videojs.EventTarget,
  37179. mergeOptions = videojs.mergeOptions;
  37180. var dashPlaylistUnchanged = function dashPlaylistUnchanged(a, b) {
  37181. if (!isPlaylistUnchanged(a, b)) {
  37182. return false;
  37183. } // for dash the above check will often return true in scenarios where
  37184. // the playlist actually has changed because mediaSequence isn't a
  37185. // dash thing, and we often set it to 1. So if the playlists have the same amount
  37186. // of segments we return true.
  37187. // So for dash we need to make sure that the underlying segments are different.
  37188. // if sidx changed then the playlists are different.
  37189. if (a.sidx && b.sidx && (a.sidx.offset !== b.sidx.offset || a.sidx.length !== b.sidx.length)) {
  37190. return false;
  37191. } else if (!a.sidx && b.sidx || a.sidx && !b.sidx) {
  37192. return false;
  37193. } // one or the other does not have segments
  37194. // there was a change.
  37195. if (a.segments && !b.segments || !a.segments && b.segments) {
  37196. return false;
  37197. } // neither has segments nothing changed
  37198. if (!a.segments && !b.segments) {
  37199. return true;
  37200. } // check segments themselves
  37201. for (var i = 0; i < a.segments.length; i++) {
  37202. var aSegment = a.segments[i];
  37203. var bSegment = b.segments[i]; // if uris are different between segments there was a change
  37204. if (aSegment.uri !== bSegment.uri) {
  37205. return false;
  37206. } // neither segment has a byterange, there will be no byterange change.
  37207. if (!aSegment.byterange && !bSegment.byterange) {
  37208. continue;
  37209. }
  37210. var aByterange = aSegment.byterange;
  37211. var bByterange = bSegment.byterange; // if byterange only exists on one of the segments, there was a change.
  37212. if (aByterange && !bByterange || !aByterange && bByterange) {
  37213. return false;
  37214. } // if both segments have byterange with different offsets, there was a change.
  37215. if (aByterange.offset !== bByterange.offset || aByterange.length !== bByterange.length) {
  37216. return false;
  37217. }
  37218. } // if everything was the same with segments, this is the same playlist.
  37219. return true;
  37220. };
  37221. /**
  37222. * Use the representation IDs from the mpd object to create groupIDs, the NAME is set to mandatory representation
  37223. * ID in the parser. This allows for continuous playout across periods with the same representation IDs
  37224. * (continuous periods as defined in DASH-IF 3.2.12). This is assumed in the mpd-parser as well. If we want to support
  37225. * periods without continuous playback this function may need modification as well as the parser.
  37226. */
  37227. var dashGroupId = function dashGroupId(type, group, label, playlist) {
  37228. // If the manifest somehow does not have an ID (non-dash compliant), use the label.
  37229. var playlistId = playlist.attributes.NAME || label;
  37230. return "placeholder-uri-" + type + "-" + group + "-" + playlistId;
  37231. };
  37232. /**
  37233. * Parses the master XML string and updates playlist URI references.
  37234. *
  37235. * @param {Object} config
  37236. * Object of arguments
  37237. * @param {string} config.masterXml
  37238. * The mpd XML
  37239. * @param {string} config.srcUrl
  37240. * The mpd URL
  37241. * @param {Date} config.clientOffset
  37242. * A time difference between server and client
  37243. * @param {Object} config.sidxMapping
  37244. * SIDX mappings for moof/mdat URIs and byte ranges
  37245. * @return {Object}
  37246. * The parsed mpd manifest object
  37247. */
  37248. var parseMasterXml = function parseMasterXml(_ref) {
  37249. var masterXml = _ref.masterXml,
  37250. srcUrl = _ref.srcUrl,
  37251. clientOffset = _ref.clientOffset,
  37252. sidxMapping = _ref.sidxMapping,
  37253. previousManifest = _ref.previousManifest;
  37254. var manifest = parse(masterXml, {
  37255. manifestUri: srcUrl,
  37256. clientOffset: clientOffset,
  37257. sidxMapping: sidxMapping,
  37258. previousManifest: previousManifest
  37259. });
  37260. addPropertiesToMaster(manifest, srcUrl, dashGroupId);
  37261. return manifest;
  37262. };
  37263. /**
  37264. * Removes any mediaGroup labels that no longer exist in the newMaster
  37265. *
  37266. * @param {Object} update
  37267. * The previous mpd object being updated
  37268. * @param {Object} newMaster
  37269. * The new mpd object
  37270. */
  37271. var removeOldMediaGroupLabels = function removeOldMediaGroupLabels(update, newMaster) {
  37272. forEachMediaGroup(update, function (properties, type, group, label) {
  37273. if (!(label in newMaster.mediaGroups[type][group])) {
  37274. delete update.mediaGroups[type][group][label];
  37275. }
  37276. });
  37277. };
  37278. /**
  37279. * Returns a new master manifest that is the result of merging an updated master manifest
  37280. * into the original version.
  37281. *
  37282. * @param {Object} oldMaster
  37283. * The old parsed mpd object
  37284. * @param {Object} newMaster
  37285. * The updated parsed mpd object
  37286. * @return {Object}
  37287. * A new object representing the original master manifest with the updated media
  37288. * playlists merged in
  37289. */
  37290. var updateMaster = function updateMaster(oldMaster, newMaster, sidxMapping) {
  37291. var noChanges = true;
  37292. var update = mergeOptions(oldMaster, {
  37293. // These are top level properties that can be updated
  37294. duration: newMaster.duration,
  37295. minimumUpdatePeriod: newMaster.minimumUpdatePeriod,
  37296. timelineStarts: newMaster.timelineStarts
  37297. }); // First update the playlists in playlist list
  37298. for (var i = 0; i < newMaster.playlists.length; i++) {
  37299. var playlist = newMaster.playlists[i];
  37300. if (playlist.sidx) {
  37301. var sidxKey = generateSidxKey(playlist.sidx); // add sidx segments to the playlist if we have all the sidx info already
  37302. if (sidxMapping && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx) {
  37303. addSidxSegmentsToPlaylist$1(playlist, sidxMapping[sidxKey].sidx, playlist.sidx.resolvedUri);
  37304. }
  37305. }
  37306. var playlistUpdate = updateMaster$1(update, playlist, dashPlaylistUnchanged);
  37307. if (playlistUpdate) {
  37308. update = playlistUpdate;
  37309. noChanges = false;
  37310. }
  37311. } // Then update media group playlists
  37312. forEachMediaGroup(newMaster, function (properties, type, group, label) {
  37313. if (properties.playlists && properties.playlists.length) {
  37314. var id = properties.playlists[0].id;
  37315. var _playlistUpdate = updateMaster$1(update, properties.playlists[0], dashPlaylistUnchanged);
  37316. if (_playlistUpdate) {
  37317. update = _playlistUpdate; // add new mediaGroup label if it doesn't exist and assign the new mediaGroup.
  37318. if (!(label in update.mediaGroups[type][group])) {
  37319. update.mediaGroups[type][group][label] = properties;
  37320. } // update the playlist reference within media groups
  37321. update.mediaGroups[type][group][label].playlists[0] = update.playlists[id];
  37322. noChanges = false;
  37323. }
  37324. }
  37325. }); // remove mediaGroup labels and references that no longer exist in the newMaster
  37326. removeOldMediaGroupLabels(update, newMaster);
  37327. if (newMaster.minimumUpdatePeriod !== oldMaster.minimumUpdatePeriod) {
  37328. noChanges = false;
  37329. }
  37330. if (noChanges) {
  37331. return null;
  37332. }
  37333. return update;
  37334. }; // SIDX should be equivalent if the URI and byteranges of the SIDX match.
  37335. // If the SIDXs have maps, the two maps should match,
  37336. // both `a` and `b` missing SIDXs is considered matching.
  37337. // If `a` or `b` but not both have a map, they aren't matching.
  37338. var equivalentSidx = function equivalentSidx(a, b) {
  37339. var neitherMap = Boolean(!a.map && !b.map);
  37340. var equivalentMap = neitherMap || Boolean(a.map && b.map && a.map.byterange.offset === b.map.byterange.offset && a.map.byterange.length === b.map.byterange.length);
  37341. return equivalentMap && a.uri === b.uri && a.byterange.offset === b.byterange.offset && a.byterange.length === b.byterange.length;
  37342. }; // exported for testing
  37343. var compareSidxEntry = function compareSidxEntry(playlists, oldSidxMapping) {
  37344. var newSidxMapping = {};
  37345. for (var id in playlists) {
  37346. var playlist = playlists[id];
  37347. var currentSidxInfo = playlist.sidx;
  37348. if (currentSidxInfo) {
  37349. var key = generateSidxKey(currentSidxInfo);
  37350. if (!oldSidxMapping[key]) {
  37351. break;
  37352. }
  37353. var savedSidxInfo = oldSidxMapping[key].sidxInfo;
  37354. if (equivalentSidx(savedSidxInfo, currentSidxInfo)) {
  37355. newSidxMapping[key] = oldSidxMapping[key];
  37356. }
  37357. }
  37358. }
  37359. return newSidxMapping;
  37360. };
  37361. /**
  37362. * A function that filters out changed items as they need to be requested separately.
  37363. *
  37364. * The method is exported for testing
  37365. *
  37366. * @param {Object} master the parsed mpd XML returned via mpd-parser
  37367. * @param {Object} oldSidxMapping the SIDX to compare against
  37368. */
  37369. var filterChangedSidxMappings = function filterChangedSidxMappings(master, oldSidxMapping) {
  37370. var videoSidx = compareSidxEntry(master.playlists, oldSidxMapping);
  37371. var mediaGroupSidx = videoSidx;
  37372. forEachMediaGroup(master, function (properties, mediaType, groupKey, labelKey) {
  37373. if (properties.playlists && properties.playlists.length) {
  37374. var playlists = properties.playlists;
  37375. mediaGroupSidx = mergeOptions(mediaGroupSidx, compareSidxEntry(playlists, oldSidxMapping));
  37376. }
  37377. });
  37378. return mediaGroupSidx;
  37379. };
  37380. var DashPlaylistLoader = /*#__PURE__*/function (_EventTarget) {
  37381. inheritsLoose(DashPlaylistLoader, _EventTarget); // DashPlaylistLoader must accept either a src url or a playlist because subsequent
  37382. // playlist loader setups from media groups will expect to be able to pass a playlist
  37383. // (since there aren't external URLs to media playlists with DASH)
  37384. function DashPlaylistLoader(srcUrlOrPlaylist, vhs, options, masterPlaylistLoader) {
  37385. var _this;
  37386. if (options === void 0) {
  37387. options = {};
  37388. }
  37389. _this = _EventTarget.call(this) || this;
  37390. _this.masterPlaylistLoader_ = masterPlaylistLoader || assertThisInitialized(_this);
  37391. if (!masterPlaylistLoader) {
  37392. _this.isMaster_ = true;
  37393. }
  37394. var _options = options,
  37395. _options$withCredenti = _options.withCredentials,
  37396. withCredentials = _options$withCredenti === void 0 ? false : _options$withCredenti,
  37397. _options$handleManife = _options.handleManifestRedirects,
  37398. handleManifestRedirects = _options$handleManife === void 0 ? false : _options$handleManife;
  37399. _this.vhs_ = vhs;
  37400. _this.withCredentials = withCredentials;
  37401. _this.handleManifestRedirects = handleManifestRedirects;
  37402. if (!srcUrlOrPlaylist) {
  37403. throw new Error('A non-empty playlist URL or object is required');
  37404. } // event naming?
  37405. _this.on('minimumUpdatePeriod', function () {
  37406. _this.refreshXml_();
  37407. }); // live playlist staleness timeout
  37408. _this.on('mediaupdatetimeout', function () {
  37409. _this.refreshMedia_(_this.media().id);
  37410. });
  37411. _this.state = 'HAVE_NOTHING';
  37412. _this.loadedPlaylists_ = {};
  37413. _this.logger_ = logger('DashPlaylistLoader'); // initialize the loader state
  37414. // The masterPlaylistLoader will be created with a string
  37415. if (_this.isMaster_) {
  37416. _this.masterPlaylistLoader_.srcUrl = srcUrlOrPlaylist; // TODO: reset sidxMapping between period changes
  37417. // once multi-period is refactored
  37418. _this.masterPlaylistLoader_.sidxMapping_ = {};
  37419. } else {
  37420. _this.childPlaylist_ = srcUrlOrPlaylist;
  37421. }
  37422. return _this;
  37423. }
  37424. var _proto = DashPlaylistLoader.prototype;
  37425. _proto.requestErrored_ = function requestErrored_(err, request, startingState) {
  37426. // disposed
  37427. if (!this.request) {
  37428. return true;
  37429. } // pending request is cleared
  37430. this.request = null;
  37431. if (err) {
  37432. // use the provided error object or create one
  37433. // based on the request/response
  37434. this.error = typeof err === 'object' && !(err instanceof Error) ? err : {
  37435. status: request.status,
  37436. message: 'DASH request error at URL: ' + request.uri,
  37437. response: request.response,
  37438. // MEDIA_ERR_NETWORK
  37439. code: 2
  37440. };
  37441. if (startingState) {
  37442. this.state = startingState;
  37443. }
  37444. this.trigger('error');
  37445. return true;
  37446. }
  37447. }
  37448. /**
  37449. * Verify that the container of the sidx segment can be parsed
  37450. * and if it can, get and parse that segment.
  37451. */
  37452. ;
  37453. _proto.addSidxSegments_ = function addSidxSegments_(playlist, startingState, cb) {
  37454. var _this2 = this;
  37455. var sidxKey = playlist.sidx && generateSidxKey(playlist.sidx); // playlist lacks sidx or sidx segments were added to this playlist already.
  37456. if (!playlist.sidx || !sidxKey || this.masterPlaylistLoader_.sidxMapping_[sidxKey]) {
  37457. // keep this function async
  37458. this.mediaRequest_ = window.setTimeout(function () {
  37459. return cb(false);
  37460. }, 0);
  37461. return;
  37462. } // resolve the segment URL relative to the playlist
  37463. var uri = resolveManifestRedirect(this.handleManifestRedirects, playlist.sidx.resolvedUri);
  37464. var fin = function fin(err, request) {
  37465. if (_this2.requestErrored_(err, request, startingState)) {
  37466. return;
  37467. }
  37468. var sidxMapping = _this2.masterPlaylistLoader_.sidxMapping_;
  37469. var sidx;
  37470. try {
  37471. sidx = parseSidx_1(toUint8(request.response).subarray(8));
  37472. } catch (e) {
  37473. // sidx parsing failed.
  37474. _this2.requestErrored_(e, request, startingState);
  37475. return;
  37476. }
  37477. sidxMapping[sidxKey] = {
  37478. sidxInfo: playlist.sidx,
  37479. sidx: sidx
  37480. };
  37481. addSidxSegmentsToPlaylist$1(playlist, sidx, playlist.sidx.resolvedUri);
  37482. return cb(true);
  37483. };
  37484. this.request = containerRequest(uri, this.vhs_.xhr, function (err, request, container, bytes) {
  37485. if (err) {
  37486. return fin(err, request);
  37487. }
  37488. if (!container || container !== 'mp4') {
  37489. return fin({
  37490. status: request.status,
  37491. message: "Unsupported " + (container || 'unknown') + " container type for sidx segment at URL: " + uri,
  37492. // response is just bytes in this case
  37493. // but we really don't want to return that.
  37494. response: '',
  37495. playlist: playlist,
  37496. internal: true,
  37497. blacklistDuration: Infinity,
  37498. // MEDIA_ERR_NETWORK
  37499. code: 2
  37500. }, request);
  37501. } // if we already downloaded the sidx bytes in the container request, use them
  37502. var _playlist$sidx$bytera = playlist.sidx.byterange,
  37503. offset = _playlist$sidx$bytera.offset,
  37504. length = _playlist$sidx$bytera.length;
  37505. if (bytes.length >= length + offset) {
  37506. return fin(err, {
  37507. response: bytes.subarray(offset, offset + length),
  37508. status: request.status,
  37509. uri: request.uri
  37510. });
  37511. } // otherwise request sidx bytes
  37512. _this2.request = _this2.vhs_.xhr({
  37513. uri: uri,
  37514. responseType: 'arraybuffer',
  37515. headers: segmentXhrHeaders({
  37516. byterange: playlist.sidx.byterange
  37517. })
  37518. }, fin);
  37519. });
  37520. };
  37521. _proto.dispose = function dispose() {
  37522. this.trigger('dispose');
  37523. this.stopRequest();
  37524. this.loadedPlaylists_ = {};
  37525. window.clearTimeout(this.minimumUpdatePeriodTimeout_);
  37526. window.clearTimeout(this.mediaRequest_);
  37527. window.clearTimeout(this.mediaUpdateTimeout);
  37528. this.mediaUpdateTimeout = null;
  37529. this.mediaRequest_ = null;
  37530. this.minimumUpdatePeriodTimeout_ = null;
  37531. if (this.masterPlaylistLoader_.createMupOnMedia_) {
  37532. this.off('loadedmetadata', this.masterPlaylistLoader_.createMupOnMedia_);
  37533. this.masterPlaylistLoader_.createMupOnMedia_ = null;
  37534. }
  37535. this.off();
  37536. };
  37537. _proto.hasPendingRequest = function hasPendingRequest() {
  37538. return this.request || this.mediaRequest_;
  37539. };
  37540. _proto.stopRequest = function stopRequest() {
  37541. if (this.request) {
  37542. var oldRequest = this.request;
  37543. this.request = null;
  37544. oldRequest.onreadystatechange = null;
  37545. oldRequest.abort();
  37546. }
  37547. };
  37548. _proto.media = function media(playlist) {
  37549. var _this3 = this; // getter
  37550. if (!playlist) {
  37551. return this.media_;
  37552. } // setter
  37553. if (this.state === 'HAVE_NOTHING') {
  37554. throw new Error('Cannot switch media playlist from ' + this.state);
  37555. }
  37556. var startingState = this.state; // find the playlist object if the target playlist has been specified by URI
  37557. if (typeof playlist === 'string') {
  37558. if (!this.masterPlaylistLoader_.master.playlists[playlist]) {
  37559. throw new Error('Unknown playlist URI: ' + playlist);
  37560. }
  37561. playlist = this.masterPlaylistLoader_.master.playlists[playlist];
  37562. }
  37563. var mediaChange = !this.media_ || playlist.id !== this.media_.id; // switch to previously loaded playlists immediately
  37564. if (mediaChange && this.loadedPlaylists_[playlist.id] && this.loadedPlaylists_[playlist.id].endList) {
  37565. this.state = 'HAVE_METADATA';
  37566. this.media_ = playlist; // trigger media change if the active media has been updated
  37567. if (mediaChange) {
  37568. this.trigger('mediachanging');
  37569. this.trigger('mediachange');
  37570. }
  37571. return;
  37572. } // switching to the active playlist is a no-op
  37573. if (!mediaChange) {
  37574. return;
  37575. } // switching from an already loaded playlist
  37576. if (this.media_) {
  37577. this.trigger('mediachanging');
  37578. }
  37579. this.addSidxSegments_(playlist, startingState, function (sidxChanged) {
  37580. // everything is ready just continue to haveMetadata
  37581. _this3.haveMetadata({
  37582. startingState: startingState,
  37583. playlist: playlist
  37584. });
  37585. });
  37586. };
  37587. _proto.haveMetadata = function haveMetadata(_ref2) {
  37588. var startingState = _ref2.startingState,
  37589. playlist = _ref2.playlist;
  37590. this.state = 'HAVE_METADATA';
  37591. this.loadedPlaylists_[playlist.id] = playlist;
  37592. this.mediaRequest_ = null; // This will trigger loadedplaylist
  37593. this.refreshMedia_(playlist.id); // fire loadedmetadata the first time a media playlist is loaded
  37594. // to resolve setup of media groups
  37595. if (startingState === 'HAVE_MASTER') {
  37596. this.trigger('loadedmetadata');
  37597. } else {
  37598. // trigger media change if the active media has been updated
  37599. this.trigger('mediachange');
  37600. }
  37601. };
  37602. _proto.pause = function pause() {
  37603. if (this.masterPlaylistLoader_.createMupOnMedia_) {
  37604. this.off('loadedmetadata', this.masterPlaylistLoader_.createMupOnMedia_);
  37605. this.masterPlaylistLoader_.createMupOnMedia_ = null;
  37606. }
  37607. this.stopRequest();
  37608. window.clearTimeout(this.mediaUpdateTimeout);
  37609. this.mediaUpdateTimeout = null;
  37610. if (this.isMaster_) {
  37611. window.clearTimeout(this.masterPlaylistLoader_.minimumUpdatePeriodTimeout_);
  37612. this.masterPlaylistLoader_.minimumUpdatePeriodTimeout_ = null;
  37613. }
  37614. if (this.state === 'HAVE_NOTHING') {
  37615. // If we pause the loader before any data has been retrieved, its as if we never
  37616. // started, so reset to an unstarted state.
  37617. this.started = false;
  37618. }
  37619. };
  37620. _proto.load = function load(isFinalRendition) {
  37621. var _this4 = this;
  37622. window.clearTimeout(this.mediaUpdateTimeout);
  37623. this.mediaUpdateTimeout = null;
  37624. var media = this.media();
  37625. if (isFinalRendition) {
  37626. var delay = media ? media.targetDuration / 2 * 1000 : 5 * 1000;
  37627. this.mediaUpdateTimeout = window.setTimeout(function () {
  37628. return _this4.load();
  37629. }, delay);
  37630. return;
  37631. } // because the playlists are internal to the manifest, load should either load the
  37632. // main manifest, or do nothing but trigger an event
  37633. if (!this.started) {
  37634. this.start();
  37635. return;
  37636. }
  37637. if (media && !media.endList) {
  37638. // Check to see if this is the master loader and the MUP was cleared (this happens
  37639. // when the loader was paused). `media` should be set at this point since one is always
  37640. // set during `start()`.
  37641. if (this.isMaster_ && !this.minimumUpdatePeriodTimeout_) {
  37642. // Trigger minimumUpdatePeriod to refresh the master manifest
  37643. this.trigger('minimumUpdatePeriod'); // Since there was no prior minimumUpdatePeriodTimeout it should be recreated
  37644. this.updateMinimumUpdatePeriodTimeout_();
  37645. }
  37646. this.trigger('mediaupdatetimeout');
  37647. } else {
  37648. this.trigger('loadedplaylist');
  37649. }
  37650. };
  37651. _proto.start = function start() {
  37652. var _this5 = this;
  37653. this.started = true; // We don't need to request the master manifest again
  37654. // Call this asynchronously to match the xhr request behavior below
  37655. if (!this.isMaster_) {
  37656. this.mediaRequest_ = window.setTimeout(function () {
  37657. return _this5.haveMaster_();
  37658. }, 0);
  37659. return;
  37660. }
  37661. this.requestMaster_(function (req, masterChanged) {
  37662. _this5.haveMaster_();
  37663. if (!_this5.hasPendingRequest() && !_this5.media_) {
  37664. _this5.media(_this5.masterPlaylistLoader_.master.playlists[0]);
  37665. }
  37666. });
  37667. };
  37668. _proto.requestMaster_ = function requestMaster_(cb) {
  37669. var _this6 = this;
  37670. this.request = this.vhs_.xhr({
  37671. uri: this.masterPlaylistLoader_.srcUrl,
  37672. withCredentials: this.withCredentials
  37673. }, function (error, req) {
  37674. if (_this6.requestErrored_(error, req)) {
  37675. if (_this6.state === 'HAVE_NOTHING') {
  37676. _this6.started = false;
  37677. }
  37678. return;
  37679. }
  37680. var masterChanged = req.responseText !== _this6.masterPlaylistLoader_.masterXml_;
  37681. _this6.masterPlaylistLoader_.masterXml_ = req.responseText;
  37682. if (req.responseHeaders && req.responseHeaders.date) {
  37683. _this6.masterLoaded_ = Date.parse(req.responseHeaders.date);
  37684. } else {
  37685. _this6.masterLoaded_ = Date.now();
  37686. }
  37687. _this6.masterPlaylistLoader_.srcUrl = resolveManifestRedirect(_this6.handleManifestRedirects, _this6.masterPlaylistLoader_.srcUrl, req);
  37688. if (masterChanged) {
  37689. _this6.handleMaster_();
  37690. _this6.syncClientServerClock_(function () {
  37691. return cb(req, masterChanged);
  37692. });
  37693. return;
  37694. }
  37695. return cb(req, masterChanged);
  37696. });
  37697. }
  37698. /**
  37699. * Parses the master xml for UTCTiming node to sync the client clock to the server
  37700. * clock. If the UTCTiming node requires a HEAD or GET request, that request is made.
  37701. *
  37702. * @param {Function} done
  37703. * Function to call when clock sync has completed
  37704. */
  37705. ;
  37706. _proto.syncClientServerClock_ = function syncClientServerClock_(done) {
  37707. var _this7 = this;
  37708. var utcTiming = parseUTCTiming(this.masterPlaylistLoader_.masterXml_); // No UTCTiming element found in the mpd. Use Date header from mpd request as the
  37709. // server clock
  37710. if (utcTiming === null) {
  37711. this.masterPlaylistLoader_.clientOffset_ = this.masterLoaded_ - Date.now();
  37712. return done();
  37713. }
  37714. if (utcTiming.method === 'DIRECT') {
  37715. this.masterPlaylistLoader_.clientOffset_ = utcTiming.value - Date.now();
  37716. return done();
  37717. }
  37718. this.request = this.vhs_.xhr({
  37719. uri: resolveUrl(this.masterPlaylistLoader_.srcUrl, utcTiming.value),
  37720. method: utcTiming.method,
  37721. withCredentials: this.withCredentials
  37722. }, function (error, req) {
  37723. // disposed
  37724. if (!_this7.request) {
  37725. return;
  37726. }
  37727. if (error) {
  37728. // sync request failed, fall back to using date header from mpd
  37729. // TODO: log warning
  37730. _this7.masterPlaylistLoader_.clientOffset_ = _this7.masterLoaded_ - Date.now();
  37731. return done();
  37732. }
  37733. var serverTime;
  37734. if (utcTiming.method === 'HEAD') {
  37735. if (!req.responseHeaders || !req.responseHeaders.date) {
  37736. // expected date header not preset, fall back to using date header from mpd
  37737. // TODO: log warning
  37738. serverTime = _this7.masterLoaded_;
  37739. } else {
  37740. serverTime = Date.parse(req.responseHeaders.date);
  37741. }
  37742. } else {
  37743. serverTime = Date.parse(req.responseText);
  37744. }
  37745. _this7.masterPlaylistLoader_.clientOffset_ = serverTime - Date.now();
  37746. done();
  37747. });
  37748. };
  37749. _proto.haveMaster_ = function haveMaster_() {
  37750. this.state = 'HAVE_MASTER';
  37751. if (this.isMaster_) {
  37752. // We have the master playlist at this point, so
  37753. // trigger this to allow MasterPlaylistController
  37754. // to make an initial playlist selection
  37755. this.trigger('loadedplaylist');
  37756. } else if (!this.media_) {
  37757. // no media playlist was specifically selected so select
  37758. // the one the child playlist loader was created with
  37759. this.media(this.childPlaylist_);
  37760. }
  37761. };
  37762. _proto.handleMaster_ = function handleMaster_() {
  37763. // clear media request
  37764. this.mediaRequest_ = null;
  37765. var oldMaster = this.masterPlaylistLoader_.master;
  37766. var newMaster = parseMasterXml({
  37767. masterXml: this.masterPlaylistLoader_.masterXml_,
  37768. srcUrl: this.masterPlaylistLoader_.srcUrl,
  37769. clientOffset: this.masterPlaylistLoader_.clientOffset_,
  37770. sidxMapping: this.masterPlaylistLoader_.sidxMapping_,
  37771. previousManifest: oldMaster
  37772. }); // if we have an old master to compare the new master against
  37773. if (oldMaster) {
  37774. newMaster = updateMaster(oldMaster, newMaster, this.masterPlaylistLoader_.sidxMapping_);
  37775. } // only update master if we have a new master
  37776. this.masterPlaylistLoader_.master = newMaster ? newMaster : oldMaster;
  37777. var location = this.masterPlaylistLoader_.master.locations && this.masterPlaylistLoader_.master.locations[0];
  37778. if (location && location !== this.masterPlaylistLoader_.srcUrl) {
  37779. this.masterPlaylistLoader_.srcUrl = location;
  37780. }
  37781. if (!oldMaster || newMaster && newMaster.minimumUpdatePeriod !== oldMaster.minimumUpdatePeriod) {
  37782. this.updateMinimumUpdatePeriodTimeout_();
  37783. }
  37784. return Boolean(newMaster);
  37785. };
  37786. _proto.updateMinimumUpdatePeriodTimeout_ = function updateMinimumUpdatePeriodTimeout_() {
  37787. var mpl = this.masterPlaylistLoader_; // cancel any pending creation of mup on media
  37788. // a new one will be added if needed.
  37789. if (mpl.createMupOnMedia_) {
  37790. mpl.off('loadedmetadata', mpl.createMupOnMedia_);
  37791. mpl.createMupOnMedia_ = null;
  37792. } // clear any pending timeouts
  37793. if (mpl.minimumUpdatePeriodTimeout_) {
  37794. window.clearTimeout(mpl.minimumUpdatePeriodTimeout_);
  37795. mpl.minimumUpdatePeriodTimeout_ = null;
  37796. }
  37797. var mup = mpl.master && mpl.master.minimumUpdatePeriod; // If the minimumUpdatePeriod has a value of 0, that indicates that the current
  37798. // MPD has no future validity, so a new one will need to be acquired when new
  37799. // media segments are to be made available. Thus, we use the target duration
  37800. // in this case
  37801. if (mup === 0) {
  37802. if (mpl.media()) {
  37803. mup = mpl.media().targetDuration * 1000;
  37804. } else {
  37805. mpl.createMupOnMedia_ = mpl.updateMinimumUpdatePeriodTimeout_;
  37806. mpl.one('loadedmetadata', mpl.createMupOnMedia_);
  37807. }
  37808. } // if minimumUpdatePeriod is invalid or <= zero, which
  37809. // can happen when a live video becomes VOD. skip timeout
  37810. // creation.
  37811. if (typeof mup !== 'number' || mup <= 0) {
  37812. if (mup < 0) {
  37813. this.logger_("found invalid minimumUpdatePeriod of " + mup + ", not setting a timeout");
  37814. }
  37815. return;
  37816. }
  37817. this.createMUPTimeout_(mup);
  37818. };
  37819. _proto.createMUPTimeout_ = function createMUPTimeout_(mup) {
  37820. var mpl = this.masterPlaylistLoader_;
  37821. mpl.minimumUpdatePeriodTimeout_ = window.setTimeout(function () {
  37822. mpl.minimumUpdatePeriodTimeout_ = null;
  37823. mpl.trigger('minimumUpdatePeriod');
  37824. mpl.createMUPTimeout_(mup);
  37825. }, mup);
  37826. }
  37827. /**
  37828. * Sends request to refresh the master xml and updates the parsed master manifest
  37829. */
  37830. ;
  37831. _proto.refreshXml_ = function refreshXml_() {
  37832. var _this8 = this;
  37833. this.requestMaster_(function (req, masterChanged) {
  37834. if (!masterChanged) {
  37835. return;
  37836. }
  37837. if (_this8.media_) {
  37838. _this8.media_ = _this8.masterPlaylistLoader_.master.playlists[_this8.media_.id];
  37839. } // This will filter out updated sidx info from the mapping
  37840. _this8.masterPlaylistLoader_.sidxMapping_ = filterChangedSidxMappings(_this8.masterPlaylistLoader_.master, _this8.masterPlaylistLoader_.sidxMapping_);
  37841. _this8.addSidxSegments_(_this8.media(), _this8.state, function (sidxChanged) {
  37842. // TODO: do we need to reload the current playlist?
  37843. _this8.refreshMedia_(_this8.media().id);
  37844. });
  37845. });
  37846. }
  37847. /**
  37848. * Refreshes the media playlist by re-parsing the master xml and updating playlist
  37849. * references. If this is an alternate loader, the updated parsed manifest is retrieved
  37850. * from the master loader.
  37851. */
  37852. ;
  37853. _proto.refreshMedia_ = function refreshMedia_(mediaID) {
  37854. var _this9 = this;
  37855. if (!mediaID) {
  37856. throw new Error('refreshMedia_ must take a media id');
  37857. } // for master we have to reparse the master xml
  37858. // to re-create segments based on current timing values
  37859. // which may change media. We only skip updating master
  37860. // if this is the first time this.media_ is being set.
  37861. // as master was just parsed in that case.
  37862. if (this.media_ && this.isMaster_) {
  37863. this.handleMaster_();
  37864. }
  37865. var playlists = this.masterPlaylistLoader_.master.playlists;
  37866. var mediaChanged = !this.media_ || this.media_ !== playlists[mediaID];
  37867. if (mediaChanged) {
  37868. this.media_ = playlists[mediaID];
  37869. } else {
  37870. this.trigger('playlistunchanged');
  37871. }
  37872. if (!this.mediaUpdateTimeout) {
  37873. var createMediaUpdateTimeout = function createMediaUpdateTimeout() {
  37874. if (_this9.media().endList) {
  37875. return;
  37876. }
  37877. _this9.mediaUpdateTimeout = window.setTimeout(function () {
  37878. _this9.trigger('mediaupdatetimeout');
  37879. createMediaUpdateTimeout();
  37880. }, refreshDelay(_this9.media(), Boolean(mediaChanged)));
  37881. };
  37882. createMediaUpdateTimeout();
  37883. }
  37884. this.trigger('loadedplaylist');
  37885. };
  37886. return DashPlaylistLoader;
  37887. }(EventTarget);
  37888. var Config = {
  37889. GOAL_BUFFER_LENGTH: 30,
  37890. MAX_GOAL_BUFFER_LENGTH: 60,
  37891. BACK_BUFFER_LENGTH: 30,
  37892. GOAL_BUFFER_LENGTH_RATE: 1,
  37893. // 0.5 MB/s
  37894. INITIAL_BANDWIDTH: 4194304,
  37895. // A fudge factor to apply to advertised playlist bitrates to account for
  37896. // temporary flucations in client bandwidth
  37897. BANDWIDTH_VARIANCE: 1.2,
  37898. // How much of the buffer must be filled before we consider upswitching
  37899. BUFFER_LOW_WATER_LINE: 0,
  37900. MAX_BUFFER_LOW_WATER_LINE: 30,
  37901. // TODO: Remove this when experimentalBufferBasedABR is removed
  37902. EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE: 16,
  37903. BUFFER_LOW_WATER_LINE_RATE: 1,
  37904. // If the buffer is greater than the high water line, we won't switch down
  37905. BUFFER_HIGH_WATER_LINE: 30
  37906. };
  37907. var stringToArrayBuffer = function stringToArrayBuffer(string) {
  37908. var view = new Uint8Array(new ArrayBuffer(string.length));
  37909. for (var i = 0; i < string.length; i++) {
  37910. view[i] = string.charCodeAt(i);
  37911. }
  37912. return view.buffer;
  37913. };
  37914. /* global Blob, BlobBuilder, Worker */
  37915. // unify worker interface
  37916. var browserWorkerPolyFill = function browserWorkerPolyFill(workerObj) {
  37917. // node only supports on/off
  37918. workerObj.on = workerObj.addEventListener;
  37919. workerObj.off = workerObj.removeEventListener;
  37920. return workerObj;
  37921. };
  37922. var createObjectURL = function createObjectURL(str) {
  37923. try {
  37924. return URL.createObjectURL(new Blob([str], {
  37925. type: 'application/javascript'
  37926. }));
  37927. } catch (e) {
  37928. var blob = new BlobBuilder();
  37929. blob.append(str);
  37930. return URL.createObjectURL(blob.getBlob());
  37931. }
  37932. };
  37933. var factory = function factory(code) {
  37934. return function () {
  37935. var objectUrl = createObjectURL(code);
  37936. var worker = browserWorkerPolyFill(new Worker(objectUrl));
  37937. worker.objURL = objectUrl;
  37938. var terminate = worker.terminate;
  37939. worker.on = worker.addEventListener;
  37940. worker.off = worker.removeEventListener;
  37941. worker.terminate = function () {
  37942. URL.revokeObjectURL(objectUrl);
  37943. return terminate.call(this);
  37944. };
  37945. return worker;
  37946. };
  37947. };
  37948. var transform = function transform(code) {
  37949. return "var browserWorkerPolyFill = " + browserWorkerPolyFill.toString() + ";\n" + 'browserWorkerPolyFill(self);\n' + code;
  37950. };
  37951. var getWorkerString = function getWorkerString(fn) {
  37952. return fn.toString().replace(/^function.+?{/, '').slice(0, -1);
  37953. };
  37954. /* rollup-plugin-worker-factory start for worker!/Users/ddashkevich/projects/http-streaming/src/transmuxer-worker.js */
  37955. var workerCode$1 = transform(getWorkerString(function () {
  37956. /**
  37957. * mux.js
  37958. *
  37959. * Copyright (c) Brightcove
  37960. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  37961. *
  37962. * A lightweight readable stream implemention that handles event dispatching.
  37963. * Objects that inherit from streams should call init in their constructors.
  37964. */
  37965. var Stream = function Stream() {
  37966. this.init = function () {
  37967. var listeners = {};
  37968. /**
  37969. * Add a listener for a specified event type.
  37970. * @param type {string} the event name
  37971. * @param listener {function} the callback to be invoked when an event of
  37972. * the specified type occurs
  37973. */
  37974. this.on = function (type, listener) {
  37975. if (!listeners[type]) {
  37976. listeners[type] = [];
  37977. }
  37978. listeners[type] = listeners[type].concat(listener);
  37979. };
  37980. /**
  37981. * Remove a listener for a specified event type.
  37982. * @param type {string} the event name
  37983. * @param listener {function} a function previously registered for this
  37984. * type of event through `on`
  37985. */
  37986. this.off = function (type, listener) {
  37987. var index;
  37988. if (!listeners[type]) {
  37989. return false;
  37990. }
  37991. index = listeners[type].indexOf(listener);
  37992. listeners[type] = listeners[type].slice();
  37993. listeners[type].splice(index, 1);
  37994. return index > -1;
  37995. };
  37996. /**
  37997. * Trigger an event of the specified type on this stream. Any additional
  37998. * arguments to this function are passed as parameters to event listeners.
  37999. * @param type {string} the event name
  38000. */
  38001. this.trigger = function (type) {
  38002. var callbacks, i, length, args;
  38003. callbacks = listeners[type];
  38004. if (!callbacks) {
  38005. return;
  38006. } // Slicing the arguments on every invocation of this method
  38007. // can add a significant amount of overhead. Avoid the
  38008. // intermediate object creation for the common case of a
  38009. // single callback argument
  38010. if (arguments.length === 2) {
  38011. length = callbacks.length;
  38012. for (i = 0; i < length; ++i) {
  38013. callbacks[i].call(this, arguments[1]);
  38014. }
  38015. } else {
  38016. args = [];
  38017. i = arguments.length;
  38018. for (i = 1; i < arguments.length; ++i) {
  38019. args.push(arguments[i]);
  38020. }
  38021. length = callbacks.length;
  38022. for (i = 0; i < length; ++i) {
  38023. callbacks[i].apply(this, args);
  38024. }
  38025. }
  38026. };
  38027. /**
  38028. * Destroys the stream and cleans up.
  38029. */
  38030. this.dispose = function () {
  38031. listeners = {};
  38032. };
  38033. };
  38034. };
  38035. /**
  38036. * Forwards all `data` events on this stream to the destination stream. The
  38037. * destination stream should provide a method `push` to receive the data
  38038. * events as they arrive.
  38039. * @param destination {stream} the stream that will receive all `data` events
  38040. * @param autoFlush {boolean} if false, we will not call `flush` on the destination
  38041. * when the current stream emits a 'done' event
  38042. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  38043. */
  38044. Stream.prototype.pipe = function (destination) {
  38045. this.on('data', function (data) {
  38046. destination.push(data);
  38047. });
  38048. this.on('done', function (flushSource) {
  38049. destination.flush(flushSource);
  38050. });
  38051. this.on('partialdone', function (flushSource) {
  38052. destination.partialFlush(flushSource);
  38053. });
  38054. this.on('endedtimeline', function (flushSource) {
  38055. destination.endTimeline(flushSource);
  38056. });
  38057. this.on('reset', function (flushSource) {
  38058. destination.reset(flushSource);
  38059. });
  38060. return destination;
  38061. }; // Default stream functions that are expected to be overridden to perform
  38062. // actual work. These are provided by the prototype as a sort of no-op
  38063. // implementation so that we don't have to check for their existence in the
  38064. // `pipe` function above.
  38065. Stream.prototype.push = function (data) {
  38066. this.trigger('data', data);
  38067. };
  38068. Stream.prototype.flush = function (flushSource) {
  38069. this.trigger('done', flushSource);
  38070. };
  38071. Stream.prototype.partialFlush = function (flushSource) {
  38072. this.trigger('partialdone', flushSource);
  38073. };
  38074. Stream.prototype.endTimeline = function (flushSource) {
  38075. this.trigger('endedtimeline', flushSource);
  38076. };
  38077. Stream.prototype.reset = function (flushSource) {
  38078. this.trigger('reset', flushSource);
  38079. };
  38080. var stream = Stream;
  38081. var MAX_UINT32$1 = Math.pow(2, 32);
  38082. var getUint64$2 = function getUint64(uint8) {
  38083. var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
  38084. var value;
  38085. if (dv.getBigUint64) {
  38086. value = dv.getBigUint64(0);
  38087. if (value < Number.MAX_SAFE_INTEGER) {
  38088. return Number(value);
  38089. }
  38090. return value;
  38091. }
  38092. return dv.getUint32(0) * MAX_UINT32$1 + dv.getUint32(4);
  38093. };
  38094. var numbers = {
  38095. getUint64: getUint64$2,
  38096. MAX_UINT32: MAX_UINT32$1
  38097. };
  38098. var MAX_UINT32 = numbers.MAX_UINT32;
  38099. var box, dinf, esds, ftyp, mdat, mfhd, minf, moof, moov, mvex, mvhd, trak, tkhd, mdia, mdhd, hdlr, sdtp, stbl, stsd, traf, trex, trun$1, types, MAJOR_BRAND, MINOR_VERSION, AVC1_BRAND, VIDEO_HDLR, AUDIO_HDLR, HDLR_TYPES, VMHD, SMHD, DREF, STCO, STSC, STSZ, STTS; // pre-calculate constants
  38100. (function () {
  38101. var i;
  38102. types = {
  38103. avc1: [],
  38104. // codingname
  38105. avcC: [],
  38106. btrt: [],
  38107. dinf: [],
  38108. dref: [],
  38109. esds: [],
  38110. ftyp: [],
  38111. hdlr: [],
  38112. mdat: [],
  38113. mdhd: [],
  38114. mdia: [],
  38115. mfhd: [],
  38116. minf: [],
  38117. moof: [],
  38118. moov: [],
  38119. mp4a: [],
  38120. // codingname
  38121. mvex: [],
  38122. mvhd: [],
  38123. pasp: [],
  38124. sdtp: [],
  38125. smhd: [],
  38126. stbl: [],
  38127. stco: [],
  38128. stsc: [],
  38129. stsd: [],
  38130. stsz: [],
  38131. stts: [],
  38132. styp: [],
  38133. tfdt: [],
  38134. tfhd: [],
  38135. traf: [],
  38136. trak: [],
  38137. trun: [],
  38138. trex: [],
  38139. tkhd: [],
  38140. vmhd: []
  38141. }; // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
  38142. // don't throw an error
  38143. if (typeof Uint8Array === 'undefined') {
  38144. return;
  38145. }
  38146. for (i in types) {
  38147. if (types.hasOwnProperty(i)) {
  38148. types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  38149. }
  38150. }
  38151. MAJOR_BRAND = new Uint8Array(['i'.charCodeAt(0), 's'.charCodeAt(0), 'o'.charCodeAt(0), 'm'.charCodeAt(0)]);
  38152. AVC1_BRAND = new Uint8Array(['a'.charCodeAt(0), 'v'.charCodeAt(0), 'c'.charCodeAt(0), '1'.charCodeAt(0)]);
  38153. MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
  38154. VIDEO_HDLR = new Uint8Array([0x00, // version 0
  38155. 0x00, 0x00, 0x00, // flags
  38156. 0x00, 0x00, 0x00, 0x00, // pre_defined
  38157. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  38158. 0x00, 0x00, 0x00, 0x00, // reserved
  38159. 0x00, 0x00, 0x00, 0x00, // reserved
  38160. 0x00, 0x00, 0x00, 0x00, // reserved
  38161. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  38162. ]);
  38163. AUDIO_HDLR = new Uint8Array([0x00, // version 0
  38164. 0x00, 0x00, 0x00, // flags
  38165. 0x00, 0x00, 0x00, 0x00, // pre_defined
  38166. 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
  38167. 0x00, 0x00, 0x00, 0x00, // reserved
  38168. 0x00, 0x00, 0x00, 0x00, // reserved
  38169. 0x00, 0x00, 0x00, 0x00, // reserved
  38170. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  38171. ]);
  38172. HDLR_TYPES = {
  38173. video: VIDEO_HDLR,
  38174. audio: AUDIO_HDLR
  38175. };
  38176. DREF = new Uint8Array([0x00, // version 0
  38177. 0x00, 0x00, 0x00, // flags
  38178. 0x00, 0x00, 0x00, 0x01, // entry_count
  38179. 0x00, 0x00, 0x00, 0x0c, // entry_size
  38180. 0x75, 0x72, 0x6c, 0x20, // 'url' type
  38181. 0x00, // version 0
  38182. 0x00, 0x00, 0x01 // entry_flags
  38183. ]);
  38184. SMHD = new Uint8Array([0x00, // version
  38185. 0x00, 0x00, 0x00, // flags
  38186. 0x00, 0x00, // balance, 0 means centered
  38187. 0x00, 0x00 // reserved
  38188. ]);
  38189. STCO = new Uint8Array([0x00, // version
  38190. 0x00, 0x00, 0x00, // flags
  38191. 0x00, 0x00, 0x00, 0x00 // entry_count
  38192. ]);
  38193. STSC = STCO;
  38194. STSZ = new Uint8Array([0x00, // version
  38195. 0x00, 0x00, 0x00, // flags
  38196. 0x00, 0x00, 0x00, 0x00, // sample_size
  38197. 0x00, 0x00, 0x00, 0x00 // sample_count
  38198. ]);
  38199. STTS = STCO;
  38200. VMHD = new Uint8Array([0x00, // version
  38201. 0x00, 0x00, 0x01, // flags
  38202. 0x00, 0x00, // graphicsmode
  38203. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  38204. ]);
  38205. })();
  38206. box = function box(type) {
  38207. var payload = [],
  38208. size = 0,
  38209. i,
  38210. result,
  38211. view;
  38212. for (i = 1; i < arguments.length; i++) {
  38213. payload.push(arguments[i]);
  38214. }
  38215. i = payload.length; // calculate the total size we need to allocate
  38216. while (i--) {
  38217. size += payload[i].byteLength;
  38218. }
  38219. result = new Uint8Array(size + 8);
  38220. view = new DataView(result.buffer, result.byteOffset, result.byteLength);
  38221. view.setUint32(0, result.byteLength);
  38222. result.set(type, 4); // copy the payload into the result
  38223. for (i = 0, size = 8; i < payload.length; i++) {
  38224. result.set(payload[i], size);
  38225. size += payload[i].byteLength;
  38226. }
  38227. return result;
  38228. };
  38229. dinf = function dinf() {
  38230. return box(types.dinf, box(types.dref, DREF));
  38231. };
  38232. esds = function esds(track) {
  38233. return box(types.esds, new Uint8Array([0x00, // version
  38234. 0x00, 0x00, 0x00, // flags
  38235. // ES_Descriptor
  38236. 0x03, // tag, ES_DescrTag
  38237. 0x19, // length
  38238. 0x00, 0x00, // ES_ID
  38239. 0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority
  38240. // DecoderConfigDescriptor
  38241. 0x04, // tag, DecoderConfigDescrTag
  38242. 0x11, // length
  38243. 0x40, // object type
  38244. 0x15, // streamType
  38245. 0x00, 0x06, 0x00, // bufferSizeDB
  38246. 0x00, 0x00, 0xda, 0xc0, // maxBitrate
  38247. 0x00, 0x00, 0xda, 0xc0, // avgBitrate
  38248. // DecoderSpecificInfo
  38249. 0x05, // tag, DecoderSpecificInfoTag
  38250. 0x02, // length
  38251. // ISO/IEC 14496-3, AudioSpecificConfig
  38252. // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
  38253. track.audioobjecttype << 3 | track.samplingfrequencyindex >>> 1, track.samplingfrequencyindex << 7 | track.channelcount << 3, 0x06, 0x01, 0x02 // GASpecificConfig
  38254. ]));
  38255. };
  38256. ftyp = function ftyp() {
  38257. return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
  38258. };
  38259. hdlr = function hdlr(type) {
  38260. return box(types.hdlr, HDLR_TYPES[type]);
  38261. };
  38262. mdat = function mdat(data) {
  38263. return box(types.mdat, data);
  38264. };
  38265. mdhd = function mdhd(track) {
  38266. var result = new Uint8Array([0x00, // version 0
  38267. 0x00, 0x00, 0x00, // flags
  38268. 0x00, 0x00, 0x00, 0x02, // creation_time
  38269. 0x00, 0x00, 0x00, 0x03, // modification_time
  38270. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  38271. track.duration >>> 24 & 0xFF, track.duration >>> 16 & 0xFF, track.duration >>> 8 & 0xFF, track.duration & 0xFF, // duration
  38272. 0x55, 0xc4, // 'und' language (undetermined)
  38273. 0x00, 0x00]); // Use the sample rate from the track metadata, when it is
  38274. // defined. The sample rate can be parsed out of an ADTS header, for
  38275. // instance.
  38276. if (track.samplerate) {
  38277. result[12] = track.samplerate >>> 24 & 0xFF;
  38278. result[13] = track.samplerate >>> 16 & 0xFF;
  38279. result[14] = track.samplerate >>> 8 & 0xFF;
  38280. result[15] = track.samplerate & 0xFF;
  38281. }
  38282. return box(types.mdhd, result);
  38283. };
  38284. mdia = function mdia(track) {
  38285. return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
  38286. };
  38287. mfhd = function mfhd(sequenceNumber) {
  38288. return box(types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
  38289. (sequenceNumber & 0xFF000000) >> 24, (sequenceNumber & 0xFF0000) >> 16, (sequenceNumber & 0xFF00) >> 8, sequenceNumber & 0xFF // sequence_number
  38290. ]));
  38291. };
  38292. minf = function minf(track) {
  38293. return box(types.minf, track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD), dinf(), stbl(track));
  38294. };
  38295. moof = function moof(sequenceNumber, tracks) {
  38296. var trackFragments = [],
  38297. i = tracks.length; // build traf boxes for each track fragment
  38298. while (i--) {
  38299. trackFragments[i] = traf(tracks[i]);
  38300. }
  38301. return box.apply(null, [types.moof, mfhd(sequenceNumber)].concat(trackFragments));
  38302. };
  38303. /**
  38304. * Returns a movie box.
  38305. * @param tracks {array} the tracks associated with this movie
  38306. * @see ISO/IEC 14496-12:2012(E), section 8.2.1
  38307. */
  38308. moov = function moov(tracks) {
  38309. var i = tracks.length,
  38310. boxes = [];
  38311. while (i--) {
  38312. boxes[i] = trak(tracks[i]);
  38313. }
  38314. return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
  38315. };
  38316. mvex = function mvex(tracks) {
  38317. var i = tracks.length,
  38318. boxes = [];
  38319. while (i--) {
  38320. boxes[i] = trex(tracks[i]);
  38321. }
  38322. return box.apply(null, [types.mvex].concat(boxes));
  38323. };
  38324. mvhd = function mvhd(duration) {
  38325. var bytes = new Uint8Array([0x00, // version 0
  38326. 0x00, 0x00, 0x00, // flags
  38327. 0x00, 0x00, 0x00, 0x01, // creation_time
  38328. 0x00, 0x00, 0x00, 0x02, // modification_time
  38329. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  38330. (duration & 0xFF000000) >> 24, (duration & 0xFF0000) >> 16, (duration & 0xFF00) >> 8, duration & 0xFF, // duration
  38331. 0x00, 0x01, 0x00, 0x00, // 1.0 rate
  38332. 0x01, 0x00, // 1.0 volume
  38333. 0x00, 0x00, // reserved
  38334. 0x00, 0x00, 0x00, 0x00, // reserved
  38335. 0x00, 0x00, 0x00, 0x00, // reserved
  38336. 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
  38337. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  38338. 0xff, 0xff, 0xff, 0xff // next_track_ID
  38339. ]);
  38340. return box(types.mvhd, bytes);
  38341. };
  38342. sdtp = function sdtp(track) {
  38343. var samples = track.samples || [],
  38344. bytes = new Uint8Array(4 + samples.length),
  38345. flags,
  38346. i; // leave the full box header (4 bytes) all zero
  38347. // write the sample table
  38348. for (i = 0; i < samples.length; i++) {
  38349. flags = samples[i].flags;
  38350. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  38351. }
  38352. return box(types.sdtp, bytes);
  38353. };
  38354. stbl = function stbl(track) {
  38355. return box(types.stbl, stsd(track), box(types.stts, STTS), box(types.stsc, STSC), box(types.stsz, STSZ), box(types.stco, STCO));
  38356. };
  38357. (function () {
  38358. var videoSample, audioSample;
  38359. stsd = function stsd(track) {
  38360. return box(types.stsd, new Uint8Array([0x00, // version 0
  38361. 0x00, 0x00, 0x00, // flags
  38362. 0x00, 0x00, 0x00, 0x01]), track.type === 'video' ? videoSample(track) : audioSample(track));
  38363. };
  38364. videoSample = function videoSample(track) {
  38365. var sps = track.sps || [],
  38366. pps = track.pps || [],
  38367. sequenceParameterSets = [],
  38368. pictureParameterSets = [],
  38369. i,
  38370. avc1Box; // assemble the SPSs
  38371. for (i = 0; i < sps.length; i++) {
  38372. sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
  38373. sequenceParameterSets.push(sps[i].byteLength & 0xFF); // sequenceParameterSetLength
  38374. sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
  38375. } // assemble the PPSs
  38376. for (i = 0; i < pps.length; i++) {
  38377. pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
  38378. pictureParameterSets.push(pps[i].byteLength & 0xFF);
  38379. pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
  38380. }
  38381. avc1Box = [types.avc1, new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  38382. 0x00, 0x01, // data_reference_index
  38383. 0x00, 0x00, // pre_defined
  38384. 0x00, 0x00, // reserved
  38385. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  38386. (track.width & 0xff00) >> 8, track.width & 0xff, // width
  38387. (track.height & 0xff00) >> 8, track.height & 0xff, // height
  38388. 0x00, 0x48, 0x00, 0x00, // horizresolution
  38389. 0x00, 0x48, 0x00, 0x00, // vertresolution
  38390. 0x00, 0x00, 0x00, 0x00, // reserved
  38391. 0x00, 0x01, // frame_count
  38392. 0x13, 0x76, 0x69, 0x64, 0x65, 0x6f, 0x6a, 0x73, 0x2d, 0x63, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x2d, 0x68, 0x6c, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // compressorname
  38393. 0x00, 0x18, // depth = 24
  38394. 0x11, 0x11 // pre_defined = -1
  38395. ]), box(types.avcC, new Uint8Array([0x01, // configurationVersion
  38396. track.profileIdc, // AVCProfileIndication
  38397. track.profileCompatibility, // profile_compatibility
  38398. track.levelIdc, // AVCLevelIndication
  38399. 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
  38400. ].concat([sps.length], // numOfSequenceParameterSets
  38401. sequenceParameterSets, // "SPS"
  38402. [pps.length], // numOfPictureParameterSets
  38403. pictureParameterSets // "PPS"
  38404. ))), box(types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
  38405. 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
  38406. 0x00, 0x2d, 0xc6, 0xc0 // avgBitrate
  38407. ]))];
  38408. if (track.sarRatio) {
  38409. var hSpacing = track.sarRatio[0],
  38410. vSpacing = track.sarRatio[1];
  38411. avc1Box.push(box(types.pasp, new Uint8Array([(hSpacing & 0xFF000000) >> 24, (hSpacing & 0xFF0000) >> 16, (hSpacing & 0xFF00) >> 8, hSpacing & 0xFF, (vSpacing & 0xFF000000) >> 24, (vSpacing & 0xFF0000) >> 16, (vSpacing & 0xFF00) >> 8, vSpacing & 0xFF])));
  38412. }
  38413. return box.apply(null, avc1Box);
  38414. };
  38415. audioSample = function audioSample(track) {
  38416. return box(types.mp4a, new Uint8Array([// SampleEntry, ISO/IEC 14496-12
  38417. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  38418. 0x00, 0x01, // data_reference_index
  38419. // AudioSampleEntry, ISO/IEC 14496-12
  38420. 0x00, 0x00, 0x00, 0x00, // reserved
  38421. 0x00, 0x00, 0x00, 0x00, // reserved
  38422. (track.channelcount & 0xff00) >> 8, track.channelcount & 0xff, // channelcount
  38423. (track.samplesize & 0xff00) >> 8, track.samplesize & 0xff, // samplesize
  38424. 0x00, 0x00, // pre_defined
  38425. 0x00, 0x00, // reserved
  38426. (track.samplerate & 0xff00) >> 8, track.samplerate & 0xff, 0x00, 0x00 // samplerate, 16.16
  38427. // MP4AudioSampleEntry, ISO/IEC 14496-14
  38428. ]), esds(track));
  38429. };
  38430. })();
  38431. tkhd = function tkhd(track) {
  38432. var result = new Uint8Array([0x00, // version 0
  38433. 0x00, 0x00, 0x07, // flags
  38434. 0x00, 0x00, 0x00, 0x00, // creation_time
  38435. 0x00, 0x00, 0x00, 0x00, // modification_time
  38436. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  38437. 0x00, 0x00, 0x00, 0x00, // reserved
  38438. (track.duration & 0xFF000000) >> 24, (track.duration & 0xFF0000) >> 16, (track.duration & 0xFF00) >> 8, track.duration & 0xFF, // duration
  38439. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  38440. 0x00, 0x00, // layer
  38441. 0x00, 0x00, // alternate_group
  38442. 0x01, 0x00, // non-audio track volume
  38443. 0x00, 0x00, // reserved
  38444. 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
  38445. (track.width & 0xFF00) >> 8, track.width & 0xFF, 0x00, 0x00, // width
  38446. (track.height & 0xFF00) >> 8, track.height & 0xFF, 0x00, 0x00 // height
  38447. ]);
  38448. return box(types.tkhd, result);
  38449. };
  38450. /**
  38451. * Generate a track fragment (traf) box. A traf box collects metadata
  38452. * about tracks in a movie fragment (moof) box.
  38453. */
  38454. traf = function traf(track) {
  38455. var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable, dataOffset, upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
  38456. trackFragmentHeader = box(types.tfhd, new Uint8Array([0x00, // version 0
  38457. 0x00, 0x00, 0x3a, // flags
  38458. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  38459. 0x00, 0x00, 0x00, 0x01, // sample_description_index
  38460. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  38461. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  38462. 0x00, 0x00, 0x00, 0x00 // default_sample_flags
  38463. ]));
  38464. upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / MAX_UINT32);
  38465. lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % MAX_UINT32);
  38466. trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([0x01, // version 1
  38467. 0x00, 0x00, 0x00, // flags
  38468. // baseMediaDecodeTime
  38469. upperWordBaseMediaDecodeTime >>> 24 & 0xFF, upperWordBaseMediaDecodeTime >>> 16 & 0xFF, upperWordBaseMediaDecodeTime >>> 8 & 0xFF, upperWordBaseMediaDecodeTime & 0xFF, lowerWordBaseMediaDecodeTime >>> 24 & 0xFF, lowerWordBaseMediaDecodeTime >>> 16 & 0xFF, lowerWordBaseMediaDecodeTime >>> 8 & 0xFF, lowerWordBaseMediaDecodeTime & 0xFF])); // the data offset specifies the number of bytes from the start of
  38470. // the containing moof to the first payload byte of the associated
  38471. // mdat
  38472. dataOffset = 32 + // tfhd
  38473. 20 + // tfdt
  38474. 8 + // traf header
  38475. 16 + // mfhd
  38476. 8 + // moof header
  38477. 8; // mdat header
  38478. // audio tracks require less metadata
  38479. if (track.type === 'audio') {
  38480. trackFragmentRun = trun$1(track, dataOffset);
  38481. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun);
  38482. } // video tracks should contain an independent and disposable samples
  38483. // box (sdtp)
  38484. // generate one and adjust offsets to match
  38485. sampleDependencyTable = sdtp(track);
  38486. trackFragmentRun = trun$1(track, sampleDependencyTable.length + dataOffset);
  38487. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable);
  38488. };
  38489. /**
  38490. * Generate a track box.
  38491. * @param track {object} a track definition
  38492. * @return {Uint8Array} the track box
  38493. */
  38494. trak = function trak(track) {
  38495. track.duration = track.duration || 0xffffffff;
  38496. return box(types.trak, tkhd(track), mdia(track));
  38497. };
  38498. trex = function trex(track) {
  38499. var result = new Uint8Array([0x00, // version 0
  38500. 0x00, 0x00, 0x00, // flags
  38501. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  38502. 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  38503. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  38504. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  38505. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  38506. ]); // the last two bytes of default_sample_flags is the sample
  38507. // degradation priority, a hint about the importance of this sample
  38508. // relative to others. Lower the degradation priority for all sample
  38509. // types other than video.
  38510. if (track.type !== 'video') {
  38511. result[result.length - 1] = 0x00;
  38512. }
  38513. return box(types.trex, result);
  38514. };
  38515. (function () {
  38516. var audioTrun, videoTrun, trunHeader; // This method assumes all samples are uniform. That is, if a
  38517. // duration is present for the first sample, it will be present for
  38518. // all subsequent samples.
  38519. // see ISO/IEC 14496-12:2012, Section 8.8.8.1
  38520. trunHeader = function trunHeader(samples, offset) {
  38521. var durationPresent = 0,
  38522. sizePresent = 0,
  38523. flagsPresent = 0,
  38524. compositionTimeOffset = 0; // trun flag constants
  38525. if (samples.length) {
  38526. if (samples[0].duration !== undefined) {
  38527. durationPresent = 0x1;
  38528. }
  38529. if (samples[0].size !== undefined) {
  38530. sizePresent = 0x2;
  38531. }
  38532. if (samples[0].flags !== undefined) {
  38533. flagsPresent = 0x4;
  38534. }
  38535. if (samples[0].compositionTimeOffset !== undefined) {
  38536. compositionTimeOffset = 0x8;
  38537. }
  38538. }
  38539. return [0x00, // version 0
  38540. 0x00, durationPresent | sizePresent | flagsPresent | compositionTimeOffset, 0x01, // flags
  38541. (samples.length & 0xFF000000) >>> 24, (samples.length & 0xFF0000) >>> 16, (samples.length & 0xFF00) >>> 8, samples.length & 0xFF, // sample_count
  38542. (offset & 0xFF000000) >>> 24, (offset & 0xFF0000) >>> 16, (offset & 0xFF00) >>> 8, offset & 0xFF // data_offset
  38543. ];
  38544. };
  38545. videoTrun = function videoTrun(track, offset) {
  38546. var bytesOffest, bytes, header, samples, sample, i;
  38547. samples = track.samples || [];
  38548. offset += 8 + 12 + 16 * samples.length;
  38549. header = trunHeader(samples, offset);
  38550. bytes = new Uint8Array(header.length + samples.length * 16);
  38551. bytes.set(header);
  38552. bytesOffest = header.length;
  38553. for (i = 0; i < samples.length; i++) {
  38554. sample = samples[i];
  38555. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  38556. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  38557. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  38558. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  38559. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  38560. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  38561. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  38562. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  38563. bytes[bytesOffest++] = sample.flags.isLeading << 2 | sample.flags.dependsOn;
  38564. bytes[bytesOffest++] = sample.flags.isDependedOn << 6 | sample.flags.hasRedundancy << 4 | sample.flags.paddingValue << 1 | sample.flags.isNonSyncSample;
  38565. bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;
  38566. bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags
  38567. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;
  38568. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;
  38569. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;
  38570. bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset
  38571. }
  38572. return box(types.trun, bytes);
  38573. };
  38574. audioTrun = function audioTrun(track, offset) {
  38575. var bytes, bytesOffest, header, samples, sample, i;
  38576. samples = track.samples || [];
  38577. offset += 8 + 12 + 8 * samples.length;
  38578. header = trunHeader(samples, offset);
  38579. bytes = new Uint8Array(header.length + samples.length * 8);
  38580. bytes.set(header);
  38581. bytesOffest = header.length;
  38582. for (i = 0; i < samples.length; i++) {
  38583. sample = samples[i];
  38584. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  38585. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  38586. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  38587. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  38588. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  38589. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  38590. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  38591. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  38592. }
  38593. return box(types.trun, bytes);
  38594. };
  38595. trun$1 = function trun(track, offset) {
  38596. if (track.type === 'audio') {
  38597. return audioTrun(track, offset);
  38598. }
  38599. return videoTrun(track, offset);
  38600. };
  38601. })();
  38602. var mp4Generator = {
  38603. ftyp: ftyp,
  38604. mdat: mdat,
  38605. moof: moof,
  38606. moov: moov,
  38607. initSegment: function initSegment(tracks) {
  38608. var fileType = ftyp(),
  38609. movie = moov(tracks),
  38610. result;
  38611. result = new Uint8Array(fileType.byteLength + movie.byteLength);
  38612. result.set(fileType);
  38613. result.set(movie, fileType.byteLength);
  38614. return result;
  38615. }
  38616. };
  38617. /**
  38618. * mux.js
  38619. *
  38620. * Copyright (c) Brightcove
  38621. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  38622. */
  38623. // Convert an array of nal units into an array of frames with each frame being
  38624. // composed of the nal units that make up that frame
  38625. // Also keep track of cummulative data about the frame from the nal units such
  38626. // as the frame duration, starting pts, etc.
  38627. var groupNalsIntoFrames = function groupNalsIntoFrames(nalUnits) {
  38628. var i,
  38629. currentNal,
  38630. currentFrame = [],
  38631. frames = []; // TODO added for LHLS, make sure this is OK
  38632. frames.byteLength = 0;
  38633. frames.nalCount = 0;
  38634. frames.duration = 0;
  38635. currentFrame.byteLength = 0;
  38636. for (i = 0; i < nalUnits.length; i++) {
  38637. currentNal = nalUnits[i]; // Split on 'aud'-type nal units
  38638. if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
  38639. // Since the very first nal unit is expected to be an AUD
  38640. // only push to the frames array when currentFrame is not empty
  38641. if (currentFrame.length) {
  38642. currentFrame.duration = currentNal.dts - currentFrame.dts; // TODO added for LHLS, make sure this is OK
  38643. frames.byteLength += currentFrame.byteLength;
  38644. frames.nalCount += currentFrame.length;
  38645. frames.duration += currentFrame.duration;
  38646. frames.push(currentFrame);
  38647. }
  38648. currentFrame = [currentNal];
  38649. currentFrame.byteLength = currentNal.data.byteLength;
  38650. currentFrame.pts = currentNal.pts;
  38651. currentFrame.dts = currentNal.dts;
  38652. } else {
  38653. // Specifically flag key frames for ease of use later
  38654. if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
  38655. currentFrame.keyFrame = true;
  38656. }
  38657. currentFrame.duration = currentNal.dts - currentFrame.dts;
  38658. currentFrame.byteLength += currentNal.data.byteLength;
  38659. currentFrame.push(currentNal);
  38660. }
  38661. } // For the last frame, use the duration of the previous frame if we
  38662. // have nothing better to go on
  38663. if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) {
  38664. currentFrame.duration = frames[frames.length - 1].duration;
  38665. } // Push the final frame
  38666. // TODO added for LHLS, make sure this is OK
  38667. frames.byteLength += currentFrame.byteLength;
  38668. frames.nalCount += currentFrame.length;
  38669. frames.duration += currentFrame.duration;
  38670. frames.push(currentFrame);
  38671. return frames;
  38672. }; // Convert an array of frames into an array of Gop with each Gop being composed
  38673. // of the frames that make up that Gop
  38674. // Also keep track of cummulative data about the Gop from the frames such as the
  38675. // Gop duration, starting pts, etc.
  38676. var groupFramesIntoGops = function groupFramesIntoGops(frames) {
  38677. var i,
  38678. currentFrame,
  38679. currentGop = [],
  38680. gops = []; // We must pre-set some of the values on the Gop since we
  38681. // keep running totals of these values
  38682. currentGop.byteLength = 0;
  38683. currentGop.nalCount = 0;
  38684. currentGop.duration = 0;
  38685. currentGop.pts = frames[0].pts;
  38686. currentGop.dts = frames[0].dts; // store some metadata about all the Gops
  38687. gops.byteLength = 0;
  38688. gops.nalCount = 0;
  38689. gops.duration = 0;
  38690. gops.pts = frames[0].pts;
  38691. gops.dts = frames[0].dts;
  38692. for (i = 0; i < frames.length; i++) {
  38693. currentFrame = frames[i];
  38694. if (currentFrame.keyFrame) {
  38695. // Since the very first frame is expected to be an keyframe
  38696. // only push to the gops array when currentGop is not empty
  38697. if (currentGop.length) {
  38698. gops.push(currentGop);
  38699. gops.byteLength += currentGop.byteLength;
  38700. gops.nalCount += currentGop.nalCount;
  38701. gops.duration += currentGop.duration;
  38702. }
  38703. currentGop = [currentFrame];
  38704. currentGop.nalCount = currentFrame.length;
  38705. currentGop.byteLength = currentFrame.byteLength;
  38706. currentGop.pts = currentFrame.pts;
  38707. currentGop.dts = currentFrame.dts;
  38708. currentGop.duration = currentFrame.duration;
  38709. } else {
  38710. currentGop.duration += currentFrame.duration;
  38711. currentGop.nalCount += currentFrame.length;
  38712. currentGop.byteLength += currentFrame.byteLength;
  38713. currentGop.push(currentFrame);
  38714. }
  38715. }
  38716. if (gops.length && currentGop.duration <= 0) {
  38717. currentGop.duration = gops[gops.length - 1].duration;
  38718. }
  38719. gops.byteLength += currentGop.byteLength;
  38720. gops.nalCount += currentGop.nalCount;
  38721. gops.duration += currentGop.duration; // push the final Gop
  38722. gops.push(currentGop);
  38723. return gops;
  38724. };
  38725. /*
  38726. * Search for the first keyframe in the GOPs and throw away all frames
  38727. * until that keyframe. Then extend the duration of the pulled keyframe
  38728. * and pull the PTS and DTS of the keyframe so that it covers the time
  38729. * range of the frames that were disposed.
  38730. *
  38731. * @param {Array} gops video GOPs
  38732. * @returns {Array} modified video GOPs
  38733. */
  38734. var extendFirstKeyFrame = function extendFirstKeyFrame(gops) {
  38735. var currentGop;
  38736. if (!gops[0][0].keyFrame && gops.length > 1) {
  38737. // Remove the first GOP
  38738. currentGop = gops.shift();
  38739. gops.byteLength -= currentGop.byteLength;
  38740. gops.nalCount -= currentGop.nalCount; // Extend the first frame of what is now the
  38741. // first gop to cover the time period of the
  38742. // frames we just removed
  38743. gops[0][0].dts = currentGop.dts;
  38744. gops[0][0].pts = currentGop.pts;
  38745. gops[0][0].duration += currentGop.duration;
  38746. }
  38747. return gops;
  38748. };
  38749. /**
  38750. * Default sample object
  38751. * see ISO/IEC 14496-12:2012, section 8.6.4.3
  38752. */
  38753. var createDefaultSample = function createDefaultSample() {
  38754. return {
  38755. size: 0,
  38756. flags: {
  38757. isLeading: 0,
  38758. dependsOn: 1,
  38759. isDependedOn: 0,
  38760. hasRedundancy: 0,
  38761. degradationPriority: 0,
  38762. isNonSyncSample: 1
  38763. }
  38764. };
  38765. };
  38766. /*
  38767. * Collates information from a video frame into an object for eventual
  38768. * entry into an MP4 sample table.
  38769. *
  38770. * @param {Object} frame the video frame
  38771. * @param {Number} dataOffset the byte offset to position the sample
  38772. * @return {Object} object containing sample table info for a frame
  38773. */
  38774. var sampleForFrame = function sampleForFrame(frame, dataOffset) {
  38775. var sample = createDefaultSample();
  38776. sample.dataOffset = dataOffset;
  38777. sample.compositionTimeOffset = frame.pts - frame.dts;
  38778. sample.duration = frame.duration;
  38779. sample.size = 4 * frame.length; // Space for nal unit size
  38780. sample.size += frame.byteLength;
  38781. if (frame.keyFrame) {
  38782. sample.flags.dependsOn = 2;
  38783. sample.flags.isNonSyncSample = 0;
  38784. }
  38785. return sample;
  38786. }; // generate the track's sample table from an array of gops
  38787. var generateSampleTable$1 = function generateSampleTable(gops, baseDataOffset) {
  38788. var h,
  38789. i,
  38790. sample,
  38791. currentGop,
  38792. currentFrame,
  38793. dataOffset = baseDataOffset || 0,
  38794. samples = [];
  38795. for (h = 0; h < gops.length; h++) {
  38796. currentGop = gops[h];
  38797. for (i = 0; i < currentGop.length; i++) {
  38798. currentFrame = currentGop[i];
  38799. sample = sampleForFrame(currentFrame, dataOffset);
  38800. dataOffset += sample.size;
  38801. samples.push(sample);
  38802. }
  38803. }
  38804. return samples;
  38805. }; // generate the track's raw mdat data from an array of gops
  38806. var concatenateNalData = function concatenateNalData(gops) {
  38807. var h,
  38808. i,
  38809. j,
  38810. currentGop,
  38811. currentFrame,
  38812. currentNal,
  38813. dataOffset = 0,
  38814. nalsByteLength = gops.byteLength,
  38815. numberOfNals = gops.nalCount,
  38816. totalByteLength = nalsByteLength + 4 * numberOfNals,
  38817. data = new Uint8Array(totalByteLength),
  38818. view = new DataView(data.buffer); // For each Gop..
  38819. for (h = 0; h < gops.length; h++) {
  38820. currentGop = gops[h]; // For each Frame..
  38821. for (i = 0; i < currentGop.length; i++) {
  38822. currentFrame = currentGop[i]; // For each NAL..
  38823. for (j = 0; j < currentFrame.length; j++) {
  38824. currentNal = currentFrame[j];
  38825. view.setUint32(dataOffset, currentNal.data.byteLength);
  38826. dataOffset += 4;
  38827. data.set(currentNal.data, dataOffset);
  38828. dataOffset += currentNal.data.byteLength;
  38829. }
  38830. }
  38831. }
  38832. return data;
  38833. }; // generate the track's sample table from a frame
  38834. var generateSampleTableForFrame = function generateSampleTableForFrame(frame, baseDataOffset) {
  38835. var sample,
  38836. dataOffset = baseDataOffset || 0,
  38837. samples = [];
  38838. sample = sampleForFrame(frame, dataOffset);
  38839. samples.push(sample);
  38840. return samples;
  38841. }; // generate the track's raw mdat data from a frame
  38842. var concatenateNalDataForFrame = function concatenateNalDataForFrame(frame) {
  38843. var i,
  38844. currentNal,
  38845. dataOffset = 0,
  38846. nalsByteLength = frame.byteLength,
  38847. numberOfNals = frame.length,
  38848. totalByteLength = nalsByteLength + 4 * numberOfNals,
  38849. data = new Uint8Array(totalByteLength),
  38850. view = new DataView(data.buffer); // For each NAL..
  38851. for (i = 0; i < frame.length; i++) {
  38852. currentNal = frame[i];
  38853. view.setUint32(dataOffset, currentNal.data.byteLength);
  38854. dataOffset += 4;
  38855. data.set(currentNal.data, dataOffset);
  38856. dataOffset += currentNal.data.byteLength;
  38857. }
  38858. return data;
  38859. };
  38860. var frameUtils = {
  38861. groupNalsIntoFrames: groupNalsIntoFrames,
  38862. groupFramesIntoGops: groupFramesIntoGops,
  38863. extendFirstKeyFrame: extendFirstKeyFrame,
  38864. generateSampleTable: generateSampleTable$1,
  38865. concatenateNalData: concatenateNalData,
  38866. generateSampleTableForFrame: generateSampleTableForFrame,
  38867. concatenateNalDataForFrame: concatenateNalDataForFrame
  38868. };
  38869. /**
  38870. * mux.js
  38871. *
  38872. * Copyright (c) Brightcove
  38873. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  38874. */
  38875. var highPrefix = [33, 16, 5, 32, 164, 27];
  38876. var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
  38877. var zeroFill = function zeroFill(count) {
  38878. var a = [];
  38879. while (count--) {
  38880. a.push(0);
  38881. }
  38882. return a;
  38883. };
  38884. var makeTable = function makeTable(metaTable) {
  38885. return Object.keys(metaTable).reduce(function (obj, key) {
  38886. obj[key] = new Uint8Array(metaTable[key].reduce(function (arr, part) {
  38887. return arr.concat(part);
  38888. }, []));
  38889. return obj;
  38890. }, {});
  38891. };
  38892. var silence;
  38893. var silence_1 = function silence_1() {
  38894. if (!silence) {
  38895. // Frames-of-silence to use for filling in missing AAC frames
  38896. var coneOfSilence = {
  38897. 96000: [highPrefix, [227, 64], zeroFill(154), [56]],
  38898. 88200: [highPrefix, [231], zeroFill(170), [56]],
  38899. 64000: [highPrefix, [248, 192], zeroFill(240), [56]],
  38900. 48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
  38901. 44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
  38902. 32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
  38903. 24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
  38904. 16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
  38905. 12000: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 253, 128], zeroFill(259), [56]],
  38906. 11025: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 255, 192], zeroFill(268), [55, 175, 128], zeroFill(108), [112]],
  38907. 8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
  38908. };
  38909. silence = makeTable(coneOfSilence);
  38910. }
  38911. return silence;
  38912. };
  38913. /**
  38914. * mux.js
  38915. *
  38916. * Copyright (c) Brightcove
  38917. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  38918. */
  38919. var ONE_SECOND_IN_TS$4 = 90000,
  38920. // 90kHz clock
  38921. secondsToVideoTs,
  38922. secondsToAudioTs,
  38923. videoTsToSeconds,
  38924. audioTsToSeconds,
  38925. audioTsToVideoTs,
  38926. videoTsToAudioTs,
  38927. metadataTsToSeconds;
  38928. secondsToVideoTs = function secondsToVideoTs(seconds) {
  38929. return seconds * ONE_SECOND_IN_TS$4;
  38930. };
  38931. secondsToAudioTs = function secondsToAudioTs(seconds, sampleRate) {
  38932. return seconds * sampleRate;
  38933. };
  38934. videoTsToSeconds = function videoTsToSeconds(timestamp) {
  38935. return timestamp / ONE_SECOND_IN_TS$4;
  38936. };
  38937. audioTsToSeconds = function audioTsToSeconds(timestamp, sampleRate) {
  38938. return timestamp / sampleRate;
  38939. };
  38940. audioTsToVideoTs = function audioTsToVideoTs(timestamp, sampleRate) {
  38941. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  38942. };
  38943. videoTsToAudioTs = function videoTsToAudioTs(timestamp, sampleRate) {
  38944. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  38945. };
  38946. /**
  38947. * Adjust ID3 tag or caption timing information by the timeline pts values
  38948. * (if keepOriginalTimestamps is false) and convert to seconds
  38949. */
  38950. metadataTsToSeconds = function metadataTsToSeconds(timestamp, timelineStartPts, keepOriginalTimestamps) {
  38951. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  38952. };
  38953. var clock = {
  38954. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS$4,
  38955. secondsToVideoTs: secondsToVideoTs,
  38956. secondsToAudioTs: secondsToAudioTs,
  38957. videoTsToSeconds: videoTsToSeconds,
  38958. audioTsToSeconds: audioTsToSeconds,
  38959. audioTsToVideoTs: audioTsToVideoTs,
  38960. videoTsToAudioTs: videoTsToAudioTs,
  38961. metadataTsToSeconds: metadataTsToSeconds
  38962. };
  38963. /**
  38964. * mux.js
  38965. *
  38966. * Copyright (c) Brightcove
  38967. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  38968. */
  38969. /**
  38970. * Sum the `byteLength` properties of the data in each AAC frame
  38971. */
  38972. var sumFrameByteLengths = function sumFrameByteLengths(array) {
  38973. var i,
  38974. currentObj,
  38975. sum = 0; // sum the byteLength's all each nal unit in the frame
  38976. for (i = 0; i < array.length; i++) {
  38977. currentObj = array[i];
  38978. sum += currentObj.data.byteLength;
  38979. }
  38980. return sum;
  38981. }; // Possibly pad (prefix) the audio track with silence if appending this track
  38982. // would lead to the introduction of a gap in the audio buffer
  38983. var prefixWithSilence = function prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime) {
  38984. var baseMediaDecodeTimeTs,
  38985. frameDuration = 0,
  38986. audioGapDuration = 0,
  38987. audioFillFrameCount = 0,
  38988. audioFillDuration = 0,
  38989. silentFrame,
  38990. i,
  38991. firstFrame;
  38992. if (!frames.length) {
  38993. return;
  38994. }
  38995. baseMediaDecodeTimeTs = clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate); // determine frame clock duration based on sample rate, round up to avoid overfills
  38996. frameDuration = Math.ceil(clock.ONE_SECOND_IN_TS / (track.samplerate / 1024));
  38997. if (audioAppendStartTs && videoBaseMediaDecodeTime) {
  38998. // insert the shortest possible amount (audio gap or audio to video gap)
  38999. audioGapDuration = baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime); // number of full frames in the audio gap
  39000. audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
  39001. audioFillDuration = audioFillFrameCount * frameDuration;
  39002. } // don't attempt to fill gaps smaller than a single frame or larger
  39003. // than a half second
  39004. if (audioFillFrameCount < 1 || audioFillDuration > clock.ONE_SECOND_IN_TS / 2) {
  39005. return;
  39006. }
  39007. silentFrame = silence_1()[track.samplerate];
  39008. if (!silentFrame) {
  39009. // we don't have a silent frame pregenerated for the sample rate, so use a frame
  39010. // from the content instead
  39011. silentFrame = frames[0].data;
  39012. }
  39013. for (i = 0; i < audioFillFrameCount; i++) {
  39014. firstFrame = frames[0];
  39015. frames.splice(0, 0, {
  39016. data: silentFrame,
  39017. dts: firstFrame.dts - frameDuration,
  39018. pts: firstFrame.pts - frameDuration
  39019. });
  39020. }
  39021. track.baseMediaDecodeTime -= Math.floor(clock.videoTsToAudioTs(audioFillDuration, track.samplerate));
  39022. return audioFillDuration;
  39023. }; // If the audio segment extends before the earliest allowed dts
  39024. // value, remove AAC frames until starts at or after the earliest
  39025. // allowed DTS so that we don't end up with a negative baseMedia-
  39026. // DecodeTime for the audio track
  39027. var trimAdtsFramesByEarliestDts = function trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts) {
  39028. if (track.minSegmentDts >= earliestAllowedDts) {
  39029. return adtsFrames;
  39030. } // We will need to recalculate the earliest segment Dts
  39031. track.minSegmentDts = Infinity;
  39032. return adtsFrames.filter(function (currentFrame) {
  39033. // If this is an allowed frame, keep it and record it's Dts
  39034. if (currentFrame.dts >= earliestAllowedDts) {
  39035. track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
  39036. track.minSegmentPts = track.minSegmentDts;
  39037. return true;
  39038. } // Otherwise, discard it
  39039. return false;
  39040. });
  39041. }; // generate the track's raw mdat data from an array of frames
  39042. var generateSampleTable = function generateSampleTable(frames) {
  39043. var i,
  39044. currentFrame,
  39045. samples = [];
  39046. for (i = 0; i < frames.length; i++) {
  39047. currentFrame = frames[i];
  39048. samples.push({
  39049. size: currentFrame.data.byteLength,
  39050. duration: 1024 // For AAC audio, all samples contain 1024 samples
  39051. });
  39052. }
  39053. return samples;
  39054. }; // generate the track's sample table from an array of frames
  39055. var concatenateFrameData = function concatenateFrameData(frames) {
  39056. var i,
  39057. currentFrame,
  39058. dataOffset = 0,
  39059. data = new Uint8Array(sumFrameByteLengths(frames));
  39060. for (i = 0; i < frames.length; i++) {
  39061. currentFrame = frames[i];
  39062. data.set(currentFrame.data, dataOffset);
  39063. dataOffset += currentFrame.data.byteLength;
  39064. }
  39065. return data;
  39066. };
  39067. var audioFrameUtils = {
  39068. prefixWithSilence: prefixWithSilence,
  39069. trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
  39070. generateSampleTable: generateSampleTable,
  39071. concatenateFrameData: concatenateFrameData
  39072. };
  39073. /**
  39074. * mux.js
  39075. *
  39076. * Copyright (c) Brightcove
  39077. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  39078. */
  39079. var ONE_SECOND_IN_TS$3 = clock.ONE_SECOND_IN_TS;
  39080. /**
  39081. * Store information about the start and end of the track and the
  39082. * duration for each frame/sample we process in order to calculate
  39083. * the baseMediaDecodeTime
  39084. */
  39085. var collectDtsInfo = function collectDtsInfo(track, data) {
  39086. if (typeof data.pts === 'number') {
  39087. if (track.timelineStartInfo.pts === undefined) {
  39088. track.timelineStartInfo.pts = data.pts;
  39089. }
  39090. if (track.minSegmentPts === undefined) {
  39091. track.minSegmentPts = data.pts;
  39092. } else {
  39093. track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
  39094. }
  39095. if (track.maxSegmentPts === undefined) {
  39096. track.maxSegmentPts = data.pts;
  39097. } else {
  39098. track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
  39099. }
  39100. }
  39101. if (typeof data.dts === 'number') {
  39102. if (track.timelineStartInfo.dts === undefined) {
  39103. track.timelineStartInfo.dts = data.dts;
  39104. }
  39105. if (track.minSegmentDts === undefined) {
  39106. track.minSegmentDts = data.dts;
  39107. } else {
  39108. track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
  39109. }
  39110. if (track.maxSegmentDts === undefined) {
  39111. track.maxSegmentDts = data.dts;
  39112. } else {
  39113. track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
  39114. }
  39115. }
  39116. };
  39117. /**
  39118. * Clear values used to calculate the baseMediaDecodeTime between
  39119. * tracks
  39120. */
  39121. var clearDtsInfo = function clearDtsInfo(track) {
  39122. delete track.minSegmentDts;
  39123. delete track.maxSegmentDts;
  39124. delete track.minSegmentPts;
  39125. delete track.maxSegmentPts;
  39126. };
  39127. /**
  39128. * Calculate the track's baseMediaDecodeTime based on the earliest
  39129. * DTS the transmuxer has ever seen and the minimum DTS for the
  39130. * current track
  39131. * @param track {object} track metadata configuration
  39132. * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
  39133. * in the source; false to adjust the first segment to start at 0.
  39134. */
  39135. var calculateTrackBaseMediaDecodeTime = function calculateTrackBaseMediaDecodeTime(track, keepOriginalTimestamps) {
  39136. var baseMediaDecodeTime,
  39137. scale,
  39138. minSegmentDts = track.minSegmentDts; // Optionally adjust the time so the first segment starts at zero.
  39139. if (!keepOriginalTimestamps) {
  39140. minSegmentDts -= track.timelineStartInfo.dts;
  39141. } // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
  39142. // we want the start of the first segment to be placed
  39143. baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime; // Add to that the distance this segment is from the very first
  39144. baseMediaDecodeTime += minSegmentDts; // baseMediaDecodeTime must not become negative
  39145. baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
  39146. if (track.type === 'audio') {
  39147. // Audio has a different clock equal to the sampling_rate so we need to
  39148. // scale the PTS values into the clock rate of the track
  39149. scale = track.samplerate / ONE_SECOND_IN_TS$3;
  39150. baseMediaDecodeTime *= scale;
  39151. baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
  39152. }
  39153. return baseMediaDecodeTime;
  39154. };
  39155. var trackDecodeInfo = {
  39156. clearDtsInfo: clearDtsInfo,
  39157. calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
  39158. collectDtsInfo: collectDtsInfo
  39159. };
  39160. /**
  39161. * mux.js
  39162. *
  39163. * Copyright (c) Brightcove
  39164. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  39165. *
  39166. * Reads in-band caption information from a video elementary
  39167. * stream. Captions must follow the CEA-708 standard for injection
  39168. * into an MPEG-2 transport streams.
  39169. * @see https://en.wikipedia.org/wiki/CEA-708
  39170. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  39171. */
  39172. // payload type field to indicate how they are to be
  39173. // interpreted. CEAS-708 caption content is always transmitted with
  39174. // payload type 0x04.
  39175. var USER_DATA_REGISTERED_ITU_T_T35 = 4,
  39176. RBSP_TRAILING_BITS = 128;
  39177. /**
  39178. * Parse a supplemental enhancement information (SEI) NAL unit.
  39179. * Stops parsing once a message of type ITU T T35 has been found.
  39180. *
  39181. * @param bytes {Uint8Array} the bytes of a SEI NAL unit
  39182. * @return {object} the parsed SEI payload
  39183. * @see Rec. ITU-T H.264, 7.3.2.3.1
  39184. */
  39185. var parseSei = function parseSei(bytes) {
  39186. var i = 0,
  39187. result = {
  39188. payloadType: -1,
  39189. payloadSize: 0
  39190. },
  39191. payloadType = 0,
  39192. payloadSize = 0; // go through the sei_rbsp parsing each each individual sei_message
  39193. while (i < bytes.byteLength) {
  39194. // stop once we have hit the end of the sei_rbsp
  39195. if (bytes[i] === RBSP_TRAILING_BITS) {
  39196. break;
  39197. } // Parse payload type
  39198. while (bytes[i] === 0xFF) {
  39199. payloadType += 255;
  39200. i++;
  39201. }
  39202. payloadType += bytes[i++]; // Parse payload size
  39203. while (bytes[i] === 0xFF) {
  39204. payloadSize += 255;
  39205. i++;
  39206. }
  39207. payloadSize += bytes[i++]; // this sei_message is a 608/708 caption so save it and break
  39208. // there can only ever be one caption message in a frame's sei
  39209. if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
  39210. var userIdentifier = String.fromCharCode(bytes[i + 3], bytes[i + 4], bytes[i + 5], bytes[i + 6]);
  39211. if (userIdentifier === 'GA94') {
  39212. result.payloadType = payloadType;
  39213. result.payloadSize = payloadSize;
  39214. result.payload = bytes.subarray(i, i + payloadSize);
  39215. break;
  39216. } else {
  39217. result.payload = void 0;
  39218. }
  39219. } // skip the payload and parse the next message
  39220. i += payloadSize;
  39221. payloadType = 0;
  39222. payloadSize = 0;
  39223. }
  39224. return result;
  39225. }; // see ANSI/SCTE 128-1 (2013), section 8.1
  39226. var parseUserData = function parseUserData(sei) {
  39227. // itu_t_t35_contry_code must be 181 (United States) for
  39228. // captions
  39229. if (sei.payload[0] !== 181) {
  39230. return null;
  39231. } // itu_t_t35_provider_code should be 49 (ATSC) for captions
  39232. if ((sei.payload[1] << 8 | sei.payload[2]) !== 49) {
  39233. return null;
  39234. } // the user_identifier should be "GA94" to indicate ATSC1 data
  39235. if (String.fromCharCode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== 'GA94') {
  39236. return null;
  39237. } // finally, user_data_type_code should be 0x03 for caption data
  39238. if (sei.payload[7] !== 0x03) {
  39239. return null;
  39240. } // return the user_data_type_structure and strip the trailing
  39241. // marker bits
  39242. return sei.payload.subarray(8, sei.payload.length - 1);
  39243. }; // see CEA-708-D, section 4.4
  39244. var parseCaptionPackets = function parseCaptionPackets(pts, userData) {
  39245. var results = [],
  39246. i,
  39247. count,
  39248. offset,
  39249. data; // if this is just filler, return immediately
  39250. if (!(userData[0] & 0x40)) {
  39251. return results;
  39252. } // parse out the cc_data_1 and cc_data_2 fields
  39253. count = userData[0] & 0x1f;
  39254. for (i = 0; i < count; i++) {
  39255. offset = i * 3;
  39256. data = {
  39257. type: userData[offset + 2] & 0x03,
  39258. pts: pts
  39259. }; // capture cc data when cc_valid is 1
  39260. if (userData[offset + 2] & 0x04) {
  39261. data.ccData = userData[offset + 3] << 8 | userData[offset + 4];
  39262. results.push(data);
  39263. }
  39264. }
  39265. return results;
  39266. };
  39267. var discardEmulationPreventionBytes$1 = function discardEmulationPreventionBytes(data) {
  39268. var length = data.byteLength,
  39269. emulationPreventionBytesPositions = [],
  39270. i = 1,
  39271. newLength,
  39272. newData; // Find all `Emulation Prevention Bytes`
  39273. while (i < length - 2) {
  39274. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  39275. emulationPreventionBytesPositions.push(i + 2);
  39276. i += 2;
  39277. } else {
  39278. i++;
  39279. }
  39280. } // If no Emulation Prevention Bytes were found just return the original
  39281. // array
  39282. if (emulationPreventionBytesPositions.length === 0) {
  39283. return data;
  39284. } // Create a new array to hold the NAL unit data
  39285. newLength = length - emulationPreventionBytesPositions.length;
  39286. newData = new Uint8Array(newLength);
  39287. var sourceIndex = 0;
  39288. for (i = 0; i < newLength; sourceIndex++, i++) {
  39289. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  39290. // Skip this byte
  39291. sourceIndex++; // Remove this position index
  39292. emulationPreventionBytesPositions.shift();
  39293. }
  39294. newData[i] = data[sourceIndex];
  39295. }
  39296. return newData;
  39297. }; // exports
  39298. var captionPacketParser = {
  39299. parseSei: parseSei,
  39300. parseUserData: parseUserData,
  39301. parseCaptionPackets: parseCaptionPackets,
  39302. discardEmulationPreventionBytes: discardEmulationPreventionBytes$1,
  39303. USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
  39304. }; // Link To Transport
  39305. // -----------------
  39306. var CaptionStream$1 = function CaptionStream(options) {
  39307. options = options || {};
  39308. CaptionStream.prototype.init.call(this); // parse708captions flag, default to true
  39309. this.parse708captions_ = typeof options.parse708captions === 'boolean' ? options.parse708captions : true;
  39310. this.captionPackets_ = [];
  39311. this.ccStreams_ = [new Cea608Stream(0, 0), // eslint-disable-line no-use-before-define
  39312. new Cea608Stream(0, 1), // eslint-disable-line no-use-before-define
  39313. new Cea608Stream(1, 0), // eslint-disable-line no-use-before-define
  39314. new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
  39315. ];
  39316. if (this.parse708captions_) {
  39317. this.cc708Stream_ = new Cea708Stream({
  39318. captionServices: options.captionServices
  39319. }); // eslint-disable-line no-use-before-define
  39320. }
  39321. this.reset(); // forward data and done events from CCs to this CaptionStream
  39322. this.ccStreams_.forEach(function (cc) {
  39323. cc.on('data', this.trigger.bind(this, 'data'));
  39324. cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
  39325. cc.on('done', this.trigger.bind(this, 'done'));
  39326. }, this);
  39327. if (this.parse708captions_) {
  39328. this.cc708Stream_.on('data', this.trigger.bind(this, 'data'));
  39329. this.cc708Stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));
  39330. this.cc708Stream_.on('done', this.trigger.bind(this, 'done'));
  39331. }
  39332. };
  39333. CaptionStream$1.prototype = new stream();
  39334. CaptionStream$1.prototype.push = function (event) {
  39335. var sei, userData, newCaptionPackets; // only examine SEI NALs
  39336. if (event.nalUnitType !== 'sei_rbsp') {
  39337. return;
  39338. } // parse the sei
  39339. sei = captionPacketParser.parseSei(event.escapedRBSP); // no payload data, skip
  39340. if (!sei.payload) {
  39341. return;
  39342. } // ignore everything but user_data_registered_itu_t_t35
  39343. if (sei.payloadType !== captionPacketParser.USER_DATA_REGISTERED_ITU_T_T35) {
  39344. return;
  39345. } // parse out the user data payload
  39346. userData = captionPacketParser.parseUserData(sei); // ignore unrecognized userData
  39347. if (!userData) {
  39348. return;
  39349. } // Sometimes, the same segment # will be downloaded twice. To stop the
  39350. // caption data from being processed twice, we track the latest dts we've
  39351. // received and ignore everything with a dts before that. However, since
  39352. // data for a specific dts can be split across packets on either side of
  39353. // a segment boundary, we need to make sure we *don't* ignore the packets
  39354. // from the *next* segment that have dts === this.latestDts_. By constantly
  39355. // tracking the number of packets received with dts === this.latestDts_, we
  39356. // know how many should be ignored once we start receiving duplicates.
  39357. if (event.dts < this.latestDts_) {
  39358. // We've started getting older data, so set the flag.
  39359. this.ignoreNextEqualDts_ = true;
  39360. return;
  39361. } else if (event.dts === this.latestDts_ && this.ignoreNextEqualDts_) {
  39362. this.numSameDts_--;
  39363. if (!this.numSameDts_) {
  39364. // We've received the last duplicate packet, time to start processing again
  39365. this.ignoreNextEqualDts_ = false;
  39366. }
  39367. return;
  39368. } // parse out CC data packets and save them for later
  39369. newCaptionPackets = captionPacketParser.parseCaptionPackets(event.pts, userData);
  39370. this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
  39371. if (this.latestDts_ !== event.dts) {
  39372. this.numSameDts_ = 0;
  39373. }
  39374. this.numSameDts_++;
  39375. this.latestDts_ = event.dts;
  39376. };
  39377. CaptionStream$1.prototype.flushCCStreams = function (flushType) {
  39378. this.ccStreams_.forEach(function (cc) {
  39379. return flushType === 'flush' ? cc.flush() : cc.partialFlush();
  39380. }, this);
  39381. };
  39382. CaptionStream$1.prototype.flushStream = function (flushType) {
  39383. // make sure we actually parsed captions before proceeding
  39384. if (!this.captionPackets_.length) {
  39385. this.flushCCStreams(flushType);
  39386. return;
  39387. } // In Chrome, the Array#sort function is not stable so add a
  39388. // presortIndex that we can use to ensure we get a stable-sort
  39389. this.captionPackets_.forEach(function (elem, idx) {
  39390. elem.presortIndex = idx;
  39391. }); // sort caption byte-pairs based on their PTS values
  39392. this.captionPackets_.sort(function (a, b) {
  39393. if (a.pts === b.pts) {
  39394. return a.presortIndex - b.presortIndex;
  39395. }
  39396. return a.pts - b.pts;
  39397. });
  39398. this.captionPackets_.forEach(function (packet) {
  39399. if (packet.type < 2) {
  39400. // Dispatch packet to the right Cea608Stream
  39401. this.dispatchCea608Packet(packet);
  39402. } else {
  39403. // Dispatch packet to the Cea708Stream
  39404. this.dispatchCea708Packet(packet);
  39405. }
  39406. }, this);
  39407. this.captionPackets_.length = 0;
  39408. this.flushCCStreams(flushType);
  39409. };
  39410. CaptionStream$1.prototype.flush = function () {
  39411. return this.flushStream('flush');
  39412. }; // Only called if handling partial data
  39413. CaptionStream$1.prototype.partialFlush = function () {
  39414. return this.flushStream('partialFlush');
  39415. };
  39416. CaptionStream$1.prototype.reset = function () {
  39417. this.latestDts_ = null;
  39418. this.ignoreNextEqualDts_ = false;
  39419. this.numSameDts_ = 0;
  39420. this.activeCea608Channel_ = [null, null];
  39421. this.ccStreams_.forEach(function (ccStream) {
  39422. ccStream.reset();
  39423. });
  39424. }; // From the CEA-608 spec:
  39425. /*
  39426. * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
  39427. * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
  39428. * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
  39429. * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
  39430. * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
  39431. * to switch to captioning or Text.
  39432. */
  39433. // With that in mind, we ignore any data between an XDS control code and a
  39434. // subsequent closed-captioning control code.
  39435. CaptionStream$1.prototype.dispatchCea608Packet = function (packet) {
  39436. // NOTE: packet.type is the CEA608 field
  39437. if (this.setsTextOrXDSActive(packet)) {
  39438. this.activeCea608Channel_[packet.type] = null;
  39439. } else if (this.setsChannel1Active(packet)) {
  39440. this.activeCea608Channel_[packet.type] = 0;
  39441. } else if (this.setsChannel2Active(packet)) {
  39442. this.activeCea608Channel_[packet.type] = 1;
  39443. }
  39444. if (this.activeCea608Channel_[packet.type] === null) {
  39445. // If we haven't received anything to set the active channel, or the
  39446. // packets are Text/XDS data, discard the data; we don't want jumbled
  39447. // captions
  39448. return;
  39449. }
  39450. this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
  39451. };
  39452. CaptionStream$1.prototype.setsChannel1Active = function (packet) {
  39453. return (packet.ccData & 0x7800) === 0x1000;
  39454. };
  39455. CaptionStream$1.prototype.setsChannel2Active = function (packet) {
  39456. return (packet.ccData & 0x7800) === 0x1800;
  39457. };
  39458. CaptionStream$1.prototype.setsTextOrXDSActive = function (packet) {
  39459. return (packet.ccData & 0x7100) === 0x0100 || (packet.ccData & 0x78fe) === 0x102a || (packet.ccData & 0x78fe) === 0x182a;
  39460. };
  39461. CaptionStream$1.prototype.dispatchCea708Packet = function (packet) {
  39462. if (this.parse708captions_) {
  39463. this.cc708Stream_.push(packet);
  39464. }
  39465. }; // ----------------------
  39466. // Session to Application
  39467. // ----------------------
  39468. // This hash maps special and extended character codes to their
  39469. // proper Unicode equivalent. The first one-byte key is just a
  39470. // non-standard character code. The two-byte keys that follow are
  39471. // the extended CEA708 character codes, along with the preceding
  39472. // 0x10 extended character byte to distinguish these codes from
  39473. // non-extended character codes. Every CEA708 character code that
  39474. // is not in this object maps directly to a standard unicode
  39475. // character code.
  39476. // The transparent space and non-breaking transparent space are
  39477. // technically not fully supported since there is no code to
  39478. // make them transparent, so they have normal non-transparent
  39479. // stand-ins.
  39480. // The special closed caption (CC) character isn't a standard
  39481. // unicode character, so a fairly similar unicode character was
  39482. // chosen in it's place.
  39483. var CHARACTER_TRANSLATION_708 = {
  39484. 0x7f: 0x266a,
  39485. // ♪
  39486. 0x1020: 0x20,
  39487. // Transparent Space
  39488. 0x1021: 0xa0,
  39489. // Nob-breaking Transparent Space
  39490. 0x1025: 0x2026,
  39491. // …
  39492. 0x102a: 0x0160,
  39493. // Š
  39494. 0x102c: 0x0152,
  39495. // Œ
  39496. 0x1030: 0x2588,
  39497. // █
  39498. 0x1031: 0x2018,
  39499. // ‘
  39500. 0x1032: 0x2019,
  39501. // ’
  39502. 0x1033: 0x201c,
  39503. // “
  39504. 0x1034: 0x201d,
  39505. // ”
  39506. 0x1035: 0x2022,
  39507. // •
  39508. 0x1039: 0x2122,
  39509. // ™
  39510. 0x103a: 0x0161,
  39511. // š
  39512. 0x103c: 0x0153,
  39513. // œ
  39514. 0x103d: 0x2120,
  39515. // ℠
  39516. 0x103f: 0x0178,
  39517. // Ÿ
  39518. 0x1076: 0x215b,
  39519. // ⅛
  39520. 0x1077: 0x215c,
  39521. // ⅜
  39522. 0x1078: 0x215d,
  39523. // ⅝
  39524. 0x1079: 0x215e,
  39525. // ⅞
  39526. 0x107a: 0x23d0,
  39527. // ⏐
  39528. 0x107b: 0x23a4,
  39529. // ⎤
  39530. 0x107c: 0x23a3,
  39531. // ⎣
  39532. 0x107d: 0x23af,
  39533. // ⎯
  39534. 0x107e: 0x23a6,
  39535. // ⎦
  39536. 0x107f: 0x23a1,
  39537. // ⎡
  39538. 0x10a0: 0x3138 // ㄸ (CC char)
  39539. };
  39540. var get708CharFromCode = function get708CharFromCode(code) {
  39541. var newCode = CHARACTER_TRANSLATION_708[code] || code;
  39542. if (code & 0x1000 && code === newCode) {
  39543. // Invalid extended code
  39544. return '';
  39545. }
  39546. return String.fromCharCode(newCode);
  39547. };
  39548. var within708TextBlock = function within708TextBlock(b) {
  39549. return 0x20 <= b && b <= 0x7f || 0xa0 <= b && b <= 0xff;
  39550. };
  39551. var Cea708Window = function Cea708Window(windowNum) {
  39552. this.windowNum = windowNum;
  39553. this.reset();
  39554. };
  39555. Cea708Window.prototype.reset = function () {
  39556. this.clearText();
  39557. this.pendingNewLine = false;
  39558. this.winAttr = {};
  39559. this.penAttr = {};
  39560. this.penLoc = {};
  39561. this.penColor = {}; // These default values are arbitrary,
  39562. // defineWindow will usually override them
  39563. this.visible = 0;
  39564. this.rowLock = 0;
  39565. this.columnLock = 0;
  39566. this.priority = 0;
  39567. this.relativePositioning = 0;
  39568. this.anchorVertical = 0;
  39569. this.anchorHorizontal = 0;
  39570. this.anchorPoint = 0;
  39571. this.rowCount = 1;
  39572. this.virtualRowCount = this.rowCount + 1;
  39573. this.columnCount = 41;
  39574. this.windowStyle = 0;
  39575. this.penStyle = 0;
  39576. };
  39577. Cea708Window.prototype.getText = function () {
  39578. return this.rows.join('\n');
  39579. };
  39580. Cea708Window.prototype.clearText = function () {
  39581. this.rows = [''];
  39582. this.rowIdx = 0;
  39583. };
  39584. Cea708Window.prototype.newLine = function (pts) {
  39585. if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === 'function') {
  39586. this.beforeRowOverflow(pts);
  39587. }
  39588. if (this.rows.length > 0) {
  39589. this.rows.push('');
  39590. this.rowIdx++;
  39591. } // Show all virtual rows since there's no visible scrolling
  39592. while (this.rows.length > this.virtualRowCount) {
  39593. this.rows.shift();
  39594. this.rowIdx--;
  39595. }
  39596. };
  39597. Cea708Window.prototype.isEmpty = function () {
  39598. if (this.rows.length === 0) {
  39599. return true;
  39600. } else if (this.rows.length === 1) {
  39601. return this.rows[0] === '';
  39602. }
  39603. return false;
  39604. };
  39605. Cea708Window.prototype.addText = function (text) {
  39606. this.rows[this.rowIdx] += text;
  39607. };
  39608. Cea708Window.prototype.backspace = function () {
  39609. if (!this.isEmpty()) {
  39610. var row = this.rows[this.rowIdx];
  39611. this.rows[this.rowIdx] = row.substr(0, row.length - 1);
  39612. }
  39613. };
  39614. var Cea708Service = function Cea708Service(serviceNum, encoding, stream) {
  39615. this.serviceNum = serviceNum;
  39616. this.text = '';
  39617. this.currentWindow = new Cea708Window(-1);
  39618. this.windows = [];
  39619. this.stream = stream; // Try to setup a TextDecoder if an `encoding` value was provided
  39620. if (typeof encoding === 'string') {
  39621. this.createTextDecoder(encoding);
  39622. }
  39623. };
  39624. /**
  39625. * Initialize service windows
  39626. * Must be run before service use
  39627. *
  39628. * @param {Integer} pts PTS value
  39629. * @param {Function} beforeRowOverflow Function to execute before row overflow of a window
  39630. */
  39631. Cea708Service.prototype.init = function (pts, beforeRowOverflow) {
  39632. this.startPts = pts;
  39633. for (var win = 0; win < 8; win++) {
  39634. this.windows[win] = new Cea708Window(win);
  39635. if (typeof beforeRowOverflow === 'function') {
  39636. this.windows[win].beforeRowOverflow = beforeRowOverflow;
  39637. }
  39638. }
  39639. };
  39640. /**
  39641. * Set current window of service to be affected by commands
  39642. *
  39643. * @param {Integer} windowNum Window number
  39644. */
  39645. Cea708Service.prototype.setCurrentWindow = function (windowNum) {
  39646. this.currentWindow = this.windows[windowNum];
  39647. };
  39648. /**
  39649. * Try to create a TextDecoder if it is natively supported
  39650. */
  39651. Cea708Service.prototype.createTextDecoder = function (encoding) {
  39652. if (typeof TextDecoder === 'undefined') {
  39653. this.stream.trigger('log', {
  39654. level: 'warn',
  39655. message: 'The `encoding` option is unsupported without TextDecoder support'
  39656. });
  39657. } else {
  39658. try {
  39659. this.textDecoder_ = new TextDecoder(encoding);
  39660. } catch (error) {
  39661. this.stream.trigger('log', {
  39662. level: 'warn',
  39663. message: 'TextDecoder could not be created with ' + encoding + ' encoding. ' + error
  39664. });
  39665. }
  39666. }
  39667. };
  39668. var Cea708Stream = function Cea708Stream(options) {
  39669. options = options || {};
  39670. Cea708Stream.prototype.init.call(this);
  39671. var self = this;
  39672. var captionServices = options.captionServices || {};
  39673. var captionServiceEncodings = {};
  39674. var serviceProps; // Get service encodings from captionServices option block
  39675. Object.keys(captionServices).forEach(function (serviceName) {
  39676. serviceProps = captionServices[serviceName];
  39677. if (/^SERVICE/.test(serviceName)) {
  39678. captionServiceEncodings[serviceName] = serviceProps.encoding;
  39679. }
  39680. });
  39681. this.serviceEncodings = captionServiceEncodings;
  39682. this.current708Packet = null;
  39683. this.services = {};
  39684. this.push = function (packet) {
  39685. if (packet.type === 3) {
  39686. // 708 packet start
  39687. self.new708Packet();
  39688. self.add708Bytes(packet);
  39689. } else {
  39690. if (self.current708Packet === null) {
  39691. // This should only happen at the start of a file if there's no packet start.
  39692. self.new708Packet();
  39693. }
  39694. self.add708Bytes(packet);
  39695. }
  39696. };
  39697. };
  39698. Cea708Stream.prototype = new stream();
  39699. /**
  39700. * Push current 708 packet, create new 708 packet.
  39701. */
  39702. Cea708Stream.prototype.new708Packet = function () {
  39703. if (this.current708Packet !== null) {
  39704. this.push708Packet();
  39705. }
  39706. this.current708Packet = {
  39707. data: [],
  39708. ptsVals: []
  39709. };
  39710. };
  39711. /**
  39712. * Add pts and both bytes from packet into current 708 packet.
  39713. */
  39714. Cea708Stream.prototype.add708Bytes = function (packet) {
  39715. var data = packet.ccData;
  39716. var byte0 = data >>> 8;
  39717. var byte1 = data & 0xff; // I would just keep a list of packets instead of bytes, but it isn't clear in the spec
  39718. // that service blocks will always line up with byte pairs.
  39719. this.current708Packet.ptsVals.push(packet.pts);
  39720. this.current708Packet.data.push(byte0);
  39721. this.current708Packet.data.push(byte1);
  39722. };
  39723. /**
  39724. * Parse completed 708 packet into service blocks and push each service block.
  39725. */
  39726. Cea708Stream.prototype.push708Packet = function () {
  39727. var packet708 = this.current708Packet;
  39728. var packetData = packet708.data;
  39729. var serviceNum = null;
  39730. var blockSize = null;
  39731. var i = 0;
  39732. var b = packetData[i++];
  39733. packet708.seq = b >> 6;
  39734. packet708.sizeCode = b & 0x3f; // 0b00111111;
  39735. for (; i < packetData.length; i++) {
  39736. b = packetData[i++];
  39737. serviceNum = b >> 5;
  39738. blockSize = b & 0x1f; // 0b00011111
  39739. if (serviceNum === 7 && blockSize > 0) {
  39740. // Extended service num
  39741. b = packetData[i++];
  39742. serviceNum = b;
  39743. }
  39744. this.pushServiceBlock(serviceNum, i, blockSize);
  39745. if (blockSize > 0) {
  39746. i += blockSize - 1;
  39747. }
  39748. }
  39749. };
  39750. /**
  39751. * Parse service block, execute commands, read text.
  39752. *
  39753. * Note: While many of these commands serve important purposes,
  39754. * many others just parse out the parameters or attributes, but
  39755. * nothing is done with them because this is not a full and complete
  39756. * implementation of the entire 708 spec.
  39757. *
  39758. * @param {Integer} serviceNum Service number
  39759. * @param {Integer} start Start index of the 708 packet data
  39760. * @param {Integer} size Block size
  39761. */
  39762. Cea708Stream.prototype.pushServiceBlock = function (serviceNum, start, size) {
  39763. var b;
  39764. var i = start;
  39765. var packetData = this.current708Packet.data;
  39766. var service = this.services[serviceNum];
  39767. if (!service) {
  39768. service = this.initService(serviceNum, i);
  39769. }
  39770. for (; i < start + size && i < packetData.length; i++) {
  39771. b = packetData[i];
  39772. if (within708TextBlock(b)) {
  39773. i = this.handleText(i, service);
  39774. } else if (b === 0x18) {
  39775. i = this.multiByteCharacter(i, service);
  39776. } else if (b === 0x10) {
  39777. i = this.extendedCommands(i, service);
  39778. } else if (0x80 <= b && b <= 0x87) {
  39779. i = this.setCurrentWindow(i, service);
  39780. } else if (0x98 <= b && b <= 0x9f) {
  39781. i = this.defineWindow(i, service);
  39782. } else if (b === 0x88) {
  39783. i = this.clearWindows(i, service);
  39784. } else if (b === 0x8c) {
  39785. i = this.deleteWindows(i, service);
  39786. } else if (b === 0x89) {
  39787. i = this.displayWindows(i, service);
  39788. } else if (b === 0x8a) {
  39789. i = this.hideWindows(i, service);
  39790. } else if (b === 0x8b) {
  39791. i = this.toggleWindows(i, service);
  39792. } else if (b === 0x97) {
  39793. i = this.setWindowAttributes(i, service);
  39794. } else if (b === 0x90) {
  39795. i = this.setPenAttributes(i, service);
  39796. } else if (b === 0x91) {
  39797. i = this.setPenColor(i, service);
  39798. } else if (b === 0x92) {
  39799. i = this.setPenLocation(i, service);
  39800. } else if (b === 0x8f) {
  39801. service = this.reset(i, service);
  39802. } else if (b === 0x08) {
  39803. // BS: Backspace
  39804. service.currentWindow.backspace();
  39805. } else if (b === 0x0c) {
  39806. // FF: Form feed
  39807. service.currentWindow.clearText();
  39808. } else if (b === 0x0d) {
  39809. // CR: Carriage return
  39810. service.currentWindow.pendingNewLine = true;
  39811. } else if (b === 0x0e) {
  39812. // HCR: Horizontal carriage return
  39813. service.currentWindow.clearText();
  39814. } else if (b === 0x8d) {
  39815. // DLY: Delay, nothing to do
  39816. i++;
  39817. } else ;
  39818. }
  39819. };
  39820. /**
  39821. * Execute an extended command
  39822. *
  39823. * @param {Integer} i Current index in the 708 packet
  39824. * @param {Service} service The service object to be affected
  39825. * @return {Integer} New index after parsing
  39826. */
  39827. Cea708Stream.prototype.extendedCommands = function (i, service) {
  39828. var packetData = this.current708Packet.data;
  39829. var b = packetData[++i];
  39830. if (within708TextBlock(b)) {
  39831. i = this.handleText(i, service, {
  39832. isExtended: true
  39833. });
  39834. }
  39835. return i;
  39836. };
  39837. /**
  39838. * Get PTS value of a given byte index
  39839. *
  39840. * @param {Integer} byteIndex Index of the byte
  39841. * @return {Integer} PTS
  39842. */
  39843. Cea708Stream.prototype.getPts = function (byteIndex) {
  39844. // There's 1 pts value per 2 bytes
  39845. return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];
  39846. };
  39847. /**
  39848. * Initializes a service
  39849. *
  39850. * @param {Integer} serviceNum Service number
  39851. * @return {Service} Initialized service object
  39852. */
  39853. Cea708Stream.prototype.initService = function (serviceNum, i) {
  39854. var serviceName = 'SERVICE' + serviceNum;
  39855. var self = this;
  39856. var serviceName;
  39857. var encoding;
  39858. if (serviceName in this.serviceEncodings) {
  39859. encoding = this.serviceEncodings[serviceName];
  39860. }
  39861. this.services[serviceNum] = new Cea708Service(serviceNum, encoding, self);
  39862. this.services[serviceNum].init(this.getPts(i), function (pts) {
  39863. self.flushDisplayed(pts, self.services[serviceNum]);
  39864. });
  39865. return this.services[serviceNum];
  39866. };
  39867. /**
  39868. * Execute text writing to current window
  39869. *
  39870. * @param {Integer} i Current index in the 708 packet
  39871. * @param {Service} service The service object to be affected
  39872. * @return {Integer} New index after parsing
  39873. */
  39874. Cea708Stream.prototype.handleText = function (i, service, options) {
  39875. var isExtended = options && options.isExtended;
  39876. var isMultiByte = options && options.isMultiByte;
  39877. var packetData = this.current708Packet.data;
  39878. var extended = isExtended ? 0x1000 : 0x0000;
  39879. var currentByte = packetData[i];
  39880. var nextByte = packetData[i + 1];
  39881. var win = service.currentWindow;
  39882. var _char;
  39883. var charCodeArray; // Use the TextDecoder if one was created for this service
  39884. if (service.textDecoder_ && !isExtended) {
  39885. if (isMultiByte) {
  39886. charCodeArray = [currentByte, nextByte];
  39887. i++;
  39888. } else {
  39889. charCodeArray = [currentByte];
  39890. }
  39891. _char = service.textDecoder_.decode(new Uint8Array(charCodeArray));
  39892. } else {
  39893. _char = get708CharFromCode(extended | currentByte);
  39894. }
  39895. if (win.pendingNewLine && !win.isEmpty()) {
  39896. win.newLine(this.getPts(i));
  39897. }
  39898. win.pendingNewLine = false;
  39899. win.addText(_char);
  39900. return i;
  39901. };
  39902. /**
  39903. * Handle decoding of multibyte character
  39904. *
  39905. * @param {Integer} i Current index in the 708 packet
  39906. * @param {Service} service The service object to be affected
  39907. * @return {Integer} New index after parsing
  39908. */
  39909. Cea708Stream.prototype.multiByteCharacter = function (i, service) {
  39910. var packetData = this.current708Packet.data;
  39911. var firstByte = packetData[i + 1];
  39912. var secondByte = packetData[i + 2];
  39913. if (within708TextBlock(firstByte) && within708TextBlock(secondByte)) {
  39914. i = this.handleText(++i, service, {
  39915. isMultiByte: true
  39916. });
  39917. }
  39918. return i;
  39919. };
  39920. /**
  39921. * Parse and execute the CW# command.
  39922. *
  39923. * Set the current window.
  39924. *
  39925. * @param {Integer} i Current index in the 708 packet
  39926. * @param {Service} service The service object to be affected
  39927. * @return {Integer} New index after parsing
  39928. */
  39929. Cea708Stream.prototype.setCurrentWindow = function (i, service) {
  39930. var packetData = this.current708Packet.data;
  39931. var b = packetData[i];
  39932. var windowNum = b & 0x07;
  39933. service.setCurrentWindow(windowNum);
  39934. return i;
  39935. };
  39936. /**
  39937. * Parse and execute the DF# command.
  39938. *
  39939. * Define a window and set it as the current window.
  39940. *
  39941. * @param {Integer} i Current index in the 708 packet
  39942. * @param {Service} service The service object to be affected
  39943. * @return {Integer} New index after parsing
  39944. */
  39945. Cea708Stream.prototype.defineWindow = function (i, service) {
  39946. var packetData = this.current708Packet.data;
  39947. var b = packetData[i];
  39948. var windowNum = b & 0x07;
  39949. service.setCurrentWindow(windowNum);
  39950. var win = service.currentWindow;
  39951. b = packetData[++i];
  39952. win.visible = (b & 0x20) >> 5; // v
  39953. win.rowLock = (b & 0x10) >> 4; // rl
  39954. win.columnLock = (b & 0x08) >> 3; // cl
  39955. win.priority = b & 0x07; // p
  39956. b = packetData[++i];
  39957. win.relativePositioning = (b & 0x80) >> 7; // rp
  39958. win.anchorVertical = b & 0x7f; // av
  39959. b = packetData[++i];
  39960. win.anchorHorizontal = b; // ah
  39961. b = packetData[++i];
  39962. win.anchorPoint = (b & 0xf0) >> 4; // ap
  39963. win.rowCount = b & 0x0f; // rc
  39964. b = packetData[++i];
  39965. win.columnCount = b & 0x3f; // cc
  39966. b = packetData[++i];
  39967. win.windowStyle = (b & 0x38) >> 3; // ws
  39968. win.penStyle = b & 0x07; // ps
  39969. // The spec says there are (rowCount+1) "virtual rows"
  39970. win.virtualRowCount = win.rowCount + 1;
  39971. return i;
  39972. };
  39973. /**
  39974. * Parse and execute the SWA command.
  39975. *
  39976. * Set attributes of the current window.
  39977. *
  39978. * @param {Integer} i Current index in the 708 packet
  39979. * @param {Service} service The service object to be affected
  39980. * @return {Integer} New index after parsing
  39981. */
  39982. Cea708Stream.prototype.setWindowAttributes = function (i, service) {
  39983. var packetData = this.current708Packet.data;
  39984. var b = packetData[i];
  39985. var winAttr = service.currentWindow.winAttr;
  39986. b = packetData[++i];
  39987. winAttr.fillOpacity = (b & 0xc0) >> 6; // fo
  39988. winAttr.fillRed = (b & 0x30) >> 4; // fr
  39989. winAttr.fillGreen = (b & 0x0c) >> 2; // fg
  39990. winAttr.fillBlue = b & 0x03; // fb
  39991. b = packetData[++i];
  39992. winAttr.borderType = (b & 0xc0) >> 6; // bt
  39993. winAttr.borderRed = (b & 0x30) >> 4; // br
  39994. winAttr.borderGreen = (b & 0x0c) >> 2; // bg
  39995. winAttr.borderBlue = b & 0x03; // bb
  39996. b = packetData[++i];
  39997. winAttr.borderType += (b & 0x80) >> 5; // bt
  39998. winAttr.wordWrap = (b & 0x40) >> 6; // ww
  39999. winAttr.printDirection = (b & 0x30) >> 4; // pd
  40000. winAttr.scrollDirection = (b & 0x0c) >> 2; // sd
  40001. winAttr.justify = b & 0x03; // j
  40002. b = packetData[++i];
  40003. winAttr.effectSpeed = (b & 0xf0) >> 4; // es
  40004. winAttr.effectDirection = (b & 0x0c) >> 2; // ed
  40005. winAttr.displayEffect = b & 0x03; // de
  40006. return i;
  40007. };
  40008. /**
  40009. * Gather text from all displayed windows and push a caption to output.
  40010. *
  40011. * @param {Integer} i Current index in the 708 packet
  40012. * @param {Service} service The service object to be affected
  40013. */
  40014. Cea708Stream.prototype.flushDisplayed = function (pts, service) {
  40015. var displayedText = []; // TODO: Positioning not supported, displaying multiple windows will not necessarily
  40016. // display text in the correct order, but sample files so far have not shown any issue.
  40017. for (var winId = 0; winId < 8; winId++) {
  40018. if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {
  40019. displayedText.push(service.windows[winId].getText());
  40020. }
  40021. }
  40022. service.endPts = pts;
  40023. service.text = displayedText.join('\n\n');
  40024. this.pushCaption(service);
  40025. service.startPts = pts;
  40026. };
  40027. /**
  40028. * Push a caption to output if the caption contains text.
  40029. *
  40030. * @param {Service} service The service object to be affected
  40031. */
  40032. Cea708Stream.prototype.pushCaption = function (service) {
  40033. if (service.text !== '') {
  40034. this.trigger('data', {
  40035. startPts: service.startPts,
  40036. endPts: service.endPts,
  40037. text: service.text,
  40038. stream: 'cc708_' + service.serviceNum
  40039. });
  40040. service.text = '';
  40041. service.startPts = service.endPts;
  40042. }
  40043. };
  40044. /**
  40045. * Parse and execute the DSW command.
  40046. *
  40047. * Set visible property of windows based on the parsed bitmask.
  40048. *
  40049. * @param {Integer} i Current index in the 708 packet
  40050. * @param {Service} service The service object to be affected
  40051. * @return {Integer} New index after parsing
  40052. */
  40053. Cea708Stream.prototype.displayWindows = function (i, service) {
  40054. var packetData = this.current708Packet.data;
  40055. var b = packetData[++i];
  40056. var pts = this.getPts(i);
  40057. this.flushDisplayed(pts, service);
  40058. for (var winId = 0; winId < 8; winId++) {
  40059. if (b & 0x01 << winId) {
  40060. service.windows[winId].visible = 1;
  40061. }
  40062. }
  40063. return i;
  40064. };
  40065. /**
  40066. * Parse and execute the HDW command.
  40067. *
  40068. * Set visible property of windows based on the parsed bitmask.
  40069. *
  40070. * @param {Integer} i Current index in the 708 packet
  40071. * @param {Service} service The service object to be affected
  40072. * @return {Integer} New index after parsing
  40073. */
  40074. Cea708Stream.prototype.hideWindows = function (i, service) {
  40075. var packetData = this.current708Packet.data;
  40076. var b = packetData[++i];
  40077. var pts = this.getPts(i);
  40078. this.flushDisplayed(pts, service);
  40079. for (var winId = 0; winId < 8; winId++) {
  40080. if (b & 0x01 << winId) {
  40081. service.windows[winId].visible = 0;
  40082. }
  40083. }
  40084. return i;
  40085. };
  40086. /**
  40087. * Parse and execute the TGW command.
  40088. *
  40089. * Set visible property of windows based on the parsed bitmask.
  40090. *
  40091. * @param {Integer} i Current index in the 708 packet
  40092. * @param {Service} service The service object to be affected
  40093. * @return {Integer} New index after parsing
  40094. */
  40095. Cea708Stream.prototype.toggleWindows = function (i, service) {
  40096. var packetData = this.current708Packet.data;
  40097. var b = packetData[++i];
  40098. var pts = this.getPts(i);
  40099. this.flushDisplayed(pts, service);
  40100. for (var winId = 0; winId < 8; winId++) {
  40101. if (b & 0x01 << winId) {
  40102. service.windows[winId].visible ^= 1;
  40103. }
  40104. }
  40105. return i;
  40106. };
  40107. /**
  40108. * Parse and execute the CLW command.
  40109. *
  40110. * Clear text of windows based on the parsed bitmask.
  40111. *
  40112. * @param {Integer} i Current index in the 708 packet
  40113. * @param {Service} service The service object to be affected
  40114. * @return {Integer} New index after parsing
  40115. */
  40116. Cea708Stream.prototype.clearWindows = function (i, service) {
  40117. var packetData = this.current708Packet.data;
  40118. var b = packetData[++i];
  40119. var pts = this.getPts(i);
  40120. this.flushDisplayed(pts, service);
  40121. for (var winId = 0; winId < 8; winId++) {
  40122. if (b & 0x01 << winId) {
  40123. service.windows[winId].clearText();
  40124. }
  40125. }
  40126. return i;
  40127. };
  40128. /**
  40129. * Parse and execute the DLW command.
  40130. *
  40131. * Re-initialize windows based on the parsed bitmask.
  40132. *
  40133. * @param {Integer} i Current index in the 708 packet
  40134. * @param {Service} service The service object to be affected
  40135. * @return {Integer} New index after parsing
  40136. */
  40137. Cea708Stream.prototype.deleteWindows = function (i, service) {
  40138. var packetData = this.current708Packet.data;
  40139. var b = packetData[++i];
  40140. var pts = this.getPts(i);
  40141. this.flushDisplayed(pts, service);
  40142. for (var winId = 0; winId < 8; winId++) {
  40143. if (b & 0x01 << winId) {
  40144. service.windows[winId].reset();
  40145. }
  40146. }
  40147. return i;
  40148. };
  40149. /**
  40150. * Parse and execute the SPA command.
  40151. *
  40152. * Set pen attributes of the current window.
  40153. *
  40154. * @param {Integer} i Current index in the 708 packet
  40155. * @param {Service} service The service object to be affected
  40156. * @return {Integer} New index after parsing
  40157. */
  40158. Cea708Stream.prototype.setPenAttributes = function (i, service) {
  40159. var packetData = this.current708Packet.data;
  40160. var b = packetData[i];
  40161. var penAttr = service.currentWindow.penAttr;
  40162. b = packetData[++i];
  40163. penAttr.textTag = (b & 0xf0) >> 4; // tt
  40164. penAttr.offset = (b & 0x0c) >> 2; // o
  40165. penAttr.penSize = b & 0x03; // s
  40166. b = packetData[++i];
  40167. penAttr.italics = (b & 0x80) >> 7; // i
  40168. penAttr.underline = (b & 0x40) >> 6; // u
  40169. penAttr.edgeType = (b & 0x38) >> 3; // et
  40170. penAttr.fontStyle = b & 0x07; // fs
  40171. return i;
  40172. };
  40173. /**
  40174. * Parse and execute the SPC command.
  40175. *
  40176. * Set pen color of the current window.
  40177. *
  40178. * @param {Integer} i Current index in the 708 packet
  40179. * @param {Service} service The service object to be affected
  40180. * @return {Integer} New index after parsing
  40181. */
  40182. Cea708Stream.prototype.setPenColor = function (i, service) {
  40183. var packetData = this.current708Packet.data;
  40184. var b = packetData[i];
  40185. var penColor = service.currentWindow.penColor;
  40186. b = packetData[++i];
  40187. penColor.fgOpacity = (b & 0xc0) >> 6; // fo
  40188. penColor.fgRed = (b & 0x30) >> 4; // fr
  40189. penColor.fgGreen = (b & 0x0c) >> 2; // fg
  40190. penColor.fgBlue = b & 0x03; // fb
  40191. b = packetData[++i];
  40192. penColor.bgOpacity = (b & 0xc0) >> 6; // bo
  40193. penColor.bgRed = (b & 0x30) >> 4; // br
  40194. penColor.bgGreen = (b & 0x0c) >> 2; // bg
  40195. penColor.bgBlue = b & 0x03; // bb
  40196. b = packetData[++i];
  40197. penColor.edgeRed = (b & 0x30) >> 4; // er
  40198. penColor.edgeGreen = (b & 0x0c) >> 2; // eg
  40199. penColor.edgeBlue = b & 0x03; // eb
  40200. return i;
  40201. };
  40202. /**
  40203. * Parse and execute the SPL command.
  40204. *
  40205. * Set pen location of the current window.
  40206. *
  40207. * @param {Integer} i Current index in the 708 packet
  40208. * @param {Service} service The service object to be affected
  40209. * @return {Integer} New index after parsing
  40210. */
  40211. Cea708Stream.prototype.setPenLocation = function (i, service) {
  40212. var packetData = this.current708Packet.data;
  40213. var b = packetData[i];
  40214. var penLoc = service.currentWindow.penLoc; // Positioning isn't really supported at the moment, so this essentially just inserts a linebreak
  40215. service.currentWindow.pendingNewLine = true;
  40216. b = packetData[++i];
  40217. penLoc.row = b & 0x0f; // r
  40218. b = packetData[++i];
  40219. penLoc.column = b & 0x3f; // c
  40220. return i;
  40221. };
  40222. /**
  40223. * Execute the RST command.
  40224. *
  40225. * Reset service to a clean slate. Re-initialize.
  40226. *
  40227. * @param {Integer} i Current index in the 708 packet
  40228. * @param {Service} service The service object to be affected
  40229. * @return {Service} Re-initialized service
  40230. */
  40231. Cea708Stream.prototype.reset = function (i, service) {
  40232. var pts = this.getPts(i);
  40233. this.flushDisplayed(pts, service);
  40234. return this.initService(service.serviceNum, i);
  40235. }; // This hash maps non-ASCII, special, and extended character codes to their
  40236. // proper Unicode equivalent. The first keys that are only a single byte
  40237. // are the non-standard ASCII characters, which simply map the CEA608 byte
  40238. // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
  40239. // character codes, but have their MSB bitmasked with 0x03 so that a lookup
  40240. // can be performed regardless of the field and data channel on which the
  40241. // character code was received.
  40242. var CHARACTER_TRANSLATION = {
  40243. 0x2a: 0xe1,
  40244. // á
  40245. 0x5c: 0xe9,
  40246. // é
  40247. 0x5e: 0xed,
  40248. // í
  40249. 0x5f: 0xf3,
  40250. // ó
  40251. 0x60: 0xfa,
  40252. // ú
  40253. 0x7b: 0xe7,
  40254. // ç
  40255. 0x7c: 0xf7,
  40256. // ÷
  40257. 0x7d: 0xd1,
  40258. // Ñ
  40259. 0x7e: 0xf1,
  40260. // ñ
  40261. 0x7f: 0x2588,
  40262. // █
  40263. 0x0130: 0xae,
  40264. // ®
  40265. 0x0131: 0xb0,
  40266. // °
  40267. 0x0132: 0xbd,
  40268. // ½
  40269. 0x0133: 0xbf,
  40270. // ¿
  40271. 0x0134: 0x2122,
  40272. // ™
  40273. 0x0135: 0xa2,
  40274. // ¢
  40275. 0x0136: 0xa3,
  40276. // £
  40277. 0x0137: 0x266a,
  40278. // ♪
  40279. 0x0138: 0xe0,
  40280. // à
  40281. 0x0139: 0xa0,
  40282. //
  40283. 0x013a: 0xe8,
  40284. // è
  40285. 0x013b: 0xe2,
  40286. // â
  40287. 0x013c: 0xea,
  40288. // ê
  40289. 0x013d: 0xee,
  40290. // î
  40291. 0x013e: 0xf4,
  40292. // ô
  40293. 0x013f: 0xfb,
  40294. // û
  40295. 0x0220: 0xc1,
  40296. // Á
  40297. 0x0221: 0xc9,
  40298. // É
  40299. 0x0222: 0xd3,
  40300. // Ó
  40301. 0x0223: 0xda,
  40302. // Ú
  40303. 0x0224: 0xdc,
  40304. // Ü
  40305. 0x0225: 0xfc,
  40306. // ü
  40307. 0x0226: 0x2018,
  40308. // ‘
  40309. 0x0227: 0xa1,
  40310. // ¡
  40311. 0x0228: 0x2a,
  40312. // *
  40313. 0x0229: 0x27,
  40314. // '
  40315. 0x022a: 0x2014,
  40316. // —
  40317. 0x022b: 0xa9,
  40318. // ©
  40319. 0x022c: 0x2120,
  40320. // ℠
  40321. 0x022d: 0x2022,
  40322. // •
  40323. 0x022e: 0x201c,
  40324. // “
  40325. 0x022f: 0x201d,
  40326. // ”
  40327. 0x0230: 0xc0,
  40328. // À
  40329. 0x0231: 0xc2,
  40330. // Â
  40331. 0x0232: 0xc7,
  40332. // Ç
  40333. 0x0233: 0xc8,
  40334. // È
  40335. 0x0234: 0xca,
  40336. // Ê
  40337. 0x0235: 0xcb,
  40338. // Ë
  40339. 0x0236: 0xeb,
  40340. // ë
  40341. 0x0237: 0xce,
  40342. // Î
  40343. 0x0238: 0xcf,
  40344. // Ï
  40345. 0x0239: 0xef,
  40346. // ï
  40347. 0x023a: 0xd4,
  40348. // Ô
  40349. 0x023b: 0xd9,
  40350. // Ù
  40351. 0x023c: 0xf9,
  40352. // ù
  40353. 0x023d: 0xdb,
  40354. // Û
  40355. 0x023e: 0xab,
  40356. // «
  40357. 0x023f: 0xbb,
  40358. // »
  40359. 0x0320: 0xc3,
  40360. // Ã
  40361. 0x0321: 0xe3,
  40362. // ã
  40363. 0x0322: 0xcd,
  40364. // Í
  40365. 0x0323: 0xcc,
  40366. // Ì
  40367. 0x0324: 0xec,
  40368. // ì
  40369. 0x0325: 0xd2,
  40370. // Ò
  40371. 0x0326: 0xf2,
  40372. // ò
  40373. 0x0327: 0xd5,
  40374. // Õ
  40375. 0x0328: 0xf5,
  40376. // õ
  40377. 0x0329: 0x7b,
  40378. // {
  40379. 0x032a: 0x7d,
  40380. // }
  40381. 0x032b: 0x5c,
  40382. // \
  40383. 0x032c: 0x5e,
  40384. // ^
  40385. 0x032d: 0x5f,
  40386. // _
  40387. 0x032e: 0x7c,
  40388. // |
  40389. 0x032f: 0x7e,
  40390. // ~
  40391. 0x0330: 0xc4,
  40392. // Ä
  40393. 0x0331: 0xe4,
  40394. // ä
  40395. 0x0332: 0xd6,
  40396. // Ö
  40397. 0x0333: 0xf6,
  40398. // ö
  40399. 0x0334: 0xdf,
  40400. // ß
  40401. 0x0335: 0xa5,
  40402. // ¥
  40403. 0x0336: 0xa4,
  40404. // ¤
  40405. 0x0337: 0x2502,
  40406. // │
  40407. 0x0338: 0xc5,
  40408. // Å
  40409. 0x0339: 0xe5,
  40410. // å
  40411. 0x033a: 0xd8,
  40412. // Ø
  40413. 0x033b: 0xf8,
  40414. // ø
  40415. 0x033c: 0x250c,
  40416. // ┌
  40417. 0x033d: 0x2510,
  40418. // ┐
  40419. 0x033e: 0x2514,
  40420. // └
  40421. 0x033f: 0x2518 // ┘
  40422. };
  40423. var getCharFromCode = function getCharFromCode(code) {
  40424. if (code === null) {
  40425. return '';
  40426. }
  40427. code = CHARACTER_TRANSLATION[code] || code;
  40428. return String.fromCharCode(code);
  40429. }; // the index of the last row in a CEA-608 display buffer
  40430. var BOTTOM_ROW = 14; // This array is used for mapping PACs -> row #, since there's no way of
  40431. // getting it through bit logic.
  40432. var ROWS = [0x1100, 0x1120, 0x1200, 0x1220, 0x1500, 0x1520, 0x1600, 0x1620, 0x1700, 0x1720, 0x1000, 0x1300, 0x1320, 0x1400, 0x1420]; // CEA-608 captions are rendered onto a 34x15 matrix of character
  40433. // cells. The "bottom" row is the last element in the outer array.
  40434. var createDisplayBuffer = function createDisplayBuffer() {
  40435. var result = [],
  40436. i = BOTTOM_ROW + 1;
  40437. while (i--) {
  40438. result.push('');
  40439. }
  40440. return result;
  40441. };
  40442. var Cea608Stream = function Cea608Stream(field, dataChannel) {
  40443. Cea608Stream.prototype.init.call(this);
  40444. this.field_ = field || 0;
  40445. this.dataChannel_ = dataChannel || 0;
  40446. this.name_ = 'CC' + ((this.field_ << 1 | this.dataChannel_) + 1);
  40447. this.setConstants();
  40448. this.reset();
  40449. this.push = function (packet) {
  40450. var data, swap, char0, char1, text; // remove the parity bits
  40451. data = packet.ccData & 0x7f7f; // ignore duplicate control codes; the spec demands they're sent twice
  40452. if (data === this.lastControlCode_) {
  40453. this.lastControlCode_ = null;
  40454. return;
  40455. } // Store control codes
  40456. if ((data & 0xf000) === 0x1000) {
  40457. this.lastControlCode_ = data;
  40458. } else if (data !== this.PADDING_) {
  40459. this.lastControlCode_ = null;
  40460. }
  40461. char0 = data >>> 8;
  40462. char1 = data & 0xff;
  40463. if (data === this.PADDING_) {
  40464. return;
  40465. } else if (data === this.RESUME_CAPTION_LOADING_) {
  40466. this.mode_ = 'popOn';
  40467. } else if (data === this.END_OF_CAPTION_) {
  40468. // If an EOC is received while in paint-on mode, the displayed caption
  40469. // text should be swapped to non-displayed memory as if it was a pop-on
  40470. // caption. Because of that, we should explicitly switch back to pop-on
  40471. // mode
  40472. this.mode_ = 'popOn';
  40473. this.clearFormatting(packet.pts); // if a caption was being displayed, it's gone now
  40474. this.flushDisplayed(packet.pts); // flip memory
  40475. swap = this.displayed_;
  40476. this.displayed_ = this.nonDisplayed_;
  40477. this.nonDisplayed_ = swap; // start measuring the time to display the caption
  40478. this.startPts_ = packet.pts;
  40479. } else if (data === this.ROLL_UP_2_ROWS_) {
  40480. this.rollUpRows_ = 2;
  40481. this.setRollUp(packet.pts);
  40482. } else if (data === this.ROLL_UP_3_ROWS_) {
  40483. this.rollUpRows_ = 3;
  40484. this.setRollUp(packet.pts);
  40485. } else if (data === this.ROLL_UP_4_ROWS_) {
  40486. this.rollUpRows_ = 4;
  40487. this.setRollUp(packet.pts);
  40488. } else if (data === this.CARRIAGE_RETURN_) {
  40489. this.clearFormatting(packet.pts);
  40490. this.flushDisplayed(packet.pts);
  40491. this.shiftRowsUp_();
  40492. this.startPts_ = packet.pts;
  40493. } else if (data === this.BACKSPACE_) {
  40494. if (this.mode_ === 'popOn') {
  40495. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  40496. } else {
  40497. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  40498. }
  40499. } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
  40500. this.flushDisplayed(packet.pts);
  40501. this.displayed_ = createDisplayBuffer();
  40502. } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
  40503. this.nonDisplayed_ = createDisplayBuffer();
  40504. } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
  40505. if (this.mode_ !== 'paintOn') {
  40506. // NOTE: This should be removed when proper caption positioning is
  40507. // implemented
  40508. this.flushDisplayed(packet.pts);
  40509. this.displayed_ = createDisplayBuffer();
  40510. }
  40511. this.mode_ = 'paintOn';
  40512. this.startPts_ = packet.pts; // Append special characters to caption text
  40513. } else if (this.isSpecialCharacter(char0, char1)) {
  40514. // Bitmask char0 so that we can apply character transformations
  40515. // regardless of field and data channel.
  40516. // Then byte-shift to the left and OR with char1 so we can pass the
  40517. // entire character code to `getCharFromCode`.
  40518. char0 = (char0 & 0x03) << 8;
  40519. text = getCharFromCode(char0 | char1);
  40520. this[this.mode_](packet.pts, text);
  40521. this.column_++; // Append extended characters to caption text
  40522. } else if (this.isExtCharacter(char0, char1)) {
  40523. // Extended characters always follow their "non-extended" equivalents.
  40524. // IE if a "è" is desired, you'll always receive "eè"; non-compliant
  40525. // decoders are supposed to drop the "è", while compliant decoders
  40526. // backspace the "e" and insert "è".
  40527. // Delete the previous character
  40528. if (this.mode_ === 'popOn') {
  40529. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  40530. } else {
  40531. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  40532. } // Bitmask char0 so that we can apply character transformations
  40533. // regardless of field and data channel.
  40534. // Then byte-shift to the left and OR with char1 so we can pass the
  40535. // entire character code to `getCharFromCode`.
  40536. char0 = (char0 & 0x03) << 8;
  40537. text = getCharFromCode(char0 | char1);
  40538. this[this.mode_](packet.pts, text);
  40539. this.column_++; // Process mid-row codes
  40540. } else if (this.isMidRowCode(char0, char1)) {
  40541. // Attributes are not additive, so clear all formatting
  40542. this.clearFormatting(packet.pts); // According to the standard, mid-row codes
  40543. // should be replaced with spaces, so add one now
  40544. this[this.mode_](packet.pts, ' ');
  40545. this.column_++;
  40546. if ((char1 & 0xe) === 0xe) {
  40547. this.addFormatting(packet.pts, ['i']);
  40548. }
  40549. if ((char1 & 0x1) === 0x1) {
  40550. this.addFormatting(packet.pts, ['u']);
  40551. } // Detect offset control codes and adjust cursor
  40552. } else if (this.isOffsetControlCode(char0, char1)) {
  40553. // Cursor position is set by indent PAC (see below) in 4-column
  40554. // increments, with an additional offset code of 1-3 to reach any
  40555. // of the 32 columns specified by CEA-608. So all we need to do
  40556. // here is increment the column cursor by the given offset.
  40557. this.column_ += char1 & 0x03; // Detect PACs (Preamble Address Codes)
  40558. } else if (this.isPAC(char0, char1)) {
  40559. // There's no logic for PAC -> row mapping, so we have to just
  40560. // find the row code in an array and use its index :(
  40561. var row = ROWS.indexOf(data & 0x1f20); // Configure the caption window if we're in roll-up mode
  40562. if (this.mode_ === 'rollUp') {
  40563. // This implies that the base row is incorrectly set.
  40564. // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
  40565. // of roll-up rows set.
  40566. if (row - this.rollUpRows_ + 1 < 0) {
  40567. row = this.rollUpRows_ - 1;
  40568. }
  40569. this.setRollUp(packet.pts, row);
  40570. }
  40571. if (row !== this.row_) {
  40572. // formatting is only persistent for current row
  40573. this.clearFormatting(packet.pts);
  40574. this.row_ = row;
  40575. } // All PACs can apply underline, so detect and apply
  40576. // (All odd-numbered second bytes set underline)
  40577. if (char1 & 0x1 && this.formatting_.indexOf('u') === -1) {
  40578. this.addFormatting(packet.pts, ['u']);
  40579. }
  40580. if ((data & 0x10) === 0x10) {
  40581. // We've got an indent level code. Each successive even number
  40582. // increments the column cursor by 4, so we can get the desired
  40583. // column position by bit-shifting to the right (to get n/2)
  40584. // and multiplying by 4.
  40585. this.column_ = ((data & 0xe) >> 1) * 4;
  40586. }
  40587. if (this.isColorPAC(char1)) {
  40588. // it's a color code, though we only support white, which
  40589. // can be either normal or italicized. white italics can be
  40590. // either 0x4e or 0x6e depending on the row, so we just
  40591. // bitwise-and with 0xe to see if italics should be turned on
  40592. if ((char1 & 0xe) === 0xe) {
  40593. this.addFormatting(packet.pts, ['i']);
  40594. }
  40595. } // We have a normal character in char0, and possibly one in char1
  40596. } else if (this.isNormalChar(char0)) {
  40597. if (char1 === 0x00) {
  40598. char1 = null;
  40599. }
  40600. text = getCharFromCode(char0);
  40601. text += getCharFromCode(char1);
  40602. this[this.mode_](packet.pts, text);
  40603. this.column_ += text.length;
  40604. } // finish data processing
  40605. };
  40606. };
  40607. Cea608Stream.prototype = new stream(); // Trigger a cue point that captures the current state of the
  40608. // display buffer
  40609. Cea608Stream.prototype.flushDisplayed = function (pts) {
  40610. var content = this.displayed_ // remove spaces from the start and end of the string
  40611. .map(function (row, index) {
  40612. try {
  40613. return row.trim();
  40614. } catch (e) {
  40615. // Ordinarily, this shouldn't happen. However, caption
  40616. // parsing errors should not throw exceptions and
  40617. // break playback.
  40618. this.trigger('log', {
  40619. level: 'warn',
  40620. message: 'Skipping a malformed 608 caption at index ' + index + '.'
  40621. });
  40622. return '';
  40623. }
  40624. }, this) // combine all text rows to display in one cue
  40625. .join('\n') // and remove blank rows from the start and end, but not the middle
  40626. .replace(/^\n+|\n+$/g, '');
  40627. if (content.length) {
  40628. this.trigger('data', {
  40629. startPts: this.startPts_,
  40630. endPts: pts,
  40631. text: content,
  40632. stream: this.name_
  40633. });
  40634. }
  40635. };
  40636. /**
  40637. * Zero out the data, used for startup and on seek
  40638. */
  40639. Cea608Stream.prototype.reset = function () {
  40640. this.mode_ = 'popOn'; // When in roll-up mode, the index of the last row that will
  40641. // actually display captions. If a caption is shifted to a row
  40642. // with a lower index than this, it is cleared from the display
  40643. // buffer
  40644. this.topRow_ = 0;
  40645. this.startPts_ = 0;
  40646. this.displayed_ = createDisplayBuffer();
  40647. this.nonDisplayed_ = createDisplayBuffer();
  40648. this.lastControlCode_ = null; // Track row and column for proper line-breaking and spacing
  40649. this.column_ = 0;
  40650. this.row_ = BOTTOM_ROW;
  40651. this.rollUpRows_ = 2; // This variable holds currently-applied formatting
  40652. this.formatting_ = [];
  40653. };
  40654. /**
  40655. * Sets up control code and related constants for this instance
  40656. */
  40657. Cea608Stream.prototype.setConstants = function () {
  40658. // The following attributes have these uses:
  40659. // ext_ : char0 for mid-row codes, and the base for extended
  40660. // chars (ext_+0, ext_+1, and ext_+2 are char0s for
  40661. // extended codes)
  40662. // control_: char0 for control codes, except byte-shifted to the
  40663. // left so that we can do this.control_ | CONTROL_CODE
  40664. // offset_: char0 for tab offset codes
  40665. //
  40666. // It's also worth noting that control codes, and _only_ control codes,
  40667. // differ between field 1 and field2. Field 2 control codes are always
  40668. // their field 1 value plus 1. That's why there's the "| field" on the
  40669. // control value.
  40670. if (this.dataChannel_ === 0) {
  40671. this.BASE_ = 0x10;
  40672. this.EXT_ = 0x11;
  40673. this.CONTROL_ = (0x14 | this.field_) << 8;
  40674. this.OFFSET_ = 0x17;
  40675. } else if (this.dataChannel_ === 1) {
  40676. this.BASE_ = 0x18;
  40677. this.EXT_ = 0x19;
  40678. this.CONTROL_ = (0x1c | this.field_) << 8;
  40679. this.OFFSET_ = 0x1f;
  40680. } // Constants for the LSByte command codes recognized by Cea608Stream. This
  40681. // list is not exhaustive. For a more comprehensive listing and semantics see
  40682. // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
  40683. // Padding
  40684. this.PADDING_ = 0x0000; // Pop-on Mode
  40685. this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;
  40686. this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f; // Roll-up Mode
  40687. this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;
  40688. this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;
  40689. this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;
  40690. this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d; // paint-on mode
  40691. this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29; // Erasure
  40692. this.BACKSPACE_ = this.CONTROL_ | 0x21;
  40693. this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;
  40694. this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
  40695. };
  40696. /**
  40697. * Detects if the 2-byte packet data is a special character
  40698. *
  40699. * Special characters have a second byte in the range 0x30 to 0x3f,
  40700. * with the first byte being 0x11 (for data channel 1) or 0x19 (for
  40701. * data channel 2).
  40702. *
  40703. * @param {Integer} char0 The first byte
  40704. * @param {Integer} char1 The second byte
  40705. * @return {Boolean} Whether the 2 bytes are an special character
  40706. */
  40707. Cea608Stream.prototype.isSpecialCharacter = function (char0, char1) {
  40708. return char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f;
  40709. };
  40710. /**
  40711. * Detects if the 2-byte packet data is an extended character
  40712. *
  40713. * Extended characters have a second byte in the range 0x20 to 0x3f,
  40714. * with the first byte being 0x12 or 0x13 (for data channel 1) or
  40715. * 0x1a or 0x1b (for data channel 2).
  40716. *
  40717. * @param {Integer} char0 The first byte
  40718. * @param {Integer} char1 The second byte
  40719. * @return {Boolean} Whether the 2 bytes are an extended character
  40720. */
  40721. Cea608Stream.prototype.isExtCharacter = function (char0, char1) {
  40722. return (char0 === this.EXT_ + 1 || char0 === this.EXT_ + 2) && char1 >= 0x20 && char1 <= 0x3f;
  40723. };
  40724. /**
  40725. * Detects if the 2-byte packet is a mid-row code
  40726. *
  40727. * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
  40728. * the first byte being 0x11 (for data channel 1) or 0x19 (for data
  40729. * channel 2).
  40730. *
  40731. * @param {Integer} char0 The first byte
  40732. * @param {Integer} char1 The second byte
  40733. * @return {Boolean} Whether the 2 bytes are a mid-row code
  40734. */
  40735. Cea608Stream.prototype.isMidRowCode = function (char0, char1) {
  40736. return char0 === this.EXT_ && char1 >= 0x20 && char1 <= 0x2f;
  40737. };
  40738. /**
  40739. * Detects if the 2-byte packet is an offset control code
  40740. *
  40741. * Offset control codes have a second byte in the range 0x21 to 0x23,
  40742. * with the first byte being 0x17 (for data channel 1) or 0x1f (for
  40743. * data channel 2).
  40744. *
  40745. * @param {Integer} char0 The first byte
  40746. * @param {Integer} char1 The second byte
  40747. * @return {Boolean} Whether the 2 bytes are an offset control code
  40748. */
  40749. Cea608Stream.prototype.isOffsetControlCode = function (char0, char1) {
  40750. return char0 === this.OFFSET_ && char1 >= 0x21 && char1 <= 0x23;
  40751. };
  40752. /**
  40753. * Detects if the 2-byte packet is a Preamble Address Code
  40754. *
  40755. * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
  40756. * or 0x18 to 0x1f (for data channel 2), with the second byte in the
  40757. * range 0x40 to 0x7f.
  40758. *
  40759. * @param {Integer} char0 The first byte
  40760. * @param {Integer} char1 The second byte
  40761. * @return {Boolean} Whether the 2 bytes are a PAC
  40762. */
  40763. Cea608Stream.prototype.isPAC = function (char0, char1) {
  40764. return char0 >= this.BASE_ && char0 < this.BASE_ + 8 && char1 >= 0x40 && char1 <= 0x7f;
  40765. };
  40766. /**
  40767. * Detects if a packet's second byte is in the range of a PAC color code
  40768. *
  40769. * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
  40770. * 0x60 to 0x6f.
  40771. *
  40772. * @param {Integer} char1 The second byte
  40773. * @return {Boolean} Whether the byte is a color PAC
  40774. */
  40775. Cea608Stream.prototype.isColorPAC = function (char1) {
  40776. return char1 >= 0x40 && char1 <= 0x4f || char1 >= 0x60 && char1 <= 0x7f;
  40777. };
  40778. /**
  40779. * Detects if a single byte is in the range of a normal character
  40780. *
  40781. * Normal text bytes are in the range 0x20 to 0x7f.
  40782. *
  40783. * @param {Integer} char The byte
  40784. * @return {Boolean} Whether the byte is a normal character
  40785. */
  40786. Cea608Stream.prototype.isNormalChar = function (_char2) {
  40787. return _char2 >= 0x20 && _char2 <= 0x7f;
  40788. };
  40789. /**
  40790. * Configures roll-up
  40791. *
  40792. * @param {Integer} pts Current PTS
  40793. * @param {Integer} newBaseRow Used by PACs to slide the current window to
  40794. * a new position
  40795. */
  40796. Cea608Stream.prototype.setRollUp = function (pts, newBaseRow) {
  40797. // Reset the base row to the bottom row when switching modes
  40798. if (this.mode_ !== 'rollUp') {
  40799. this.row_ = BOTTOM_ROW;
  40800. this.mode_ = 'rollUp'; // Spec says to wipe memories when switching to roll-up
  40801. this.flushDisplayed(pts);
  40802. this.nonDisplayed_ = createDisplayBuffer();
  40803. this.displayed_ = createDisplayBuffer();
  40804. }
  40805. if (newBaseRow !== undefined && newBaseRow !== this.row_) {
  40806. // move currently displayed captions (up or down) to the new base row
  40807. for (var i = 0; i < this.rollUpRows_; i++) {
  40808. this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
  40809. this.displayed_[this.row_ - i] = '';
  40810. }
  40811. }
  40812. if (newBaseRow === undefined) {
  40813. newBaseRow = this.row_;
  40814. }
  40815. this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
  40816. }; // Adds the opening HTML tag for the passed character to the caption text,
  40817. // and keeps track of it for later closing
  40818. Cea608Stream.prototype.addFormatting = function (pts, format) {
  40819. this.formatting_ = this.formatting_.concat(format);
  40820. var text = format.reduce(function (text, format) {
  40821. return text + '<' + format + '>';
  40822. }, '');
  40823. this[this.mode_](pts, text);
  40824. }; // Adds HTML closing tags for current formatting to caption text and
  40825. // clears remembered formatting
  40826. Cea608Stream.prototype.clearFormatting = function (pts) {
  40827. if (!this.formatting_.length) {
  40828. return;
  40829. }
  40830. var text = this.formatting_.reverse().reduce(function (text, format) {
  40831. return text + '</' + format + '>';
  40832. }, '');
  40833. this.formatting_ = [];
  40834. this[this.mode_](pts, text);
  40835. }; // Mode Implementations
  40836. Cea608Stream.prototype.popOn = function (pts, text) {
  40837. var baseRow = this.nonDisplayed_[this.row_]; // buffer characters
  40838. baseRow += text;
  40839. this.nonDisplayed_[this.row_] = baseRow;
  40840. };
  40841. Cea608Stream.prototype.rollUp = function (pts, text) {
  40842. var baseRow = this.displayed_[this.row_];
  40843. baseRow += text;
  40844. this.displayed_[this.row_] = baseRow;
  40845. };
  40846. Cea608Stream.prototype.shiftRowsUp_ = function () {
  40847. var i; // clear out inactive rows
  40848. for (i = 0; i < this.topRow_; i++) {
  40849. this.displayed_[i] = '';
  40850. }
  40851. for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
  40852. this.displayed_[i] = '';
  40853. } // shift displayed rows up
  40854. for (i = this.topRow_; i < this.row_; i++) {
  40855. this.displayed_[i] = this.displayed_[i + 1];
  40856. } // clear out the bottom row
  40857. this.displayed_[this.row_] = '';
  40858. };
  40859. Cea608Stream.prototype.paintOn = function (pts, text) {
  40860. var baseRow = this.displayed_[this.row_];
  40861. baseRow += text;
  40862. this.displayed_[this.row_] = baseRow;
  40863. }; // exports
  40864. var captionStream = {
  40865. CaptionStream: CaptionStream$1,
  40866. Cea608Stream: Cea608Stream,
  40867. Cea708Stream: Cea708Stream
  40868. };
  40869. /**
  40870. * mux.js
  40871. *
  40872. * Copyright (c) Brightcove
  40873. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  40874. */
  40875. var streamTypes = {
  40876. H264_STREAM_TYPE: 0x1B,
  40877. ADTS_STREAM_TYPE: 0x0F,
  40878. METADATA_STREAM_TYPE: 0x15
  40879. };
  40880. var MAX_TS = 8589934592;
  40881. var RO_THRESH = 4294967296;
  40882. var TYPE_SHARED = 'shared';
  40883. var handleRollover$1 = function handleRollover(value, reference) {
  40884. var direction = 1;
  40885. if (value > reference) {
  40886. // If the current timestamp value is greater than our reference timestamp and we detect a
  40887. // timestamp rollover, this means the roll over is happening in the opposite direction.
  40888. // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
  40889. // point will be set to a small number, e.g. 1. The user then seeks backwards over the
  40890. // rollover point. In loading this segment, the timestamp values will be very large,
  40891. // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
  40892. // the time stamp to be `value - 2^33`.
  40893. direction = -1;
  40894. } // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
  40895. // cause an incorrect adjustment.
  40896. while (Math.abs(reference - value) > RO_THRESH) {
  40897. value += direction * MAX_TS;
  40898. }
  40899. return value;
  40900. };
  40901. var TimestampRolloverStream$1 = function TimestampRolloverStream(type) {
  40902. var lastDTS, referenceDTS;
  40903. TimestampRolloverStream.prototype.init.call(this); // The "shared" type is used in cases where a stream will contain muxed
  40904. // video and audio. We could use `undefined` here, but having a string
  40905. // makes debugging a little clearer.
  40906. this.type_ = type || TYPE_SHARED;
  40907. this.push = function (data) {
  40908. // Any "shared" rollover streams will accept _all_ data. Otherwise,
  40909. // streams will only accept data that matches their type.
  40910. if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
  40911. return;
  40912. }
  40913. if (referenceDTS === undefined) {
  40914. referenceDTS = data.dts;
  40915. }
  40916. data.dts = handleRollover$1(data.dts, referenceDTS);
  40917. data.pts = handleRollover$1(data.pts, referenceDTS);
  40918. lastDTS = data.dts;
  40919. this.trigger('data', data);
  40920. };
  40921. this.flush = function () {
  40922. referenceDTS = lastDTS;
  40923. this.trigger('done');
  40924. };
  40925. this.endTimeline = function () {
  40926. this.flush();
  40927. this.trigger('endedtimeline');
  40928. };
  40929. this.discontinuity = function () {
  40930. referenceDTS = void 0;
  40931. lastDTS = void 0;
  40932. };
  40933. this.reset = function () {
  40934. this.discontinuity();
  40935. this.trigger('reset');
  40936. };
  40937. };
  40938. TimestampRolloverStream$1.prototype = new stream();
  40939. var timestampRolloverStream = {
  40940. TimestampRolloverStream: TimestampRolloverStream$1,
  40941. handleRollover: handleRollover$1
  40942. };
  40943. var percentEncode$1 = function percentEncode(bytes, start, end) {
  40944. var i,
  40945. result = '';
  40946. for (i = start; i < end; i++) {
  40947. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  40948. }
  40949. return result;
  40950. },
  40951. // return the string representation of the specified byte range,
  40952. // interpreted as UTf-8.
  40953. parseUtf8 = function parseUtf8(bytes, start, end) {
  40954. return decodeURIComponent(percentEncode$1(bytes, start, end));
  40955. },
  40956. // return the string representation of the specified byte range,
  40957. // interpreted as ISO-8859-1.
  40958. parseIso88591$1 = function parseIso88591(bytes, start, end) {
  40959. return unescape(percentEncode$1(bytes, start, end)); // jshint ignore:line
  40960. },
  40961. parseSyncSafeInteger$1 = function parseSyncSafeInteger(data) {
  40962. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  40963. },
  40964. tagParsers = {
  40965. TXXX: function TXXX(tag) {
  40966. var i;
  40967. if (tag.data[0] !== 3) {
  40968. // ignore frames with unrecognized character encodings
  40969. return;
  40970. }
  40971. for (i = 1; i < tag.data.length; i++) {
  40972. if (tag.data[i] === 0) {
  40973. // parse the text fields
  40974. tag.description = parseUtf8(tag.data, 1, i); // do not include the null terminator in the tag value
  40975. tag.value = parseUtf8(tag.data, i + 1, tag.data.length).replace(/\0*$/, '');
  40976. break;
  40977. }
  40978. }
  40979. tag.data = tag.value;
  40980. },
  40981. WXXX: function WXXX(tag) {
  40982. var i;
  40983. if (tag.data[0] !== 3) {
  40984. // ignore frames with unrecognized character encodings
  40985. return;
  40986. }
  40987. for (i = 1; i < tag.data.length; i++) {
  40988. if (tag.data[i] === 0) {
  40989. // parse the description and URL fields
  40990. tag.description = parseUtf8(tag.data, 1, i);
  40991. tag.url = parseUtf8(tag.data, i + 1, tag.data.length);
  40992. break;
  40993. }
  40994. }
  40995. },
  40996. PRIV: function PRIV(tag) {
  40997. var i;
  40998. for (i = 0; i < tag.data.length; i++) {
  40999. if (tag.data[i] === 0) {
  41000. // parse the description and URL fields
  41001. tag.owner = parseIso88591$1(tag.data, 0, i);
  41002. break;
  41003. }
  41004. }
  41005. tag.privateData = tag.data.subarray(i + 1);
  41006. tag.data = tag.privateData;
  41007. }
  41008. },
  41009. _MetadataStream;
  41010. _MetadataStream = function MetadataStream(options) {
  41011. var settings = {
  41012. // the bytes of the program-level descriptor field in MP2T
  41013. // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
  41014. // program element descriptors"
  41015. descriptor: options && options.descriptor
  41016. },
  41017. // the total size in bytes of the ID3 tag being parsed
  41018. tagSize = 0,
  41019. // tag data that is not complete enough to be parsed
  41020. buffer = [],
  41021. // the total number of bytes currently in the buffer
  41022. bufferSize = 0,
  41023. i;
  41024. _MetadataStream.prototype.init.call(this); // calculate the text track in-band metadata track dispatch type
  41025. // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
  41026. this.dispatchType = streamTypes.METADATA_STREAM_TYPE.toString(16);
  41027. if (settings.descriptor) {
  41028. for (i = 0; i < settings.descriptor.length; i++) {
  41029. this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
  41030. }
  41031. }
  41032. this.push = function (chunk) {
  41033. var tag, frameStart, frameSize, frame, i, frameHeader;
  41034. if (chunk.type !== 'timed-metadata') {
  41035. return;
  41036. } // if data_alignment_indicator is set in the PES header,
  41037. // we must have the start of a new ID3 tag. Assume anything
  41038. // remaining in the buffer was malformed and throw it out
  41039. if (chunk.dataAlignmentIndicator) {
  41040. bufferSize = 0;
  41041. buffer.length = 0;
  41042. } // ignore events that don't look like ID3 data
  41043. if (buffer.length === 0 && (chunk.data.length < 10 || chunk.data[0] !== 'I'.charCodeAt(0) || chunk.data[1] !== 'D'.charCodeAt(0) || chunk.data[2] !== '3'.charCodeAt(0))) {
  41044. this.trigger('log', {
  41045. level: 'warn',
  41046. message: 'Skipping unrecognized metadata packet'
  41047. });
  41048. return;
  41049. } // add this chunk to the data we've collected so far
  41050. buffer.push(chunk);
  41051. bufferSize += chunk.data.byteLength; // grab the size of the entire frame from the ID3 header
  41052. if (buffer.length === 1) {
  41053. // the frame size is transmitted as a 28-bit integer in the
  41054. // last four bytes of the ID3 header.
  41055. // The most significant bit of each byte is dropped and the
  41056. // results concatenated to recover the actual value.
  41057. tagSize = parseSyncSafeInteger$1(chunk.data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  41058. // convenient for our comparisons to include it
  41059. tagSize += 10;
  41060. } // if the entire frame has not arrived, wait for more data
  41061. if (bufferSize < tagSize) {
  41062. return;
  41063. } // collect the entire frame so it can be parsed
  41064. tag = {
  41065. data: new Uint8Array(tagSize),
  41066. frames: [],
  41067. pts: buffer[0].pts,
  41068. dts: buffer[0].dts
  41069. };
  41070. for (i = 0; i < tagSize;) {
  41071. tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
  41072. i += buffer[0].data.byteLength;
  41073. bufferSize -= buffer[0].data.byteLength;
  41074. buffer.shift();
  41075. } // find the start of the first frame and the end of the tag
  41076. frameStart = 10;
  41077. if (tag.data[5] & 0x40) {
  41078. // advance the frame start past the extended header
  41079. frameStart += 4; // header size field
  41080. frameStart += parseSyncSafeInteger$1(tag.data.subarray(10, 14)); // clip any padding off the end
  41081. tagSize -= parseSyncSafeInteger$1(tag.data.subarray(16, 20));
  41082. } // parse one or more ID3 frames
  41083. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  41084. do {
  41085. // determine the number of bytes in this frame
  41086. frameSize = parseSyncSafeInteger$1(tag.data.subarray(frameStart + 4, frameStart + 8));
  41087. if (frameSize < 1) {
  41088. this.trigger('log', {
  41089. level: 'warn',
  41090. message: 'Malformed ID3 frame encountered. Skipping metadata parsing.'
  41091. });
  41092. return;
  41093. }
  41094. frameHeader = String.fromCharCode(tag.data[frameStart], tag.data[frameStart + 1], tag.data[frameStart + 2], tag.data[frameStart + 3]);
  41095. frame = {
  41096. id: frameHeader,
  41097. data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
  41098. };
  41099. frame.key = frame.id;
  41100. if (tagParsers[frame.id]) {
  41101. tagParsers[frame.id](frame); // handle the special PRIV frame used to indicate the start
  41102. // time for raw AAC data
  41103. if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
  41104. var d = frame.data,
  41105. size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  41106. size *= 4;
  41107. size += d[7] & 0x03;
  41108. frame.timeStamp = size; // in raw AAC, all subsequent data will be timestamped based
  41109. // on the value of this frame
  41110. // we couldn't have known the appropriate pts and dts before
  41111. // parsing this ID3 tag so set those values now
  41112. if (tag.pts === undefined && tag.dts === undefined) {
  41113. tag.pts = frame.timeStamp;
  41114. tag.dts = frame.timeStamp;
  41115. }
  41116. this.trigger('timestamp', frame);
  41117. }
  41118. }
  41119. tag.frames.push(frame);
  41120. frameStart += 10; // advance past the frame header
  41121. frameStart += frameSize; // advance past the frame body
  41122. } while (frameStart < tagSize);
  41123. this.trigger('data', tag);
  41124. };
  41125. };
  41126. _MetadataStream.prototype = new stream();
  41127. var metadataStream = _MetadataStream;
  41128. var TimestampRolloverStream = timestampRolloverStream.TimestampRolloverStream; // object types
  41129. var _TransportPacketStream, _TransportParseStream, _ElementaryStream; // constants
  41130. var MP2T_PACKET_LENGTH$1 = 188,
  41131. // bytes
  41132. SYNC_BYTE$1 = 0x47;
  41133. /**
  41134. * Splits an incoming stream of binary data into MPEG-2 Transport
  41135. * Stream packets.
  41136. */
  41137. _TransportPacketStream = function TransportPacketStream() {
  41138. var buffer = new Uint8Array(MP2T_PACKET_LENGTH$1),
  41139. bytesInBuffer = 0;
  41140. _TransportPacketStream.prototype.init.call(this); // Deliver new bytes to the stream.
  41141. /**
  41142. * Split a stream of data into M2TS packets
  41143. **/
  41144. this.push = function (bytes) {
  41145. var startIndex = 0,
  41146. endIndex = MP2T_PACKET_LENGTH$1,
  41147. everything; // If there are bytes remaining from the last segment, prepend them to the
  41148. // bytes that were pushed in
  41149. if (bytesInBuffer) {
  41150. everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
  41151. everything.set(buffer.subarray(0, bytesInBuffer));
  41152. everything.set(bytes, bytesInBuffer);
  41153. bytesInBuffer = 0;
  41154. } else {
  41155. everything = bytes;
  41156. } // While we have enough data for a packet
  41157. while (endIndex < everything.byteLength) {
  41158. // Look for a pair of start and end sync bytes in the data..
  41159. if (everything[startIndex] === SYNC_BYTE$1 && everything[endIndex] === SYNC_BYTE$1) {
  41160. // We found a packet so emit it and jump one whole packet forward in
  41161. // the stream
  41162. this.trigger('data', everything.subarray(startIndex, endIndex));
  41163. startIndex += MP2T_PACKET_LENGTH$1;
  41164. endIndex += MP2T_PACKET_LENGTH$1;
  41165. continue;
  41166. } // If we get here, we have somehow become de-synchronized and we need to step
  41167. // forward one byte at a time until we find a pair of sync bytes that denote
  41168. // a packet
  41169. startIndex++;
  41170. endIndex++;
  41171. } // If there was some data left over at the end of the segment that couldn't
  41172. // possibly be a whole packet, keep it because it might be the start of a packet
  41173. // that continues in the next segment
  41174. if (startIndex < everything.byteLength) {
  41175. buffer.set(everything.subarray(startIndex), 0);
  41176. bytesInBuffer = everything.byteLength - startIndex;
  41177. }
  41178. };
  41179. /**
  41180. * Passes identified M2TS packets to the TransportParseStream to be parsed
  41181. **/
  41182. this.flush = function () {
  41183. // If the buffer contains a whole packet when we are being flushed, emit it
  41184. // and empty the buffer. Otherwise hold onto the data because it may be
  41185. // important for decoding the next segment
  41186. if (bytesInBuffer === MP2T_PACKET_LENGTH$1 && buffer[0] === SYNC_BYTE$1) {
  41187. this.trigger('data', buffer);
  41188. bytesInBuffer = 0;
  41189. }
  41190. this.trigger('done');
  41191. };
  41192. this.endTimeline = function () {
  41193. this.flush();
  41194. this.trigger('endedtimeline');
  41195. };
  41196. this.reset = function () {
  41197. bytesInBuffer = 0;
  41198. this.trigger('reset');
  41199. };
  41200. };
  41201. _TransportPacketStream.prototype = new stream();
  41202. /**
  41203. * Accepts an MP2T TransportPacketStream and emits data events with parsed
  41204. * forms of the individual transport stream packets.
  41205. */
  41206. _TransportParseStream = function TransportParseStream() {
  41207. var parsePsi, parsePat, parsePmt, self;
  41208. _TransportParseStream.prototype.init.call(this);
  41209. self = this;
  41210. this.packetsWaitingForPmt = [];
  41211. this.programMapTable = undefined;
  41212. parsePsi = function parsePsi(payload, psi) {
  41213. var offset = 0; // PSI packets may be split into multiple sections and those
  41214. // sections may be split into multiple packets. If a PSI
  41215. // section starts in this packet, the payload_unit_start_indicator
  41216. // will be true and the first byte of the payload will indicate
  41217. // the offset from the current position to the start of the
  41218. // section.
  41219. if (psi.payloadUnitStartIndicator) {
  41220. offset += payload[offset] + 1;
  41221. }
  41222. if (psi.type === 'pat') {
  41223. parsePat(payload.subarray(offset), psi);
  41224. } else {
  41225. parsePmt(payload.subarray(offset), psi);
  41226. }
  41227. };
  41228. parsePat = function parsePat(payload, pat) {
  41229. pat.section_number = payload[7]; // eslint-disable-line camelcase
  41230. pat.last_section_number = payload[8]; // eslint-disable-line camelcase
  41231. // skip the PSI header and parse the first PMT entry
  41232. self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
  41233. pat.pmtPid = self.pmtPid;
  41234. };
  41235. /**
  41236. * Parse out the relevant fields of a Program Map Table (PMT).
  41237. * @param payload {Uint8Array} the PMT-specific portion of an MP2T
  41238. * packet. The first byte in this array should be the table_id
  41239. * field.
  41240. * @param pmt {object} the object that should be decorated with
  41241. * fields parsed from the PMT.
  41242. */
  41243. parsePmt = function parsePmt(payload, pmt) {
  41244. var sectionLength, tableEnd, programInfoLength, offset; // PMTs can be sent ahead of the time when they should actually
  41245. // take effect. We don't believe this should ever be the case
  41246. // for HLS but we'll ignore "forward" PMT declarations if we see
  41247. // them. Future PMT declarations have the current_next_indicator
  41248. // set to zero.
  41249. if (!(payload[5] & 0x01)) {
  41250. return;
  41251. } // overwrite any existing program map table
  41252. self.programMapTable = {
  41253. video: null,
  41254. audio: null,
  41255. 'timed-metadata': {}
  41256. }; // the mapping table ends at the end of the current section
  41257. sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
  41258. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  41259. // long the program info descriptors are
  41260. programInfoLength = (payload[10] & 0x0f) << 8 | payload[11]; // advance the offset to the first entry in the mapping table
  41261. offset = 12 + programInfoLength;
  41262. while (offset < tableEnd) {
  41263. var streamType = payload[offset];
  41264. var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]; // only map a single elementary_pid for audio and video stream types
  41265. // TODO: should this be done for metadata too? for now maintain behavior of
  41266. // multiple metadata streams
  41267. if (streamType === streamTypes.H264_STREAM_TYPE && self.programMapTable.video === null) {
  41268. self.programMapTable.video = pid;
  41269. } else if (streamType === streamTypes.ADTS_STREAM_TYPE && self.programMapTable.audio === null) {
  41270. self.programMapTable.audio = pid;
  41271. } else if (streamType === streamTypes.METADATA_STREAM_TYPE) {
  41272. // map pid to stream type for metadata streams
  41273. self.programMapTable['timed-metadata'][pid] = streamType;
  41274. } // move to the next table entry
  41275. // skip past the elementary stream descriptors, if present
  41276. offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
  41277. } // record the map on the packet as well
  41278. pmt.programMapTable = self.programMapTable;
  41279. };
  41280. /**
  41281. * Deliver a new MP2T packet to the next stream in the pipeline.
  41282. */
  41283. this.push = function (packet) {
  41284. var result = {},
  41285. offset = 4;
  41286. result.payloadUnitStartIndicator = !!(packet[1] & 0x40); // pid is a 13-bit field starting at the last bit of packet[1]
  41287. result.pid = packet[1] & 0x1f;
  41288. result.pid <<= 8;
  41289. result.pid |= packet[2]; // if an adaption field is present, its length is specified by the
  41290. // fifth byte of the TS packet header. The adaptation field is
  41291. // used to add stuffing to PES packets that don't fill a complete
  41292. // TS packet, and to specify some forms of timing and control data
  41293. // that we do not currently use.
  41294. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  41295. offset += packet[offset] + 1;
  41296. } // parse the rest of the packet based on the type
  41297. if (result.pid === 0) {
  41298. result.type = 'pat';
  41299. parsePsi(packet.subarray(offset), result);
  41300. this.trigger('data', result);
  41301. } else if (result.pid === this.pmtPid) {
  41302. result.type = 'pmt';
  41303. parsePsi(packet.subarray(offset), result);
  41304. this.trigger('data', result); // if there are any packets waiting for a PMT to be found, process them now
  41305. while (this.packetsWaitingForPmt.length) {
  41306. this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
  41307. }
  41308. } else if (this.programMapTable === undefined) {
  41309. // When we have not seen a PMT yet, defer further processing of
  41310. // PES packets until one has been parsed
  41311. this.packetsWaitingForPmt.push([packet, offset, result]);
  41312. } else {
  41313. this.processPes_(packet, offset, result);
  41314. }
  41315. };
  41316. this.processPes_ = function (packet, offset, result) {
  41317. // set the appropriate stream type
  41318. if (result.pid === this.programMapTable.video) {
  41319. result.streamType = streamTypes.H264_STREAM_TYPE;
  41320. } else if (result.pid === this.programMapTable.audio) {
  41321. result.streamType = streamTypes.ADTS_STREAM_TYPE;
  41322. } else {
  41323. // if not video or audio, it is timed-metadata or unknown
  41324. // if unknown, streamType will be undefined
  41325. result.streamType = this.programMapTable['timed-metadata'][result.pid];
  41326. }
  41327. result.type = 'pes';
  41328. result.data = packet.subarray(offset);
  41329. this.trigger('data', result);
  41330. };
  41331. };
  41332. _TransportParseStream.prototype = new stream();
  41333. _TransportParseStream.STREAM_TYPES = {
  41334. h264: 0x1b,
  41335. adts: 0x0f
  41336. };
  41337. /**
  41338. * Reconsistutes program elementary stream (PES) packets from parsed
  41339. * transport stream packets. That is, if you pipe an
  41340. * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
  41341. * events will be events which capture the bytes for individual PES
  41342. * packets plus relevant metadata that has been extracted from the
  41343. * container.
  41344. */
  41345. _ElementaryStream = function ElementaryStream() {
  41346. var self = this,
  41347. segmentHadPmt = false,
  41348. // PES packet fragments
  41349. video = {
  41350. data: [],
  41351. size: 0
  41352. },
  41353. audio = {
  41354. data: [],
  41355. size: 0
  41356. },
  41357. timedMetadata = {
  41358. data: [],
  41359. size: 0
  41360. },
  41361. programMapTable,
  41362. parsePes = function parsePes(payload, pes) {
  41363. var ptsDtsFlags;
  41364. var startPrefix = payload[0] << 16 | payload[1] << 8 | payload[2]; // default to an empty array
  41365. pes.data = new Uint8Array(); // In certain live streams, the start of a TS fragment has ts packets
  41366. // that are frame data that is continuing from the previous fragment. This
  41367. // is to check that the pes data is the start of a new pes payload
  41368. if (startPrefix !== 1) {
  41369. return;
  41370. } // get the packet length, this will be 0 for video
  41371. pes.packetLength = 6 + (payload[4] << 8 | payload[5]); // find out if this packets starts a new keyframe
  41372. pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0; // PES packets may be annotated with a PTS value, or a PTS value
  41373. // and a DTS value. Determine what combination of values is
  41374. // available to work with.
  41375. ptsDtsFlags = payload[7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  41376. // performs all bitwise operations on 32-bit integers but javascript
  41377. // supports a much greater range (52-bits) of integer using standard
  41378. // mathematical operations.
  41379. // We construct a 31-bit value using bitwise operators over the 31
  41380. // most significant bits and then multiply by 4 (equal to a left-shift
  41381. // of 2) before we add the final 2 least significant bits of the
  41382. // timestamp (equal to an OR.)
  41383. if (ptsDtsFlags & 0xC0) {
  41384. // the PTS and DTS are not written out directly. For information
  41385. // on how they are encoded, see
  41386. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  41387. pes.pts = (payload[9] & 0x0E) << 27 | (payload[10] & 0xFF) << 20 | (payload[11] & 0xFE) << 12 | (payload[12] & 0xFF) << 5 | (payload[13] & 0xFE) >>> 3;
  41388. pes.pts *= 4; // Left shift by 2
  41389. pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
  41390. pes.dts = pes.pts;
  41391. if (ptsDtsFlags & 0x40) {
  41392. pes.dts = (payload[14] & 0x0E) << 27 | (payload[15] & 0xFF) << 20 | (payload[16] & 0xFE) << 12 | (payload[17] & 0xFF) << 5 | (payload[18] & 0xFE) >>> 3;
  41393. pes.dts *= 4; // Left shift by 2
  41394. pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
  41395. }
  41396. } // the data section starts immediately after the PES header.
  41397. // pes_header_data_length specifies the number of header bytes
  41398. // that follow the last byte of the field.
  41399. pes.data = payload.subarray(9 + payload[8]);
  41400. },
  41401. /**
  41402. * Pass completely parsed PES packets to the next stream in the pipeline
  41403. **/
  41404. flushStream = function flushStream(stream, type, forceFlush) {
  41405. var packetData = new Uint8Array(stream.size),
  41406. event = {
  41407. type: type
  41408. },
  41409. i = 0,
  41410. offset = 0,
  41411. packetFlushable = false,
  41412. fragment; // do nothing if there is not enough buffered data for a complete
  41413. // PES header
  41414. if (!stream.data.length || stream.size < 9) {
  41415. return;
  41416. }
  41417. event.trackId = stream.data[0].pid; // reassemble the packet
  41418. for (i = 0; i < stream.data.length; i++) {
  41419. fragment = stream.data[i];
  41420. packetData.set(fragment.data, offset);
  41421. offset += fragment.data.byteLength;
  41422. } // parse assembled packet's PES header
  41423. parsePes(packetData, event); // non-video PES packets MUST have a non-zero PES_packet_length
  41424. // check that there is enough stream data to fill the packet
  41425. packetFlushable = type === 'video' || event.packetLength <= stream.size; // flush pending packets if the conditions are right
  41426. if (forceFlush || packetFlushable) {
  41427. stream.size = 0;
  41428. stream.data.length = 0;
  41429. } // only emit packets that are complete. this is to avoid assembling
  41430. // incomplete PES packets due to poor segmentation
  41431. if (packetFlushable) {
  41432. self.trigger('data', event);
  41433. }
  41434. };
  41435. _ElementaryStream.prototype.init.call(this);
  41436. /**
  41437. * Identifies M2TS packet types and parses PES packets using metadata
  41438. * parsed from the PMT
  41439. **/
  41440. this.push = function (data) {
  41441. ({
  41442. pat: function pat() {// we have to wait for the PMT to arrive as well before we
  41443. // have any meaningful metadata
  41444. },
  41445. pes: function pes() {
  41446. var stream, streamType;
  41447. switch (data.streamType) {
  41448. case streamTypes.H264_STREAM_TYPE:
  41449. stream = video;
  41450. streamType = 'video';
  41451. break;
  41452. case streamTypes.ADTS_STREAM_TYPE:
  41453. stream = audio;
  41454. streamType = 'audio';
  41455. break;
  41456. case streamTypes.METADATA_STREAM_TYPE:
  41457. stream = timedMetadata;
  41458. streamType = 'timed-metadata';
  41459. break;
  41460. default:
  41461. // ignore unknown stream types
  41462. return;
  41463. } // if a new packet is starting, we can flush the completed
  41464. // packet
  41465. if (data.payloadUnitStartIndicator) {
  41466. flushStream(stream, streamType, true);
  41467. } // buffer this fragment until we are sure we've received the
  41468. // complete payload
  41469. stream.data.push(data);
  41470. stream.size += data.data.byteLength;
  41471. },
  41472. pmt: function pmt() {
  41473. var event = {
  41474. type: 'metadata',
  41475. tracks: []
  41476. };
  41477. programMapTable = data.programMapTable; // translate audio and video streams to tracks
  41478. if (programMapTable.video !== null) {
  41479. event.tracks.push({
  41480. timelineStartInfo: {
  41481. baseMediaDecodeTime: 0
  41482. },
  41483. id: +programMapTable.video,
  41484. codec: 'avc',
  41485. type: 'video'
  41486. });
  41487. }
  41488. if (programMapTable.audio !== null) {
  41489. event.tracks.push({
  41490. timelineStartInfo: {
  41491. baseMediaDecodeTime: 0
  41492. },
  41493. id: +programMapTable.audio,
  41494. codec: 'adts',
  41495. type: 'audio'
  41496. });
  41497. }
  41498. segmentHadPmt = true;
  41499. self.trigger('data', event);
  41500. }
  41501. })[data.type]();
  41502. };
  41503. this.reset = function () {
  41504. video.size = 0;
  41505. video.data.length = 0;
  41506. audio.size = 0;
  41507. audio.data.length = 0;
  41508. this.trigger('reset');
  41509. };
  41510. /**
  41511. * Flush any remaining input. Video PES packets may be of variable
  41512. * length. Normally, the start of a new video packet can trigger the
  41513. * finalization of the previous packet. That is not possible if no
  41514. * more video is forthcoming, however. In that case, some other
  41515. * mechanism (like the end of the file) has to be employed. When it is
  41516. * clear that no additional data is forthcoming, calling this method
  41517. * will flush the buffered packets.
  41518. */
  41519. this.flushStreams_ = function () {
  41520. // !!THIS ORDER IS IMPORTANT!!
  41521. // video first then audio
  41522. flushStream(video, 'video');
  41523. flushStream(audio, 'audio');
  41524. flushStream(timedMetadata, 'timed-metadata');
  41525. };
  41526. this.flush = function () {
  41527. // if on flush we haven't had a pmt emitted
  41528. // and we have a pmt to emit. emit the pmt
  41529. // so that we trigger a trackinfo downstream.
  41530. if (!segmentHadPmt && programMapTable) {
  41531. var pmt = {
  41532. type: 'metadata',
  41533. tracks: []
  41534. }; // translate audio and video streams to tracks
  41535. if (programMapTable.video !== null) {
  41536. pmt.tracks.push({
  41537. timelineStartInfo: {
  41538. baseMediaDecodeTime: 0
  41539. },
  41540. id: +programMapTable.video,
  41541. codec: 'avc',
  41542. type: 'video'
  41543. });
  41544. }
  41545. if (programMapTable.audio !== null) {
  41546. pmt.tracks.push({
  41547. timelineStartInfo: {
  41548. baseMediaDecodeTime: 0
  41549. },
  41550. id: +programMapTable.audio,
  41551. codec: 'adts',
  41552. type: 'audio'
  41553. });
  41554. }
  41555. self.trigger('data', pmt);
  41556. }
  41557. segmentHadPmt = false;
  41558. this.flushStreams_();
  41559. this.trigger('done');
  41560. };
  41561. };
  41562. _ElementaryStream.prototype = new stream();
  41563. var m2ts = {
  41564. PAT_PID: 0x0000,
  41565. MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH$1,
  41566. TransportPacketStream: _TransportPacketStream,
  41567. TransportParseStream: _TransportParseStream,
  41568. ElementaryStream: _ElementaryStream,
  41569. TimestampRolloverStream: TimestampRolloverStream,
  41570. CaptionStream: captionStream.CaptionStream,
  41571. Cea608Stream: captionStream.Cea608Stream,
  41572. Cea708Stream: captionStream.Cea708Stream,
  41573. MetadataStream: metadataStream
  41574. };
  41575. for (var type in streamTypes) {
  41576. if (streamTypes.hasOwnProperty(type)) {
  41577. m2ts[type] = streamTypes[type];
  41578. }
  41579. }
  41580. var m2ts_1 = m2ts;
  41581. var ONE_SECOND_IN_TS$2 = clock.ONE_SECOND_IN_TS;
  41582. var _AdtsStream;
  41583. var ADTS_SAMPLING_FREQUENCIES$1 = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  41584. /*
  41585. * Accepts a ElementaryStream and emits data events with parsed
  41586. * AAC Audio Frames of the individual packets. Input audio in ADTS
  41587. * format is unpacked and re-emitted as AAC frames.
  41588. *
  41589. * @see http://wiki.multimedia.cx/index.php?title=ADTS
  41590. * @see http://wiki.multimedia.cx/?title=Understanding_AAC
  41591. */
  41592. _AdtsStream = function AdtsStream(handlePartialSegments) {
  41593. var buffer,
  41594. frameNum = 0;
  41595. _AdtsStream.prototype.init.call(this);
  41596. this.skipWarn_ = function (start, end) {
  41597. this.trigger('log', {
  41598. level: 'warn',
  41599. message: "adts skiping bytes " + start + " to " + end + " in frame " + frameNum + " outside syncword"
  41600. });
  41601. };
  41602. this.push = function (packet) {
  41603. var i = 0,
  41604. frameLength,
  41605. protectionSkipBytes,
  41606. oldBuffer,
  41607. sampleCount,
  41608. adtsFrameDuration;
  41609. if (!handlePartialSegments) {
  41610. frameNum = 0;
  41611. }
  41612. if (packet.type !== 'audio') {
  41613. // ignore non-audio data
  41614. return;
  41615. } // Prepend any data in the buffer to the input data so that we can parse
  41616. // aac frames the cross a PES packet boundary
  41617. if (buffer && buffer.length) {
  41618. oldBuffer = buffer;
  41619. buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
  41620. buffer.set(oldBuffer);
  41621. buffer.set(packet.data, oldBuffer.byteLength);
  41622. } else {
  41623. buffer = packet.data;
  41624. } // unpack any ADTS frames which have been fully received
  41625. // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
  41626. var skip; // We use i + 7 here because we want to be able to parse the entire header.
  41627. // If we don't have enough bytes to do that, then we definitely won't have a full frame.
  41628. while (i + 7 < buffer.length) {
  41629. // Look for the start of an ADTS header..
  41630. if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {
  41631. if (typeof skip !== 'number') {
  41632. skip = i;
  41633. } // If a valid header was not found, jump one forward and attempt to
  41634. // find a valid ADTS header starting at the next byte
  41635. i++;
  41636. continue;
  41637. }
  41638. if (typeof skip === 'number') {
  41639. this.skipWarn_(skip, i);
  41640. skip = null;
  41641. } // The protection skip bit tells us if we have 2 bytes of CRC data at the
  41642. // end of the ADTS header
  41643. protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2; // Frame length is a 13 bit integer starting 16 bits from the
  41644. // end of the sync sequence
  41645. // NOTE: frame length includes the size of the header
  41646. frameLength = (buffer[i + 3] & 0x03) << 11 | buffer[i + 4] << 3 | (buffer[i + 5] & 0xe0) >> 5;
  41647. sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
  41648. adtsFrameDuration = sampleCount * ONE_SECOND_IN_TS$2 / ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2]; // If we don't have enough data to actually finish this ADTS frame,
  41649. // then we have to wait for more data
  41650. if (buffer.byteLength - i < frameLength) {
  41651. break;
  41652. } // Otherwise, deliver the complete AAC frame
  41653. this.trigger('data', {
  41654. pts: packet.pts + frameNum * adtsFrameDuration,
  41655. dts: packet.dts + frameNum * adtsFrameDuration,
  41656. sampleCount: sampleCount,
  41657. audioobjecttype: (buffer[i + 2] >>> 6 & 0x03) + 1,
  41658. channelcount: (buffer[i + 2] & 1) << 2 | (buffer[i + 3] & 0xc0) >>> 6,
  41659. samplerate: ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2],
  41660. samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
  41661. // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
  41662. samplesize: 16,
  41663. // data is the frame without it's header
  41664. data: buffer.subarray(i + 7 + protectionSkipBytes, i + frameLength)
  41665. });
  41666. frameNum++;
  41667. i += frameLength;
  41668. }
  41669. if (typeof skip === 'number') {
  41670. this.skipWarn_(skip, i);
  41671. skip = null;
  41672. } // remove processed bytes from the buffer.
  41673. buffer = buffer.subarray(i);
  41674. };
  41675. this.flush = function () {
  41676. frameNum = 0;
  41677. this.trigger('done');
  41678. };
  41679. this.reset = function () {
  41680. buffer = void 0;
  41681. this.trigger('reset');
  41682. };
  41683. this.endTimeline = function () {
  41684. buffer = void 0;
  41685. this.trigger('endedtimeline');
  41686. };
  41687. };
  41688. _AdtsStream.prototype = new stream();
  41689. var adts = _AdtsStream;
  41690. /**
  41691. * mux.js
  41692. *
  41693. * Copyright (c) Brightcove
  41694. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  41695. */
  41696. var ExpGolomb;
  41697. /**
  41698. * Parser for exponential Golomb codes, a variable-bitwidth number encoding
  41699. * scheme used by h264.
  41700. */
  41701. ExpGolomb = function ExpGolomb(workingData) {
  41702. var // the number of bytes left to examine in workingData
  41703. workingBytesAvailable = workingData.byteLength,
  41704. // the current word being examined
  41705. workingWord = 0,
  41706. // :uint
  41707. // the number of bits left to examine in the current word
  41708. workingBitsAvailable = 0; // :uint;
  41709. // ():uint
  41710. this.length = function () {
  41711. return 8 * workingBytesAvailable;
  41712. }; // ():uint
  41713. this.bitsAvailable = function () {
  41714. return 8 * workingBytesAvailable + workingBitsAvailable;
  41715. }; // ():void
  41716. this.loadWord = function () {
  41717. var position = workingData.byteLength - workingBytesAvailable,
  41718. workingBytes = new Uint8Array(4),
  41719. availableBytes = Math.min(4, workingBytesAvailable);
  41720. if (availableBytes === 0) {
  41721. throw new Error('no bytes available');
  41722. }
  41723. workingBytes.set(workingData.subarray(position, position + availableBytes));
  41724. workingWord = new DataView(workingBytes.buffer).getUint32(0); // track the amount of workingData that has been processed
  41725. workingBitsAvailable = availableBytes * 8;
  41726. workingBytesAvailable -= availableBytes;
  41727. }; // (count:int):void
  41728. this.skipBits = function (count) {
  41729. var skipBytes; // :int
  41730. if (workingBitsAvailable > count) {
  41731. workingWord <<= count;
  41732. workingBitsAvailable -= count;
  41733. } else {
  41734. count -= workingBitsAvailable;
  41735. skipBytes = Math.floor(count / 8);
  41736. count -= skipBytes * 8;
  41737. workingBytesAvailable -= skipBytes;
  41738. this.loadWord();
  41739. workingWord <<= count;
  41740. workingBitsAvailable -= count;
  41741. }
  41742. }; // (size:int):uint
  41743. this.readBits = function (size) {
  41744. var bits = Math.min(workingBitsAvailable, size),
  41745. // :uint
  41746. valu = workingWord >>> 32 - bits; // :uint
  41747. // if size > 31, handle error
  41748. workingBitsAvailable -= bits;
  41749. if (workingBitsAvailable > 0) {
  41750. workingWord <<= bits;
  41751. } else if (workingBytesAvailable > 0) {
  41752. this.loadWord();
  41753. }
  41754. bits = size - bits;
  41755. if (bits > 0) {
  41756. return valu << bits | this.readBits(bits);
  41757. }
  41758. return valu;
  41759. }; // ():uint
  41760. this.skipLeadingZeros = function () {
  41761. var leadingZeroCount; // :uint
  41762. for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
  41763. if ((workingWord & 0x80000000 >>> leadingZeroCount) !== 0) {
  41764. // the first bit of working word is 1
  41765. workingWord <<= leadingZeroCount;
  41766. workingBitsAvailable -= leadingZeroCount;
  41767. return leadingZeroCount;
  41768. }
  41769. } // we exhausted workingWord and still have not found a 1
  41770. this.loadWord();
  41771. return leadingZeroCount + this.skipLeadingZeros();
  41772. }; // ():void
  41773. this.skipUnsignedExpGolomb = function () {
  41774. this.skipBits(1 + this.skipLeadingZeros());
  41775. }; // ():void
  41776. this.skipExpGolomb = function () {
  41777. this.skipBits(1 + this.skipLeadingZeros());
  41778. }; // ():uint
  41779. this.readUnsignedExpGolomb = function () {
  41780. var clz = this.skipLeadingZeros(); // :uint
  41781. return this.readBits(clz + 1) - 1;
  41782. }; // ():int
  41783. this.readExpGolomb = function () {
  41784. var valu = this.readUnsignedExpGolomb(); // :int
  41785. if (0x01 & valu) {
  41786. // the number is odd if the low order bit is set
  41787. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  41788. }
  41789. return -1 * (valu >>> 1); // divide by two then make it negative
  41790. }; // Some convenience functions
  41791. // :Boolean
  41792. this.readBoolean = function () {
  41793. return this.readBits(1) === 1;
  41794. }; // ():int
  41795. this.readUnsignedByte = function () {
  41796. return this.readBits(8);
  41797. };
  41798. this.loadWord();
  41799. };
  41800. var expGolomb = ExpGolomb;
  41801. var _H264Stream, _NalByteStream;
  41802. var PROFILES_WITH_OPTIONAL_SPS_DATA;
  41803. /**
  41804. * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
  41805. */
  41806. _NalByteStream = function NalByteStream() {
  41807. var syncPoint = 0,
  41808. i,
  41809. buffer;
  41810. _NalByteStream.prototype.init.call(this);
  41811. /*
  41812. * Scans a byte stream and triggers a data event with the NAL units found.
  41813. * @param {Object} data Event received from H264Stream
  41814. * @param {Uint8Array} data.data The h264 byte stream to be scanned
  41815. *
  41816. * @see H264Stream.push
  41817. */
  41818. this.push = function (data) {
  41819. var swapBuffer;
  41820. if (!buffer) {
  41821. buffer = data.data;
  41822. } else {
  41823. swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
  41824. swapBuffer.set(buffer);
  41825. swapBuffer.set(data.data, buffer.byteLength);
  41826. buffer = swapBuffer;
  41827. }
  41828. var len = buffer.byteLength; // Rec. ITU-T H.264, Annex B
  41829. // scan for NAL unit boundaries
  41830. // a match looks like this:
  41831. // 0 0 1 .. NAL .. 0 0 1
  41832. // ^ sync point ^ i
  41833. // or this:
  41834. // 0 0 1 .. NAL .. 0 0 0
  41835. // ^ sync point ^ i
  41836. // advance the sync point to a NAL start, if necessary
  41837. for (; syncPoint < len - 3; syncPoint++) {
  41838. if (buffer[syncPoint + 2] === 1) {
  41839. // the sync point is properly aligned
  41840. i = syncPoint + 5;
  41841. break;
  41842. }
  41843. }
  41844. while (i < len) {
  41845. // look at the current byte to determine if we've hit the end of
  41846. // a NAL unit boundary
  41847. switch (buffer[i]) {
  41848. case 0:
  41849. // skip past non-sync sequences
  41850. if (buffer[i - 1] !== 0) {
  41851. i += 2;
  41852. break;
  41853. } else if (buffer[i - 2] !== 0) {
  41854. i++;
  41855. break;
  41856. } // deliver the NAL unit if it isn't empty
  41857. if (syncPoint + 3 !== i - 2) {
  41858. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  41859. } // drop trailing zeroes
  41860. do {
  41861. i++;
  41862. } while (buffer[i] !== 1 && i < len);
  41863. syncPoint = i - 2;
  41864. i += 3;
  41865. break;
  41866. case 1:
  41867. // skip past non-sync sequences
  41868. if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) {
  41869. i += 3;
  41870. break;
  41871. } // deliver the NAL unit
  41872. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  41873. syncPoint = i - 2;
  41874. i += 3;
  41875. break;
  41876. default:
  41877. // the current byte isn't a one or zero, so it cannot be part
  41878. // of a sync sequence
  41879. i += 3;
  41880. break;
  41881. }
  41882. } // filter out the NAL units that were delivered
  41883. buffer = buffer.subarray(syncPoint);
  41884. i -= syncPoint;
  41885. syncPoint = 0;
  41886. };
  41887. this.reset = function () {
  41888. buffer = null;
  41889. syncPoint = 0;
  41890. this.trigger('reset');
  41891. };
  41892. this.flush = function () {
  41893. // deliver the last buffered NAL unit
  41894. if (buffer && buffer.byteLength > 3) {
  41895. this.trigger('data', buffer.subarray(syncPoint + 3));
  41896. } // reset the stream state
  41897. buffer = null;
  41898. syncPoint = 0;
  41899. this.trigger('done');
  41900. };
  41901. this.endTimeline = function () {
  41902. this.flush();
  41903. this.trigger('endedtimeline');
  41904. };
  41905. };
  41906. _NalByteStream.prototype = new stream(); // values of profile_idc that indicate additional fields are included in the SPS
  41907. // see Recommendation ITU-T H.264 (4/2013),
  41908. // 7.3.2.1.1 Sequence parameter set data syntax
  41909. PROFILES_WITH_OPTIONAL_SPS_DATA = {
  41910. 100: true,
  41911. 110: true,
  41912. 122: true,
  41913. 244: true,
  41914. 44: true,
  41915. 83: true,
  41916. 86: true,
  41917. 118: true,
  41918. 128: true,
  41919. // TODO: the three profiles below don't
  41920. // appear to have sps data in the specificiation anymore?
  41921. 138: true,
  41922. 139: true,
  41923. 134: true
  41924. };
  41925. /**
  41926. * Accepts input from a ElementaryStream and produces H.264 NAL unit data
  41927. * events.
  41928. */
  41929. _H264Stream = function H264Stream() {
  41930. var nalByteStream = new _NalByteStream(),
  41931. self,
  41932. trackId,
  41933. currentPts,
  41934. currentDts,
  41935. discardEmulationPreventionBytes,
  41936. readSequenceParameterSet,
  41937. skipScalingList;
  41938. _H264Stream.prototype.init.call(this);
  41939. self = this;
  41940. /*
  41941. * Pushes a packet from a stream onto the NalByteStream
  41942. *
  41943. * @param {Object} packet - A packet received from a stream
  41944. * @param {Uint8Array} packet.data - The raw bytes of the packet
  41945. * @param {Number} packet.dts - Decode timestamp of the packet
  41946. * @param {Number} packet.pts - Presentation timestamp of the packet
  41947. * @param {Number} packet.trackId - The id of the h264 track this packet came from
  41948. * @param {('video'|'audio')} packet.type - The type of packet
  41949. *
  41950. */
  41951. this.push = function (packet) {
  41952. if (packet.type !== 'video') {
  41953. return;
  41954. }
  41955. trackId = packet.trackId;
  41956. currentPts = packet.pts;
  41957. currentDts = packet.dts;
  41958. nalByteStream.push(packet);
  41959. };
  41960. /*
  41961. * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
  41962. * for the NALUs to the next stream component.
  41963. * Also, preprocess caption and sequence parameter NALUs.
  41964. *
  41965. * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
  41966. * @see NalByteStream.push
  41967. */
  41968. nalByteStream.on('data', function (data) {
  41969. var event = {
  41970. trackId: trackId,
  41971. pts: currentPts,
  41972. dts: currentDts,
  41973. data: data,
  41974. nalUnitTypeCode: data[0] & 0x1f
  41975. };
  41976. switch (event.nalUnitTypeCode) {
  41977. case 0x05:
  41978. event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
  41979. break;
  41980. case 0x06:
  41981. event.nalUnitType = 'sei_rbsp';
  41982. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  41983. break;
  41984. case 0x07:
  41985. event.nalUnitType = 'seq_parameter_set_rbsp';
  41986. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  41987. event.config = readSequenceParameterSet(event.escapedRBSP);
  41988. break;
  41989. case 0x08:
  41990. event.nalUnitType = 'pic_parameter_set_rbsp';
  41991. break;
  41992. case 0x09:
  41993. event.nalUnitType = 'access_unit_delimiter_rbsp';
  41994. break;
  41995. } // This triggers data on the H264Stream
  41996. self.trigger('data', event);
  41997. });
  41998. nalByteStream.on('done', function () {
  41999. self.trigger('done');
  42000. });
  42001. nalByteStream.on('partialdone', function () {
  42002. self.trigger('partialdone');
  42003. });
  42004. nalByteStream.on('reset', function () {
  42005. self.trigger('reset');
  42006. });
  42007. nalByteStream.on('endedtimeline', function () {
  42008. self.trigger('endedtimeline');
  42009. });
  42010. this.flush = function () {
  42011. nalByteStream.flush();
  42012. };
  42013. this.partialFlush = function () {
  42014. nalByteStream.partialFlush();
  42015. };
  42016. this.reset = function () {
  42017. nalByteStream.reset();
  42018. };
  42019. this.endTimeline = function () {
  42020. nalByteStream.endTimeline();
  42021. };
  42022. /**
  42023. * Advance the ExpGolomb decoder past a scaling list. The scaling
  42024. * list is optionally transmitted as part of a sequence parameter
  42025. * set and is not relevant to transmuxing.
  42026. * @param count {number} the number of entries in this scaling list
  42027. * @param expGolombDecoder {object} an ExpGolomb pointed to the
  42028. * start of a scaling list
  42029. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  42030. */
  42031. skipScalingList = function skipScalingList(count, expGolombDecoder) {
  42032. var lastScale = 8,
  42033. nextScale = 8,
  42034. j,
  42035. deltaScale;
  42036. for (j = 0; j < count; j++) {
  42037. if (nextScale !== 0) {
  42038. deltaScale = expGolombDecoder.readExpGolomb();
  42039. nextScale = (lastScale + deltaScale + 256) % 256;
  42040. }
  42041. lastScale = nextScale === 0 ? lastScale : nextScale;
  42042. }
  42043. };
  42044. /**
  42045. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  42046. * Sequence Payload"
  42047. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  42048. * unit
  42049. * @return {Uint8Array} the RBSP without any Emulation
  42050. * Prevention Bytes
  42051. */
  42052. discardEmulationPreventionBytes = function discardEmulationPreventionBytes(data) {
  42053. var length = data.byteLength,
  42054. emulationPreventionBytesPositions = [],
  42055. i = 1,
  42056. newLength,
  42057. newData; // Find all `Emulation Prevention Bytes`
  42058. while (i < length - 2) {
  42059. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  42060. emulationPreventionBytesPositions.push(i + 2);
  42061. i += 2;
  42062. } else {
  42063. i++;
  42064. }
  42065. } // If no Emulation Prevention Bytes were found just return the original
  42066. // array
  42067. if (emulationPreventionBytesPositions.length === 0) {
  42068. return data;
  42069. } // Create a new array to hold the NAL unit data
  42070. newLength = length - emulationPreventionBytesPositions.length;
  42071. newData = new Uint8Array(newLength);
  42072. var sourceIndex = 0;
  42073. for (i = 0; i < newLength; sourceIndex++, i++) {
  42074. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  42075. // Skip this byte
  42076. sourceIndex++; // Remove this position index
  42077. emulationPreventionBytesPositions.shift();
  42078. }
  42079. newData[i] = data[sourceIndex];
  42080. }
  42081. return newData;
  42082. };
  42083. /**
  42084. * Read a sequence parameter set and return some interesting video
  42085. * properties. A sequence parameter set is the H264 metadata that
  42086. * describes the properties of upcoming video frames.
  42087. * @param data {Uint8Array} the bytes of a sequence parameter set
  42088. * @return {object} an object with configuration parsed from the
  42089. * sequence parameter set, including the dimensions of the
  42090. * associated video frames.
  42091. */
  42092. readSequenceParameterSet = function readSequenceParameterSet(data) {
  42093. var frameCropLeftOffset = 0,
  42094. frameCropRightOffset = 0,
  42095. frameCropTopOffset = 0,
  42096. frameCropBottomOffset = 0,
  42097. expGolombDecoder,
  42098. profileIdc,
  42099. levelIdc,
  42100. profileCompatibility,
  42101. chromaFormatIdc,
  42102. picOrderCntType,
  42103. numRefFramesInPicOrderCntCycle,
  42104. picWidthInMbsMinus1,
  42105. picHeightInMapUnitsMinus1,
  42106. frameMbsOnlyFlag,
  42107. scalingListCount,
  42108. sarRatio = [1, 1],
  42109. aspectRatioIdc,
  42110. i;
  42111. expGolombDecoder = new expGolomb(data);
  42112. profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
  42113. profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
  42114. levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
  42115. expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
  42116. // some profiles have more optional data we don't need
  42117. if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
  42118. chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
  42119. if (chromaFormatIdc === 3) {
  42120. expGolombDecoder.skipBits(1); // separate_colour_plane_flag
  42121. }
  42122. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
  42123. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
  42124. expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
  42125. if (expGolombDecoder.readBoolean()) {
  42126. // seq_scaling_matrix_present_flag
  42127. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  42128. for (i = 0; i < scalingListCount; i++) {
  42129. if (expGolombDecoder.readBoolean()) {
  42130. // seq_scaling_list_present_flag[ i ]
  42131. if (i < 6) {
  42132. skipScalingList(16, expGolombDecoder);
  42133. } else {
  42134. skipScalingList(64, expGolombDecoder);
  42135. }
  42136. }
  42137. }
  42138. }
  42139. }
  42140. expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
  42141. picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
  42142. if (picOrderCntType === 0) {
  42143. expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
  42144. } else if (picOrderCntType === 1) {
  42145. expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
  42146. expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
  42147. expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
  42148. numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
  42149. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  42150. expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
  42151. }
  42152. }
  42153. expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
  42154. expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
  42155. picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  42156. picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  42157. frameMbsOnlyFlag = expGolombDecoder.readBits(1);
  42158. if (frameMbsOnlyFlag === 0) {
  42159. expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
  42160. }
  42161. expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
  42162. if (expGolombDecoder.readBoolean()) {
  42163. // frame_cropping_flag
  42164. frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
  42165. frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
  42166. frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
  42167. frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
  42168. }
  42169. if (expGolombDecoder.readBoolean()) {
  42170. // vui_parameters_present_flag
  42171. if (expGolombDecoder.readBoolean()) {
  42172. // aspect_ratio_info_present_flag
  42173. aspectRatioIdc = expGolombDecoder.readUnsignedByte();
  42174. switch (aspectRatioIdc) {
  42175. case 1:
  42176. sarRatio = [1, 1];
  42177. break;
  42178. case 2:
  42179. sarRatio = [12, 11];
  42180. break;
  42181. case 3:
  42182. sarRatio = [10, 11];
  42183. break;
  42184. case 4:
  42185. sarRatio = [16, 11];
  42186. break;
  42187. case 5:
  42188. sarRatio = [40, 33];
  42189. break;
  42190. case 6:
  42191. sarRatio = [24, 11];
  42192. break;
  42193. case 7:
  42194. sarRatio = [20, 11];
  42195. break;
  42196. case 8:
  42197. sarRatio = [32, 11];
  42198. break;
  42199. case 9:
  42200. sarRatio = [80, 33];
  42201. break;
  42202. case 10:
  42203. sarRatio = [18, 11];
  42204. break;
  42205. case 11:
  42206. sarRatio = [15, 11];
  42207. break;
  42208. case 12:
  42209. sarRatio = [64, 33];
  42210. break;
  42211. case 13:
  42212. sarRatio = [160, 99];
  42213. break;
  42214. case 14:
  42215. sarRatio = [4, 3];
  42216. break;
  42217. case 15:
  42218. sarRatio = [3, 2];
  42219. break;
  42220. case 16:
  42221. sarRatio = [2, 1];
  42222. break;
  42223. case 255:
  42224. {
  42225. sarRatio = [expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte()];
  42226. break;
  42227. }
  42228. }
  42229. if (sarRatio) {
  42230. sarRatio[0] / sarRatio[1];
  42231. }
  42232. }
  42233. }
  42234. return {
  42235. profileIdc: profileIdc,
  42236. levelIdc: levelIdc,
  42237. profileCompatibility: profileCompatibility,
  42238. width: (picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2,
  42239. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - frameCropTopOffset * 2 - frameCropBottomOffset * 2,
  42240. // sar is sample aspect ratio
  42241. sarRatio: sarRatio
  42242. };
  42243. };
  42244. };
  42245. _H264Stream.prototype = new stream();
  42246. var h264 = {
  42247. H264Stream: _H264Stream,
  42248. NalByteStream: _NalByteStream
  42249. };
  42250. /**
  42251. * mux.js
  42252. *
  42253. * Copyright (c) Brightcove
  42254. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  42255. *
  42256. * Utilities to detect basic properties and metadata about Aac data.
  42257. */
  42258. var ADTS_SAMPLING_FREQUENCIES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  42259. var parseId3TagSize = function parseId3TagSize(header, byteIndex) {
  42260. var returnSize = header[byteIndex + 6] << 21 | header[byteIndex + 7] << 14 | header[byteIndex + 8] << 7 | header[byteIndex + 9],
  42261. flags = header[byteIndex + 5],
  42262. footerPresent = (flags & 16) >> 4; // if we get a negative returnSize clamp it to 0
  42263. returnSize = returnSize >= 0 ? returnSize : 0;
  42264. if (footerPresent) {
  42265. return returnSize + 20;
  42266. }
  42267. return returnSize + 10;
  42268. };
  42269. var getId3Offset = function getId3Offset(data, offset) {
  42270. if (data.length - offset < 10 || data[offset] !== 'I'.charCodeAt(0) || data[offset + 1] !== 'D'.charCodeAt(0) || data[offset + 2] !== '3'.charCodeAt(0)) {
  42271. return offset;
  42272. }
  42273. offset += parseId3TagSize(data, offset);
  42274. return getId3Offset(data, offset);
  42275. }; // TODO: use vhs-utils
  42276. var isLikelyAacData$1 = function isLikelyAacData(data) {
  42277. var offset = getId3Offset(data, 0);
  42278. return data.length >= offset + 2 && (data[offset] & 0xFF) === 0xFF && (data[offset + 1] & 0xF0) === 0xF0 && // verify that the 2 layer bits are 0, aka this
  42279. // is not mp3 data but aac data.
  42280. (data[offset + 1] & 0x16) === 0x10;
  42281. };
  42282. var parseSyncSafeInteger = function parseSyncSafeInteger(data) {
  42283. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  42284. }; // return a percent-encoded representation of the specified byte range
  42285. // @see http://en.wikipedia.org/wiki/Percent-encoding
  42286. var percentEncode = function percentEncode(bytes, start, end) {
  42287. var i,
  42288. result = '';
  42289. for (i = start; i < end; i++) {
  42290. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  42291. }
  42292. return result;
  42293. }; // return the string representation of the specified byte range,
  42294. // interpreted as ISO-8859-1.
  42295. var parseIso88591 = function parseIso88591(bytes, start, end) {
  42296. return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
  42297. };
  42298. var parseAdtsSize = function parseAdtsSize(header, byteIndex) {
  42299. var lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
  42300. middle = header[byteIndex + 4] << 3,
  42301. highTwo = header[byteIndex + 3] & 0x3 << 11;
  42302. return highTwo | middle | lowThree;
  42303. };
  42304. var parseType$2 = function parseType(header, byteIndex) {
  42305. if (header[byteIndex] === 'I'.charCodeAt(0) && header[byteIndex + 1] === 'D'.charCodeAt(0) && header[byteIndex + 2] === '3'.charCodeAt(0)) {
  42306. return 'timed-metadata';
  42307. } else if (header[byteIndex] & 0xff === 0xff && (header[byteIndex + 1] & 0xf0) === 0xf0) {
  42308. return 'audio';
  42309. }
  42310. return null;
  42311. };
  42312. var parseSampleRate = function parseSampleRate(packet) {
  42313. var i = 0;
  42314. while (i + 5 < packet.length) {
  42315. if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
  42316. // If a valid header was not found, jump one forward and attempt to
  42317. // find a valid ADTS header starting at the next byte
  42318. i++;
  42319. continue;
  42320. }
  42321. return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];
  42322. }
  42323. return null;
  42324. };
  42325. var parseAacTimestamp = function parseAacTimestamp(packet) {
  42326. var frameStart, frameSize, frame, frameHeader; // find the start of the first frame and the end of the tag
  42327. frameStart = 10;
  42328. if (packet[5] & 0x40) {
  42329. // advance the frame start past the extended header
  42330. frameStart += 4; // header size field
  42331. frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
  42332. } // parse one or more ID3 frames
  42333. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  42334. do {
  42335. // determine the number of bytes in this frame
  42336. frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
  42337. if (frameSize < 1) {
  42338. return null;
  42339. }
  42340. frameHeader = String.fromCharCode(packet[frameStart], packet[frameStart + 1], packet[frameStart + 2], packet[frameStart + 3]);
  42341. if (frameHeader === 'PRIV') {
  42342. frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
  42343. for (var i = 0; i < frame.byteLength; i++) {
  42344. if (frame[i] === 0) {
  42345. var owner = parseIso88591(frame, 0, i);
  42346. if (owner === 'com.apple.streaming.transportStreamTimestamp') {
  42347. var d = frame.subarray(i + 1);
  42348. var size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  42349. size *= 4;
  42350. size += d[7] & 0x03;
  42351. return size;
  42352. }
  42353. break;
  42354. }
  42355. }
  42356. }
  42357. frameStart += 10; // advance past the frame header
  42358. frameStart += frameSize; // advance past the frame body
  42359. } while (frameStart < packet.byteLength);
  42360. return null;
  42361. };
  42362. var utils = {
  42363. isLikelyAacData: isLikelyAacData$1,
  42364. parseId3TagSize: parseId3TagSize,
  42365. parseAdtsSize: parseAdtsSize,
  42366. parseType: parseType$2,
  42367. parseSampleRate: parseSampleRate,
  42368. parseAacTimestamp: parseAacTimestamp
  42369. };
  42370. var _AacStream;
  42371. /**
  42372. * Splits an incoming stream of binary data into ADTS and ID3 Frames.
  42373. */
  42374. _AacStream = function AacStream() {
  42375. var everything = new Uint8Array(),
  42376. timeStamp = 0;
  42377. _AacStream.prototype.init.call(this);
  42378. this.setTimestamp = function (timestamp) {
  42379. timeStamp = timestamp;
  42380. };
  42381. this.push = function (bytes) {
  42382. var frameSize = 0,
  42383. byteIndex = 0,
  42384. bytesLeft,
  42385. chunk,
  42386. packet,
  42387. tempLength; // If there are bytes remaining from the last segment, prepend them to the
  42388. // bytes that were pushed in
  42389. if (everything.length) {
  42390. tempLength = everything.length;
  42391. everything = new Uint8Array(bytes.byteLength + tempLength);
  42392. everything.set(everything.subarray(0, tempLength));
  42393. everything.set(bytes, tempLength);
  42394. } else {
  42395. everything = bytes;
  42396. }
  42397. while (everything.length - byteIndex >= 3) {
  42398. if (everything[byteIndex] === 'I'.charCodeAt(0) && everything[byteIndex + 1] === 'D'.charCodeAt(0) && everything[byteIndex + 2] === '3'.charCodeAt(0)) {
  42399. // Exit early because we don't have enough to parse
  42400. // the ID3 tag header
  42401. if (everything.length - byteIndex < 10) {
  42402. break;
  42403. } // check framesize
  42404. frameSize = utils.parseId3TagSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  42405. // to emit a full packet
  42406. // Add to byteIndex to support multiple ID3 tags in sequence
  42407. if (byteIndex + frameSize > everything.length) {
  42408. break;
  42409. }
  42410. chunk = {
  42411. type: 'timed-metadata',
  42412. data: everything.subarray(byteIndex, byteIndex + frameSize)
  42413. };
  42414. this.trigger('data', chunk);
  42415. byteIndex += frameSize;
  42416. continue;
  42417. } else if ((everything[byteIndex] & 0xff) === 0xff && (everything[byteIndex + 1] & 0xf0) === 0xf0) {
  42418. // Exit early because we don't have enough to parse
  42419. // the ADTS frame header
  42420. if (everything.length - byteIndex < 7) {
  42421. break;
  42422. }
  42423. frameSize = utils.parseAdtsSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  42424. // to emit a full packet
  42425. if (byteIndex + frameSize > everything.length) {
  42426. break;
  42427. }
  42428. packet = {
  42429. type: 'audio',
  42430. data: everything.subarray(byteIndex, byteIndex + frameSize),
  42431. pts: timeStamp,
  42432. dts: timeStamp
  42433. };
  42434. this.trigger('data', packet);
  42435. byteIndex += frameSize;
  42436. continue;
  42437. }
  42438. byteIndex++;
  42439. }
  42440. bytesLeft = everything.length - byteIndex;
  42441. if (bytesLeft > 0) {
  42442. everything = everything.subarray(byteIndex);
  42443. } else {
  42444. everything = new Uint8Array();
  42445. }
  42446. };
  42447. this.reset = function () {
  42448. everything = new Uint8Array();
  42449. this.trigger('reset');
  42450. };
  42451. this.endTimeline = function () {
  42452. everything = new Uint8Array();
  42453. this.trigger('endedtimeline');
  42454. };
  42455. };
  42456. _AacStream.prototype = new stream();
  42457. var aac = _AacStream; // constants
  42458. var AUDIO_PROPERTIES = ['audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize'];
  42459. var audioProperties = AUDIO_PROPERTIES;
  42460. var VIDEO_PROPERTIES = ['width', 'height', 'profileIdc', 'levelIdc', 'profileCompatibility', 'sarRatio'];
  42461. var videoProperties = VIDEO_PROPERTIES;
  42462. var H264Stream = h264.H264Stream;
  42463. var isLikelyAacData = utils.isLikelyAacData;
  42464. var ONE_SECOND_IN_TS$1 = clock.ONE_SECOND_IN_TS; // object types
  42465. var _VideoSegmentStream, _AudioSegmentStream, _Transmuxer, _CoalesceStream;
  42466. var retriggerForStream = function retriggerForStream(key, event) {
  42467. event.stream = key;
  42468. this.trigger('log', event);
  42469. };
  42470. var addPipelineLogRetriggers = function addPipelineLogRetriggers(transmuxer, pipeline) {
  42471. var keys = Object.keys(pipeline);
  42472. for (var i = 0; i < keys.length; i++) {
  42473. var key = keys[i]; // skip non-stream keys and headOfPipeline
  42474. // which is just a duplicate
  42475. if (key === 'headOfPipeline' || !pipeline[key].on) {
  42476. continue;
  42477. }
  42478. pipeline[key].on('log', retriggerForStream.bind(transmuxer, key));
  42479. }
  42480. };
  42481. /**
  42482. * Compare two arrays (even typed) for same-ness
  42483. */
  42484. var arrayEquals = function arrayEquals(a, b) {
  42485. var i;
  42486. if (a.length !== b.length) {
  42487. return false;
  42488. } // compare the value of each element in the array
  42489. for (i = 0; i < a.length; i++) {
  42490. if (a[i] !== b[i]) {
  42491. return false;
  42492. }
  42493. }
  42494. return true;
  42495. };
  42496. var generateSegmentTimingInfo = function generateSegmentTimingInfo(baseMediaDecodeTime, startDts, startPts, endDts, endPts, prependedContentDuration) {
  42497. var ptsOffsetFromDts = startPts - startDts,
  42498. decodeDuration = endDts - startDts,
  42499. presentationDuration = endPts - startPts; // The PTS and DTS values are based on the actual stream times from the segment,
  42500. // however, the player time values will reflect a start from the baseMediaDecodeTime.
  42501. // In order to provide relevant values for the player times, base timing info on the
  42502. // baseMediaDecodeTime and the DTS and PTS durations of the segment.
  42503. return {
  42504. start: {
  42505. dts: baseMediaDecodeTime,
  42506. pts: baseMediaDecodeTime + ptsOffsetFromDts
  42507. },
  42508. end: {
  42509. dts: baseMediaDecodeTime + decodeDuration,
  42510. pts: baseMediaDecodeTime + presentationDuration
  42511. },
  42512. prependedContentDuration: prependedContentDuration,
  42513. baseMediaDecodeTime: baseMediaDecodeTime
  42514. };
  42515. };
  42516. /**
  42517. * Constructs a single-track, ISO BMFF media segment from AAC data
  42518. * events. The output of this stream can be fed to a SourceBuffer
  42519. * configured with a suitable initialization segment.
  42520. * @param track {object} track metadata configuration
  42521. * @param options {object} transmuxer options object
  42522. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  42523. * in the source; false to adjust the first segment to start at 0.
  42524. */
  42525. _AudioSegmentStream = function AudioSegmentStream(track, options) {
  42526. var adtsFrames = [],
  42527. sequenceNumber,
  42528. earliestAllowedDts = 0,
  42529. audioAppendStartTs = 0,
  42530. videoBaseMediaDecodeTime = Infinity;
  42531. options = options || {};
  42532. sequenceNumber = options.firstSequenceNumber || 0;
  42533. _AudioSegmentStream.prototype.init.call(this);
  42534. this.push = function (data) {
  42535. trackDecodeInfo.collectDtsInfo(track, data);
  42536. if (track) {
  42537. audioProperties.forEach(function (prop) {
  42538. track[prop] = data[prop];
  42539. });
  42540. } // buffer audio data until end() is called
  42541. adtsFrames.push(data);
  42542. };
  42543. this.setEarliestDts = function (earliestDts) {
  42544. earliestAllowedDts = earliestDts;
  42545. };
  42546. this.setVideoBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  42547. videoBaseMediaDecodeTime = baseMediaDecodeTime;
  42548. };
  42549. this.setAudioAppendStart = function (timestamp) {
  42550. audioAppendStartTs = timestamp;
  42551. };
  42552. this.flush = function () {
  42553. var frames, moof, mdat, boxes, frameDuration, segmentDuration, videoClockCyclesOfSilencePrefixed; // return early if no audio data has been observed
  42554. if (adtsFrames.length === 0) {
  42555. this.trigger('done', 'AudioSegmentStream');
  42556. return;
  42557. }
  42558. frames = audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts);
  42559. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps); // amount of audio filled but the value is in video clock rather than audio clock
  42560. videoClockCyclesOfSilencePrefixed = audioFrameUtils.prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime); // we have to build the index from byte locations to
  42561. // samples (that is, adts frames) in the audio data
  42562. track.samples = audioFrameUtils.generateSampleTable(frames); // concatenate the audio data to constuct the mdat
  42563. mdat = mp4Generator.mdat(audioFrameUtils.concatenateFrameData(frames));
  42564. adtsFrames = [];
  42565. moof = mp4Generator.moof(sequenceNumber, [track]);
  42566. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // bump the sequence number for next time
  42567. sequenceNumber++;
  42568. boxes.set(moof);
  42569. boxes.set(mdat, moof.byteLength);
  42570. trackDecodeInfo.clearDtsInfo(track);
  42571. frameDuration = Math.ceil(ONE_SECOND_IN_TS$1 * 1024 / track.samplerate); // TODO this check was added to maintain backwards compatibility (particularly with
  42572. // tests) on adding the timingInfo event. However, it seems unlikely that there's a
  42573. // valid use-case where an init segment/data should be triggered without associated
  42574. // frames. Leaving for now, but should be looked into.
  42575. if (frames.length) {
  42576. segmentDuration = frames.length * frameDuration;
  42577. this.trigger('segmentTimingInfo', generateSegmentTimingInfo( // The audio track's baseMediaDecodeTime is in audio clock cycles, but the
  42578. // frame info is in video clock cycles. Convert to match expectation of
  42579. // listeners (that all timestamps will be based on video clock cycles).
  42580. clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate), // frame times are already in video clock, as is segment duration
  42581. frames[0].dts, frames[0].pts, frames[0].dts + segmentDuration, frames[0].pts + segmentDuration, videoClockCyclesOfSilencePrefixed || 0));
  42582. this.trigger('timingInfo', {
  42583. start: frames[0].pts,
  42584. end: frames[0].pts + segmentDuration
  42585. });
  42586. }
  42587. this.trigger('data', {
  42588. track: track,
  42589. boxes: boxes
  42590. });
  42591. this.trigger('done', 'AudioSegmentStream');
  42592. };
  42593. this.reset = function () {
  42594. trackDecodeInfo.clearDtsInfo(track);
  42595. adtsFrames = [];
  42596. this.trigger('reset');
  42597. };
  42598. };
  42599. _AudioSegmentStream.prototype = new stream();
  42600. /**
  42601. * Constructs a single-track, ISO BMFF media segment from H264 data
  42602. * events. The output of this stream can be fed to a SourceBuffer
  42603. * configured with a suitable initialization segment.
  42604. * @param track {object} track metadata configuration
  42605. * @param options {object} transmuxer options object
  42606. * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
  42607. * gopsToAlignWith list when attempting to align gop pts
  42608. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  42609. * in the source; false to adjust the first segment to start at 0.
  42610. */
  42611. _VideoSegmentStream = function VideoSegmentStream(track, options) {
  42612. var sequenceNumber,
  42613. nalUnits = [],
  42614. gopsToAlignWith = [],
  42615. config,
  42616. pps;
  42617. options = options || {};
  42618. sequenceNumber = options.firstSequenceNumber || 0;
  42619. _VideoSegmentStream.prototype.init.call(this);
  42620. delete track.minPTS;
  42621. this.gopCache_ = [];
  42622. /**
  42623. * Constructs a ISO BMFF segment given H264 nalUnits
  42624. * @param {Object} nalUnit A data event representing a nalUnit
  42625. * @param {String} nalUnit.nalUnitType
  42626. * @param {Object} nalUnit.config Properties for a mp4 track
  42627. * @param {Uint8Array} nalUnit.data The nalUnit bytes
  42628. * @see lib/codecs/h264.js
  42629. **/
  42630. this.push = function (nalUnit) {
  42631. trackDecodeInfo.collectDtsInfo(track, nalUnit); // record the track config
  42632. if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
  42633. config = nalUnit.config;
  42634. track.sps = [nalUnit.data];
  42635. videoProperties.forEach(function (prop) {
  42636. track[prop] = config[prop];
  42637. }, this);
  42638. }
  42639. if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) {
  42640. pps = nalUnit.data;
  42641. track.pps = [nalUnit.data];
  42642. } // buffer video until flush() is called
  42643. nalUnits.push(nalUnit);
  42644. };
  42645. /**
  42646. * Pass constructed ISO BMFF track and boxes on to the
  42647. * next stream in the pipeline
  42648. **/
  42649. this.flush = function () {
  42650. var frames,
  42651. gopForFusion,
  42652. gops,
  42653. moof,
  42654. mdat,
  42655. boxes,
  42656. prependedContentDuration = 0,
  42657. firstGop,
  42658. lastGop; // Throw away nalUnits at the start of the byte stream until
  42659. // we find the first AUD
  42660. while (nalUnits.length) {
  42661. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  42662. break;
  42663. }
  42664. nalUnits.shift();
  42665. } // Return early if no video data has been observed
  42666. if (nalUnits.length === 0) {
  42667. this.resetStream_();
  42668. this.trigger('done', 'VideoSegmentStream');
  42669. return;
  42670. } // Organize the raw nal-units into arrays that represent
  42671. // higher-level constructs such as frames and gops
  42672. // (group-of-pictures)
  42673. frames = frameUtils.groupNalsIntoFrames(nalUnits);
  42674. gops = frameUtils.groupFramesIntoGops(frames); // If the first frame of this fragment is not a keyframe we have
  42675. // a problem since MSE (on Chrome) requires a leading keyframe.
  42676. //
  42677. // We have two approaches to repairing this situation:
  42678. // 1) GOP-FUSION:
  42679. // This is where we keep track of the GOPS (group-of-pictures)
  42680. // from previous fragments and attempt to find one that we can
  42681. // prepend to the current fragment in order to create a valid
  42682. // fragment.
  42683. // 2) KEYFRAME-PULLING:
  42684. // Here we search for the first keyframe in the fragment and
  42685. // throw away all the frames between the start of the fragment
  42686. // and that keyframe. We then extend the duration and pull the
  42687. // PTS of the keyframe forward so that it covers the time range
  42688. // of the frames that were disposed of.
  42689. //
  42690. // #1 is far prefereable over #2 which can cause "stuttering" but
  42691. // requires more things to be just right.
  42692. if (!gops[0][0].keyFrame) {
  42693. // Search for a gop for fusion from our gopCache
  42694. gopForFusion = this.getGopForFusion_(nalUnits[0], track);
  42695. if (gopForFusion) {
  42696. // in order to provide more accurate timing information about the segment, save
  42697. // the number of seconds prepended to the original segment due to GOP fusion
  42698. prependedContentDuration = gopForFusion.duration;
  42699. gops.unshift(gopForFusion); // Adjust Gops' metadata to account for the inclusion of the
  42700. // new gop at the beginning
  42701. gops.byteLength += gopForFusion.byteLength;
  42702. gops.nalCount += gopForFusion.nalCount;
  42703. gops.pts = gopForFusion.pts;
  42704. gops.dts = gopForFusion.dts;
  42705. gops.duration += gopForFusion.duration;
  42706. } else {
  42707. // If we didn't find a candidate gop fall back to keyframe-pulling
  42708. gops = frameUtils.extendFirstKeyFrame(gops);
  42709. }
  42710. } // Trim gops to align with gopsToAlignWith
  42711. if (gopsToAlignWith.length) {
  42712. var alignedGops;
  42713. if (options.alignGopsAtEnd) {
  42714. alignedGops = this.alignGopsAtEnd_(gops);
  42715. } else {
  42716. alignedGops = this.alignGopsAtStart_(gops);
  42717. }
  42718. if (!alignedGops) {
  42719. // save all the nals in the last GOP into the gop cache
  42720. this.gopCache_.unshift({
  42721. gop: gops.pop(),
  42722. pps: track.pps,
  42723. sps: track.sps
  42724. }); // Keep a maximum of 6 GOPs in the cache
  42725. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  42726. nalUnits = []; // return early no gops can be aligned with desired gopsToAlignWith
  42727. this.resetStream_();
  42728. this.trigger('done', 'VideoSegmentStream');
  42729. return;
  42730. } // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
  42731. // when recalculated before sending off to CoalesceStream
  42732. trackDecodeInfo.clearDtsInfo(track);
  42733. gops = alignedGops;
  42734. }
  42735. trackDecodeInfo.collectDtsInfo(track, gops); // First, we have to build the index from byte locations to
  42736. // samples (that is, frames) in the video data
  42737. track.samples = frameUtils.generateSampleTable(gops); // Concatenate the video data and construct the mdat
  42738. mdat = mp4Generator.mdat(frameUtils.concatenateNalData(gops));
  42739. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
  42740. this.trigger('processedGopsInfo', gops.map(function (gop) {
  42741. return {
  42742. pts: gop.pts,
  42743. dts: gop.dts,
  42744. byteLength: gop.byteLength
  42745. };
  42746. }));
  42747. firstGop = gops[0];
  42748. lastGop = gops[gops.length - 1];
  42749. this.trigger('segmentTimingInfo', generateSegmentTimingInfo(track.baseMediaDecodeTime, firstGop.dts, firstGop.pts, lastGop.dts + lastGop.duration, lastGop.pts + lastGop.duration, prependedContentDuration));
  42750. this.trigger('timingInfo', {
  42751. start: gops[0].pts,
  42752. end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
  42753. }); // save all the nals in the last GOP into the gop cache
  42754. this.gopCache_.unshift({
  42755. gop: gops.pop(),
  42756. pps: track.pps,
  42757. sps: track.sps
  42758. }); // Keep a maximum of 6 GOPs in the cache
  42759. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  42760. nalUnits = [];
  42761. this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
  42762. this.trigger('timelineStartInfo', track.timelineStartInfo);
  42763. moof = mp4Generator.moof(sequenceNumber, [track]); // it would be great to allocate this array up front instead of
  42764. // throwing away hundreds of media segment fragments
  42765. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // Bump the sequence number for next time
  42766. sequenceNumber++;
  42767. boxes.set(moof);
  42768. boxes.set(mdat, moof.byteLength);
  42769. this.trigger('data', {
  42770. track: track,
  42771. boxes: boxes
  42772. });
  42773. this.resetStream_(); // Continue with the flush process now
  42774. this.trigger('done', 'VideoSegmentStream');
  42775. };
  42776. this.reset = function () {
  42777. this.resetStream_();
  42778. nalUnits = [];
  42779. this.gopCache_.length = 0;
  42780. gopsToAlignWith.length = 0;
  42781. this.trigger('reset');
  42782. };
  42783. this.resetStream_ = function () {
  42784. trackDecodeInfo.clearDtsInfo(track); // reset config and pps because they may differ across segments
  42785. // for instance, when we are rendition switching
  42786. config = undefined;
  42787. pps = undefined;
  42788. }; // Search for a candidate Gop for gop-fusion from the gop cache and
  42789. // return it or return null if no good candidate was found
  42790. this.getGopForFusion_ = function (nalUnit) {
  42791. var halfSecond = 45000,
  42792. // Half-a-second in a 90khz clock
  42793. allowableOverlap = 10000,
  42794. // About 3 frames @ 30fps
  42795. nearestDistance = Infinity,
  42796. dtsDistance,
  42797. nearestGopObj,
  42798. currentGop,
  42799. currentGopObj,
  42800. i; // Search for the GOP nearest to the beginning of this nal unit
  42801. for (i = 0; i < this.gopCache_.length; i++) {
  42802. currentGopObj = this.gopCache_[i];
  42803. currentGop = currentGopObj.gop; // Reject Gops with different SPS or PPS
  42804. if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
  42805. continue;
  42806. } // Reject Gops that would require a negative baseMediaDecodeTime
  42807. if (currentGop.dts < track.timelineStartInfo.dts) {
  42808. continue;
  42809. } // The distance between the end of the gop and the start of the nalUnit
  42810. dtsDistance = nalUnit.dts - currentGop.dts - currentGop.duration; // Only consider GOPS that start before the nal unit and end within
  42811. // a half-second of the nal unit
  42812. if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) {
  42813. // Always use the closest GOP we found if there is more than
  42814. // one candidate
  42815. if (!nearestGopObj || nearestDistance > dtsDistance) {
  42816. nearestGopObj = currentGopObj;
  42817. nearestDistance = dtsDistance;
  42818. }
  42819. }
  42820. }
  42821. if (nearestGopObj) {
  42822. return nearestGopObj.gop;
  42823. }
  42824. return null;
  42825. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  42826. // of gopsToAlignWith starting from the START of the list
  42827. this.alignGopsAtStart_ = function (gops) {
  42828. var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
  42829. byteLength = gops.byteLength;
  42830. nalCount = gops.nalCount;
  42831. duration = gops.duration;
  42832. alignIndex = gopIndex = 0;
  42833. while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
  42834. align = gopsToAlignWith[alignIndex];
  42835. gop = gops[gopIndex];
  42836. if (align.pts === gop.pts) {
  42837. break;
  42838. }
  42839. if (gop.pts > align.pts) {
  42840. // this current gop starts after the current gop we want to align on, so increment
  42841. // align index
  42842. alignIndex++;
  42843. continue;
  42844. } // current gop starts before the current gop we want to align on. so increment gop
  42845. // index
  42846. gopIndex++;
  42847. byteLength -= gop.byteLength;
  42848. nalCount -= gop.nalCount;
  42849. duration -= gop.duration;
  42850. }
  42851. if (gopIndex === 0) {
  42852. // no gops to trim
  42853. return gops;
  42854. }
  42855. if (gopIndex === gops.length) {
  42856. // all gops trimmed, skip appending all gops
  42857. return null;
  42858. }
  42859. alignedGops = gops.slice(gopIndex);
  42860. alignedGops.byteLength = byteLength;
  42861. alignedGops.duration = duration;
  42862. alignedGops.nalCount = nalCount;
  42863. alignedGops.pts = alignedGops[0].pts;
  42864. alignedGops.dts = alignedGops[0].dts;
  42865. return alignedGops;
  42866. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  42867. // of gopsToAlignWith starting from the END of the list
  42868. this.alignGopsAtEnd_ = function (gops) {
  42869. var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
  42870. alignIndex = gopsToAlignWith.length - 1;
  42871. gopIndex = gops.length - 1;
  42872. alignEndIndex = null;
  42873. matchFound = false;
  42874. while (alignIndex >= 0 && gopIndex >= 0) {
  42875. align = gopsToAlignWith[alignIndex];
  42876. gop = gops[gopIndex];
  42877. if (align.pts === gop.pts) {
  42878. matchFound = true;
  42879. break;
  42880. }
  42881. if (align.pts > gop.pts) {
  42882. alignIndex--;
  42883. continue;
  42884. }
  42885. if (alignIndex === gopsToAlignWith.length - 1) {
  42886. // gop.pts is greater than the last alignment candidate. If no match is found
  42887. // by the end of this loop, we still want to append gops that come after this
  42888. // point
  42889. alignEndIndex = gopIndex;
  42890. }
  42891. gopIndex--;
  42892. }
  42893. if (!matchFound && alignEndIndex === null) {
  42894. return null;
  42895. }
  42896. var trimIndex;
  42897. if (matchFound) {
  42898. trimIndex = gopIndex;
  42899. } else {
  42900. trimIndex = alignEndIndex;
  42901. }
  42902. if (trimIndex === 0) {
  42903. return gops;
  42904. }
  42905. var alignedGops = gops.slice(trimIndex);
  42906. var metadata = alignedGops.reduce(function (total, gop) {
  42907. total.byteLength += gop.byteLength;
  42908. total.duration += gop.duration;
  42909. total.nalCount += gop.nalCount;
  42910. return total;
  42911. }, {
  42912. byteLength: 0,
  42913. duration: 0,
  42914. nalCount: 0
  42915. });
  42916. alignedGops.byteLength = metadata.byteLength;
  42917. alignedGops.duration = metadata.duration;
  42918. alignedGops.nalCount = metadata.nalCount;
  42919. alignedGops.pts = alignedGops[0].pts;
  42920. alignedGops.dts = alignedGops[0].dts;
  42921. return alignedGops;
  42922. };
  42923. this.alignGopsWith = function (newGopsToAlignWith) {
  42924. gopsToAlignWith = newGopsToAlignWith;
  42925. };
  42926. };
  42927. _VideoSegmentStream.prototype = new stream();
  42928. /**
  42929. * A Stream that can combine multiple streams (ie. audio & video)
  42930. * into a single output segment for MSE. Also supports audio-only
  42931. * and video-only streams.
  42932. * @param options {object} transmuxer options object
  42933. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  42934. * in the source; false to adjust the first segment to start at media timeline start.
  42935. */
  42936. _CoalesceStream = function CoalesceStream(options, metadataStream) {
  42937. // Number of Tracks per output segment
  42938. // If greater than 1, we combine multiple
  42939. // tracks into a single segment
  42940. this.numberOfTracks = 0;
  42941. this.metadataStream = metadataStream;
  42942. options = options || {};
  42943. if (typeof options.remux !== 'undefined') {
  42944. this.remuxTracks = !!options.remux;
  42945. } else {
  42946. this.remuxTracks = true;
  42947. }
  42948. if (typeof options.keepOriginalTimestamps === 'boolean') {
  42949. this.keepOriginalTimestamps = options.keepOriginalTimestamps;
  42950. } else {
  42951. this.keepOriginalTimestamps = false;
  42952. }
  42953. this.pendingTracks = [];
  42954. this.videoTrack = null;
  42955. this.pendingBoxes = [];
  42956. this.pendingCaptions = [];
  42957. this.pendingMetadata = [];
  42958. this.pendingBytes = 0;
  42959. this.emittedTracks = 0;
  42960. _CoalesceStream.prototype.init.call(this); // Take output from multiple
  42961. this.push = function (output) {
  42962. // buffer incoming captions until the associated video segment
  42963. // finishes
  42964. if (output.text) {
  42965. return this.pendingCaptions.push(output);
  42966. } // buffer incoming id3 tags until the final flush
  42967. if (output.frames) {
  42968. return this.pendingMetadata.push(output);
  42969. } // Add this track to the list of pending tracks and store
  42970. // important information required for the construction of
  42971. // the final segment
  42972. this.pendingTracks.push(output.track);
  42973. this.pendingBytes += output.boxes.byteLength; // TODO: is there an issue for this against chrome?
  42974. // We unshift audio and push video because
  42975. // as of Chrome 75 when switching from
  42976. // one init segment to another if the video
  42977. // mdat does not appear after the audio mdat
  42978. // only audio will play for the duration of our transmux.
  42979. if (output.track.type === 'video') {
  42980. this.videoTrack = output.track;
  42981. this.pendingBoxes.push(output.boxes);
  42982. }
  42983. if (output.track.type === 'audio') {
  42984. this.audioTrack = output.track;
  42985. this.pendingBoxes.unshift(output.boxes);
  42986. }
  42987. };
  42988. };
  42989. _CoalesceStream.prototype = new stream();
  42990. _CoalesceStream.prototype.flush = function (flushSource) {
  42991. var offset = 0,
  42992. event = {
  42993. captions: [],
  42994. captionStreams: {},
  42995. metadata: [],
  42996. info: {}
  42997. },
  42998. caption,
  42999. id3,
  43000. initSegment,
  43001. timelineStartPts = 0,
  43002. i;
  43003. if (this.pendingTracks.length < this.numberOfTracks) {
  43004. if (flushSource !== 'VideoSegmentStream' && flushSource !== 'AudioSegmentStream') {
  43005. // Return because we haven't received a flush from a data-generating
  43006. // portion of the segment (meaning that we have only recieved meta-data
  43007. // or captions.)
  43008. return;
  43009. } else if (this.remuxTracks) {
  43010. // Return until we have enough tracks from the pipeline to remux (if we
  43011. // are remuxing audio and video into a single MP4)
  43012. return;
  43013. } else if (this.pendingTracks.length === 0) {
  43014. // In the case where we receive a flush without any data having been
  43015. // received we consider it an emitted track for the purposes of coalescing
  43016. // `done` events.
  43017. // We do this for the case where there is an audio and video track in the
  43018. // segment but no audio data. (seen in several playlists with alternate
  43019. // audio tracks and no audio present in the main TS segments.)
  43020. this.emittedTracks++;
  43021. if (this.emittedTracks >= this.numberOfTracks) {
  43022. this.trigger('done');
  43023. this.emittedTracks = 0;
  43024. }
  43025. return;
  43026. }
  43027. }
  43028. if (this.videoTrack) {
  43029. timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  43030. videoProperties.forEach(function (prop) {
  43031. event.info[prop] = this.videoTrack[prop];
  43032. }, this);
  43033. } else if (this.audioTrack) {
  43034. timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  43035. audioProperties.forEach(function (prop) {
  43036. event.info[prop] = this.audioTrack[prop];
  43037. }, this);
  43038. }
  43039. if (this.videoTrack || this.audioTrack) {
  43040. if (this.pendingTracks.length === 1) {
  43041. event.type = this.pendingTracks[0].type;
  43042. } else {
  43043. event.type = 'combined';
  43044. }
  43045. this.emittedTracks += this.pendingTracks.length;
  43046. initSegment = mp4Generator.initSegment(this.pendingTracks); // Create a new typed array to hold the init segment
  43047. event.initSegment = new Uint8Array(initSegment.byteLength); // Create an init segment containing a moov
  43048. // and track definitions
  43049. event.initSegment.set(initSegment); // Create a new typed array to hold the moof+mdats
  43050. event.data = new Uint8Array(this.pendingBytes); // Append each moof+mdat (one per track) together
  43051. for (i = 0; i < this.pendingBoxes.length; i++) {
  43052. event.data.set(this.pendingBoxes[i], offset);
  43053. offset += this.pendingBoxes[i].byteLength;
  43054. } // Translate caption PTS times into second offsets to match the
  43055. // video timeline for the segment, and add track info
  43056. for (i = 0; i < this.pendingCaptions.length; i++) {
  43057. caption = this.pendingCaptions[i];
  43058. caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
  43059. caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
  43060. event.captionStreams[caption.stream] = true;
  43061. event.captions.push(caption);
  43062. } // Translate ID3 frame PTS times into second offsets to match the
  43063. // video timeline for the segment
  43064. for (i = 0; i < this.pendingMetadata.length; i++) {
  43065. id3 = this.pendingMetadata[i];
  43066. id3.cueTime = clock.metadataTsToSeconds(id3.pts, timelineStartPts, this.keepOriginalTimestamps);
  43067. event.metadata.push(id3);
  43068. } // We add this to every single emitted segment even though we only need
  43069. // it for the first
  43070. event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state
  43071. this.pendingTracks.length = 0;
  43072. this.videoTrack = null;
  43073. this.pendingBoxes.length = 0;
  43074. this.pendingCaptions.length = 0;
  43075. this.pendingBytes = 0;
  43076. this.pendingMetadata.length = 0; // Emit the built segment
  43077. // We include captions and ID3 tags for backwards compatibility,
  43078. // ideally we should send only video and audio in the data event
  43079. this.trigger('data', event); // Emit each caption to the outside world
  43080. // Ideally, this would happen immediately on parsing captions,
  43081. // but we need to ensure that video data is sent back first
  43082. // so that caption timing can be adjusted to match video timing
  43083. for (i = 0; i < event.captions.length; i++) {
  43084. caption = event.captions[i];
  43085. this.trigger('caption', caption);
  43086. } // Emit each id3 tag to the outside world
  43087. // Ideally, this would happen immediately on parsing the tag,
  43088. // but we need to ensure that video data is sent back first
  43089. // so that ID3 frame timing can be adjusted to match video timing
  43090. for (i = 0; i < event.metadata.length; i++) {
  43091. id3 = event.metadata[i];
  43092. this.trigger('id3Frame', id3);
  43093. }
  43094. } // Only emit `done` if all tracks have been flushed and emitted
  43095. if (this.emittedTracks >= this.numberOfTracks) {
  43096. this.trigger('done');
  43097. this.emittedTracks = 0;
  43098. }
  43099. };
  43100. _CoalesceStream.prototype.setRemux = function (val) {
  43101. this.remuxTracks = val;
  43102. };
  43103. /**
  43104. * A Stream that expects MP2T binary data as input and produces
  43105. * corresponding media segments, suitable for use with Media Source
  43106. * Extension (MSE) implementations that support the ISO BMFF byte
  43107. * stream format, like Chrome.
  43108. */
  43109. _Transmuxer = function Transmuxer(options) {
  43110. var self = this,
  43111. hasFlushed = true,
  43112. videoTrack,
  43113. audioTrack;
  43114. _Transmuxer.prototype.init.call(this);
  43115. options = options || {};
  43116. this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
  43117. this.transmuxPipeline_ = {};
  43118. this.setupAacPipeline = function () {
  43119. var pipeline = {};
  43120. this.transmuxPipeline_ = pipeline;
  43121. pipeline.type = 'aac';
  43122. pipeline.metadataStream = new m2ts_1.MetadataStream(); // set up the parsing pipeline
  43123. pipeline.aacStream = new aac();
  43124. pipeline.audioTimestampRolloverStream = new m2ts_1.TimestampRolloverStream('audio');
  43125. pipeline.timedMetadataTimestampRolloverStream = new m2ts_1.TimestampRolloverStream('timed-metadata');
  43126. pipeline.adtsStream = new adts();
  43127. pipeline.coalesceStream = new _CoalesceStream(options, pipeline.metadataStream);
  43128. pipeline.headOfPipeline = pipeline.aacStream;
  43129. pipeline.aacStream.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream);
  43130. pipeline.aacStream.pipe(pipeline.timedMetadataTimestampRolloverStream).pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);
  43131. pipeline.metadataStream.on('timestamp', function (frame) {
  43132. pipeline.aacStream.setTimestamp(frame.timeStamp);
  43133. });
  43134. pipeline.aacStream.on('data', function (data) {
  43135. if (data.type !== 'timed-metadata' && data.type !== 'audio' || pipeline.audioSegmentStream) {
  43136. return;
  43137. }
  43138. audioTrack = audioTrack || {
  43139. timelineStartInfo: {
  43140. baseMediaDecodeTime: self.baseMediaDecodeTime
  43141. },
  43142. codec: 'adts',
  43143. type: 'audio'
  43144. }; // hook up the audio segment stream to the first track with aac data
  43145. pipeline.coalesceStream.numberOfTracks++;
  43146. pipeline.audioSegmentStream = new _AudioSegmentStream(audioTrack, options);
  43147. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  43148. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo')); // Set up the final part of the audio pipeline
  43149. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream); // emit pmt info
  43150. self.trigger('trackinfo', {
  43151. hasAudio: !!audioTrack,
  43152. hasVideo: !!videoTrack
  43153. });
  43154. }); // Re-emit any data coming from the coalesce stream to the outside world
  43155. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline
  43156. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  43157. addPipelineLogRetriggers(this, pipeline);
  43158. };
  43159. this.setupTsPipeline = function () {
  43160. var pipeline = {};
  43161. this.transmuxPipeline_ = pipeline;
  43162. pipeline.type = 'ts';
  43163. pipeline.metadataStream = new m2ts_1.MetadataStream(); // set up the parsing pipeline
  43164. pipeline.packetStream = new m2ts_1.TransportPacketStream();
  43165. pipeline.parseStream = new m2ts_1.TransportParseStream();
  43166. pipeline.elementaryStream = new m2ts_1.ElementaryStream();
  43167. pipeline.timestampRolloverStream = new m2ts_1.TimestampRolloverStream();
  43168. pipeline.adtsStream = new adts();
  43169. pipeline.h264Stream = new H264Stream();
  43170. pipeline.captionStream = new m2ts_1.CaptionStream(options);
  43171. pipeline.coalesceStream = new _CoalesceStream(options, pipeline.metadataStream);
  43172. pipeline.headOfPipeline = pipeline.packetStream; // disassemble MPEG2-TS packets into elementary streams
  43173. pipeline.packetStream.pipe(pipeline.parseStream).pipe(pipeline.elementaryStream).pipe(pipeline.timestampRolloverStream); // !!THIS ORDER IS IMPORTANT!!
  43174. // demux the streams
  43175. pipeline.timestampRolloverStream.pipe(pipeline.h264Stream);
  43176. pipeline.timestampRolloverStream.pipe(pipeline.adtsStream);
  43177. pipeline.timestampRolloverStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream); // Hook up CEA-608/708 caption stream
  43178. pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream);
  43179. pipeline.elementaryStream.on('data', function (data) {
  43180. var i;
  43181. if (data.type === 'metadata') {
  43182. i = data.tracks.length; // scan the tracks listed in the metadata
  43183. while (i--) {
  43184. if (!videoTrack && data.tracks[i].type === 'video') {
  43185. videoTrack = data.tracks[i];
  43186. videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  43187. } else if (!audioTrack && data.tracks[i].type === 'audio') {
  43188. audioTrack = data.tracks[i];
  43189. audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  43190. }
  43191. } // hook up the video segment stream to the first track with h264 data
  43192. if (videoTrack && !pipeline.videoSegmentStream) {
  43193. pipeline.coalesceStream.numberOfTracks++;
  43194. pipeline.videoSegmentStream = new _VideoSegmentStream(videoTrack, options);
  43195. pipeline.videoSegmentStream.on('log', self.getLogTrigger_('videoSegmentStream'));
  43196. pipeline.videoSegmentStream.on('timelineStartInfo', function (timelineStartInfo) {
  43197. // When video emits timelineStartInfo data after a flush, we forward that
  43198. // info to the AudioSegmentStream, if it exists, because video timeline
  43199. // data takes precedence. Do not do this if keepOriginalTimestamps is set,
  43200. // because this is a particularly subtle form of timestamp alteration.
  43201. if (audioTrack && !options.keepOriginalTimestamps) {
  43202. audioTrack.timelineStartInfo = timelineStartInfo; // On the first segment we trim AAC frames that exist before the
  43203. // very earliest DTS we have seen in video because Chrome will
  43204. // interpret any video track with a baseMediaDecodeTime that is
  43205. // non-zero as a gap.
  43206. pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);
  43207. }
  43208. });
  43209. pipeline.videoSegmentStream.on('processedGopsInfo', self.trigger.bind(self, 'gopInfo'));
  43210. pipeline.videoSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'videoSegmentTimingInfo'));
  43211. pipeline.videoSegmentStream.on('baseMediaDecodeTime', function (baseMediaDecodeTime) {
  43212. if (audioTrack) {
  43213. pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
  43214. }
  43215. });
  43216. pipeline.videoSegmentStream.on('timingInfo', self.trigger.bind(self, 'videoTimingInfo')); // Set up the final part of the video pipeline
  43217. pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream);
  43218. }
  43219. if (audioTrack && !pipeline.audioSegmentStream) {
  43220. // hook up the audio segment stream to the first track with aac data
  43221. pipeline.coalesceStream.numberOfTracks++;
  43222. pipeline.audioSegmentStream = new _AudioSegmentStream(audioTrack, options);
  43223. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  43224. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo'));
  43225. pipeline.audioSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'audioSegmentTimingInfo')); // Set up the final part of the audio pipeline
  43226. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream);
  43227. } // emit pmt info
  43228. self.trigger('trackinfo', {
  43229. hasAudio: !!audioTrack,
  43230. hasVideo: !!videoTrack
  43231. });
  43232. }
  43233. }); // Re-emit any data coming from the coalesce stream to the outside world
  43234. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  43235. pipeline.coalesceStream.on('id3Frame', function (id3Frame) {
  43236. id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
  43237. self.trigger('id3Frame', id3Frame);
  43238. });
  43239. pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption')); // Let the consumer know we have finished flushing the entire pipeline
  43240. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  43241. addPipelineLogRetriggers(this, pipeline);
  43242. }; // hook up the segment streams once track metadata is delivered
  43243. this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  43244. var pipeline = this.transmuxPipeline_;
  43245. if (!options.keepOriginalTimestamps) {
  43246. this.baseMediaDecodeTime = baseMediaDecodeTime;
  43247. }
  43248. if (audioTrack) {
  43249. audioTrack.timelineStartInfo.dts = undefined;
  43250. audioTrack.timelineStartInfo.pts = undefined;
  43251. trackDecodeInfo.clearDtsInfo(audioTrack);
  43252. if (pipeline.audioTimestampRolloverStream) {
  43253. pipeline.audioTimestampRolloverStream.discontinuity();
  43254. }
  43255. }
  43256. if (videoTrack) {
  43257. if (pipeline.videoSegmentStream) {
  43258. pipeline.videoSegmentStream.gopCache_ = [];
  43259. }
  43260. videoTrack.timelineStartInfo.dts = undefined;
  43261. videoTrack.timelineStartInfo.pts = undefined;
  43262. trackDecodeInfo.clearDtsInfo(videoTrack);
  43263. pipeline.captionStream.reset();
  43264. }
  43265. if (pipeline.timestampRolloverStream) {
  43266. pipeline.timestampRolloverStream.discontinuity();
  43267. }
  43268. };
  43269. this.setAudioAppendStart = function (timestamp) {
  43270. if (audioTrack) {
  43271. this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
  43272. }
  43273. };
  43274. this.setRemux = function (val) {
  43275. var pipeline = this.transmuxPipeline_;
  43276. options.remux = val;
  43277. if (pipeline && pipeline.coalesceStream) {
  43278. pipeline.coalesceStream.setRemux(val);
  43279. }
  43280. };
  43281. this.alignGopsWith = function (gopsToAlignWith) {
  43282. if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
  43283. this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
  43284. }
  43285. };
  43286. this.getLogTrigger_ = function (key) {
  43287. var self = this;
  43288. return function (event) {
  43289. event.stream = key;
  43290. self.trigger('log', event);
  43291. };
  43292. }; // feed incoming data to the front of the parsing pipeline
  43293. this.push = function (data) {
  43294. if (hasFlushed) {
  43295. var isAac = isLikelyAacData(data);
  43296. if (isAac && this.transmuxPipeline_.type !== 'aac') {
  43297. this.setupAacPipeline();
  43298. } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
  43299. this.setupTsPipeline();
  43300. }
  43301. hasFlushed = false;
  43302. }
  43303. this.transmuxPipeline_.headOfPipeline.push(data);
  43304. }; // flush any buffered data
  43305. this.flush = function () {
  43306. hasFlushed = true; // Start at the top of the pipeline and flush all pending work
  43307. this.transmuxPipeline_.headOfPipeline.flush();
  43308. };
  43309. this.endTimeline = function () {
  43310. this.transmuxPipeline_.headOfPipeline.endTimeline();
  43311. };
  43312. this.reset = function () {
  43313. if (this.transmuxPipeline_.headOfPipeline) {
  43314. this.transmuxPipeline_.headOfPipeline.reset();
  43315. }
  43316. }; // Caption data has to be reset when seeking outside buffered range
  43317. this.resetCaptions = function () {
  43318. if (this.transmuxPipeline_.captionStream) {
  43319. this.transmuxPipeline_.captionStream.reset();
  43320. }
  43321. };
  43322. };
  43323. _Transmuxer.prototype = new stream();
  43324. var transmuxer = {
  43325. Transmuxer: _Transmuxer,
  43326. VideoSegmentStream: _VideoSegmentStream,
  43327. AudioSegmentStream: _AudioSegmentStream,
  43328. AUDIO_PROPERTIES: audioProperties,
  43329. VIDEO_PROPERTIES: videoProperties,
  43330. // exported for testing
  43331. generateSegmentTimingInfo: generateSegmentTimingInfo
  43332. };
  43333. /**
  43334. * mux.js
  43335. *
  43336. * Copyright (c) Brightcove
  43337. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  43338. */
  43339. var toUnsigned$3 = function toUnsigned(value) {
  43340. return value >>> 0;
  43341. };
  43342. var toHexString$1 = function toHexString(value) {
  43343. return ('00' + value.toString(16)).slice(-2);
  43344. };
  43345. var bin = {
  43346. toUnsigned: toUnsigned$3,
  43347. toHexString: toHexString$1
  43348. };
  43349. var parseType$1 = function parseType(buffer) {
  43350. var result = '';
  43351. result += String.fromCharCode(buffer[0]);
  43352. result += String.fromCharCode(buffer[1]);
  43353. result += String.fromCharCode(buffer[2]);
  43354. result += String.fromCharCode(buffer[3]);
  43355. return result;
  43356. };
  43357. var parseType_1 = parseType$1;
  43358. var toUnsigned$2 = bin.toUnsigned;
  43359. var findBox = function findBox(data, path) {
  43360. var results = [],
  43361. i,
  43362. size,
  43363. type,
  43364. end,
  43365. subresults;
  43366. if (!path.length) {
  43367. // short-circuit the search for empty paths
  43368. return null;
  43369. }
  43370. for (i = 0; i < data.byteLength;) {
  43371. size = toUnsigned$2(data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]);
  43372. type = parseType_1(data.subarray(i + 4, i + 8));
  43373. end = size > 1 ? i + size : data.byteLength;
  43374. if (type === path[0]) {
  43375. if (path.length === 1) {
  43376. // this is the end of the path and we've found the box we were
  43377. // looking for
  43378. results.push(data.subarray(i + 8, end));
  43379. } else {
  43380. // recursively search for the next box along the path
  43381. subresults = findBox(data.subarray(i + 8, end), path.slice(1));
  43382. if (subresults.length) {
  43383. results = results.concat(subresults);
  43384. }
  43385. }
  43386. }
  43387. i = end;
  43388. } // we've finished searching all of data
  43389. return results;
  43390. };
  43391. var findBox_1 = findBox;
  43392. var toUnsigned$1 = bin.toUnsigned;
  43393. var getUint64$1 = numbers.getUint64;
  43394. var tfdt = function tfdt(data) {
  43395. var result = {
  43396. version: data[0],
  43397. flags: new Uint8Array(data.subarray(1, 4))
  43398. };
  43399. if (result.version === 1) {
  43400. result.baseMediaDecodeTime = getUint64$1(data.subarray(4));
  43401. } else {
  43402. result.baseMediaDecodeTime = toUnsigned$1(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]);
  43403. }
  43404. return result;
  43405. };
  43406. var parseTfdt = tfdt;
  43407. var parseSampleFlags = function parseSampleFlags(flags) {
  43408. return {
  43409. isLeading: (flags[0] & 0x0c) >>> 2,
  43410. dependsOn: flags[0] & 0x03,
  43411. isDependedOn: (flags[1] & 0xc0) >>> 6,
  43412. hasRedundancy: (flags[1] & 0x30) >>> 4,
  43413. paddingValue: (flags[1] & 0x0e) >>> 1,
  43414. isNonSyncSample: flags[1] & 0x01,
  43415. degradationPriority: flags[2] << 8 | flags[3]
  43416. };
  43417. };
  43418. var parseSampleFlags_1 = parseSampleFlags;
  43419. var trun = function trun(data) {
  43420. var result = {
  43421. version: data[0],
  43422. flags: new Uint8Array(data.subarray(1, 4)),
  43423. samples: []
  43424. },
  43425. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  43426. // Flag interpretation
  43427. dataOffsetPresent = result.flags[2] & 0x01,
  43428. // compare with 2nd byte of 0x1
  43429. firstSampleFlagsPresent = result.flags[2] & 0x04,
  43430. // compare with 2nd byte of 0x4
  43431. sampleDurationPresent = result.flags[1] & 0x01,
  43432. // compare with 2nd byte of 0x100
  43433. sampleSizePresent = result.flags[1] & 0x02,
  43434. // compare with 2nd byte of 0x200
  43435. sampleFlagsPresent = result.flags[1] & 0x04,
  43436. // compare with 2nd byte of 0x400
  43437. sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,
  43438. // compare with 2nd byte of 0x800
  43439. sampleCount = view.getUint32(4),
  43440. offset = 8,
  43441. sample;
  43442. if (dataOffsetPresent) {
  43443. // 32 bit signed integer
  43444. result.dataOffset = view.getInt32(offset);
  43445. offset += 4;
  43446. } // Overrides the flags for the first sample only. The order of
  43447. // optional values will be: duration, size, compositionTimeOffset
  43448. if (firstSampleFlagsPresent && sampleCount) {
  43449. sample = {
  43450. flags: parseSampleFlags_1(data.subarray(offset, offset + 4))
  43451. };
  43452. offset += 4;
  43453. if (sampleDurationPresent) {
  43454. sample.duration = view.getUint32(offset);
  43455. offset += 4;
  43456. }
  43457. if (sampleSizePresent) {
  43458. sample.size = view.getUint32(offset);
  43459. offset += 4;
  43460. }
  43461. if (sampleCompositionTimeOffsetPresent) {
  43462. if (result.version === 1) {
  43463. sample.compositionTimeOffset = view.getInt32(offset);
  43464. } else {
  43465. sample.compositionTimeOffset = view.getUint32(offset);
  43466. }
  43467. offset += 4;
  43468. }
  43469. result.samples.push(sample);
  43470. sampleCount--;
  43471. }
  43472. while (sampleCount--) {
  43473. sample = {};
  43474. if (sampleDurationPresent) {
  43475. sample.duration = view.getUint32(offset);
  43476. offset += 4;
  43477. }
  43478. if (sampleSizePresent) {
  43479. sample.size = view.getUint32(offset);
  43480. offset += 4;
  43481. }
  43482. if (sampleFlagsPresent) {
  43483. sample.flags = parseSampleFlags_1(data.subarray(offset, offset + 4));
  43484. offset += 4;
  43485. }
  43486. if (sampleCompositionTimeOffsetPresent) {
  43487. if (result.version === 1) {
  43488. sample.compositionTimeOffset = view.getInt32(offset);
  43489. } else {
  43490. sample.compositionTimeOffset = view.getUint32(offset);
  43491. }
  43492. offset += 4;
  43493. }
  43494. result.samples.push(sample);
  43495. }
  43496. return result;
  43497. };
  43498. var parseTrun = trun;
  43499. var tfhd = function tfhd(data) {
  43500. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  43501. result = {
  43502. version: data[0],
  43503. flags: new Uint8Array(data.subarray(1, 4)),
  43504. trackId: view.getUint32(4)
  43505. },
  43506. baseDataOffsetPresent = result.flags[2] & 0x01,
  43507. sampleDescriptionIndexPresent = result.flags[2] & 0x02,
  43508. defaultSampleDurationPresent = result.flags[2] & 0x08,
  43509. defaultSampleSizePresent = result.flags[2] & 0x10,
  43510. defaultSampleFlagsPresent = result.flags[2] & 0x20,
  43511. durationIsEmpty = result.flags[0] & 0x010000,
  43512. defaultBaseIsMoof = result.flags[0] & 0x020000,
  43513. i;
  43514. i = 8;
  43515. if (baseDataOffsetPresent) {
  43516. i += 4; // truncate top 4 bytes
  43517. // FIXME: should we read the full 64 bits?
  43518. result.baseDataOffset = view.getUint32(12);
  43519. i += 4;
  43520. }
  43521. if (sampleDescriptionIndexPresent) {
  43522. result.sampleDescriptionIndex = view.getUint32(i);
  43523. i += 4;
  43524. }
  43525. if (defaultSampleDurationPresent) {
  43526. result.defaultSampleDuration = view.getUint32(i);
  43527. i += 4;
  43528. }
  43529. if (defaultSampleSizePresent) {
  43530. result.defaultSampleSize = view.getUint32(i);
  43531. i += 4;
  43532. }
  43533. if (defaultSampleFlagsPresent) {
  43534. result.defaultSampleFlags = view.getUint32(i);
  43535. }
  43536. if (durationIsEmpty) {
  43537. result.durationIsEmpty = true;
  43538. }
  43539. if (!baseDataOffsetPresent && defaultBaseIsMoof) {
  43540. result.baseDataOffsetIsMoof = true;
  43541. }
  43542. return result;
  43543. };
  43544. var parseTfhd = tfhd;
  43545. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  43546. var win;
  43547. if (typeof window !== "undefined") {
  43548. win = window;
  43549. } else if (typeof commonjsGlobal !== "undefined") {
  43550. win = commonjsGlobal;
  43551. } else if (typeof self !== "undefined") {
  43552. win = self;
  43553. } else {
  43554. win = {};
  43555. }
  43556. var window_1 = win;
  43557. var discardEmulationPreventionBytes = captionPacketParser.discardEmulationPreventionBytes;
  43558. var CaptionStream = captionStream.CaptionStream;
  43559. /**
  43560. * Maps an offset in the mdat to a sample based on the the size of the samples.
  43561. * Assumes that `parseSamples` has been called first.
  43562. *
  43563. * @param {Number} offset - The offset into the mdat
  43564. * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
  43565. * @return {?Object} The matching sample, or null if no match was found.
  43566. *
  43567. * @see ISO-BMFF-12/2015, Section 8.8.8
  43568. **/
  43569. var mapToSample = function mapToSample(offset, samples) {
  43570. var approximateOffset = offset;
  43571. for (var i = 0; i < samples.length; i++) {
  43572. var sample = samples[i];
  43573. if (approximateOffset < sample.size) {
  43574. return sample;
  43575. }
  43576. approximateOffset -= sample.size;
  43577. }
  43578. return null;
  43579. };
  43580. /**
  43581. * Finds SEI nal units contained in a Media Data Box.
  43582. * Assumes that `parseSamples` has been called first.
  43583. *
  43584. * @param {Uint8Array} avcStream - The bytes of the mdat
  43585. * @param {Object[]} samples - The samples parsed out by `parseSamples`
  43586. * @param {Number} trackId - The trackId of this video track
  43587. * @return {Object[]} seiNals - the parsed SEI NALUs found.
  43588. * The contents of the seiNal should match what is expected by
  43589. * CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
  43590. *
  43591. * @see ISO-BMFF-12/2015, Section 8.1.1
  43592. * @see Rec. ITU-T H.264, 7.3.2.3.1
  43593. **/
  43594. var findSeiNals = function findSeiNals(avcStream, samples, trackId) {
  43595. var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
  43596. result = {
  43597. logs: [],
  43598. seiNals: []
  43599. },
  43600. seiNal,
  43601. i,
  43602. length,
  43603. lastMatchedSample;
  43604. for (i = 0; i + 4 < avcStream.length; i += length) {
  43605. length = avcView.getUint32(i);
  43606. i += 4; // Bail if this doesn't appear to be an H264 stream
  43607. if (length <= 0) {
  43608. continue;
  43609. }
  43610. switch (avcStream[i] & 0x1F) {
  43611. case 0x06:
  43612. var data = avcStream.subarray(i + 1, i + 1 + length);
  43613. var matchingSample = mapToSample(i, samples);
  43614. seiNal = {
  43615. nalUnitType: 'sei_rbsp',
  43616. size: length,
  43617. data: data,
  43618. escapedRBSP: discardEmulationPreventionBytes(data),
  43619. trackId: trackId
  43620. };
  43621. if (matchingSample) {
  43622. seiNal.pts = matchingSample.pts;
  43623. seiNal.dts = matchingSample.dts;
  43624. lastMatchedSample = matchingSample;
  43625. } else if (lastMatchedSample) {
  43626. // If a matching sample cannot be found, use the last
  43627. // sample's values as they should be as close as possible
  43628. seiNal.pts = lastMatchedSample.pts;
  43629. seiNal.dts = lastMatchedSample.dts;
  43630. } else {
  43631. result.logs.push({
  43632. level: 'warn',
  43633. message: 'We\'ve encountered a nal unit without data at ' + i + ' for trackId ' + trackId + '. See mux.js#223.'
  43634. });
  43635. break;
  43636. }
  43637. result.seiNals.push(seiNal);
  43638. break;
  43639. }
  43640. }
  43641. return result;
  43642. };
  43643. /**
  43644. * Parses sample information out of Track Run Boxes and calculates
  43645. * the absolute presentation and decode timestamps of each sample.
  43646. *
  43647. * @param {Array<Uint8Array>} truns - The Trun Run boxes to be parsed
  43648. * @param {Number|BigInt} baseMediaDecodeTime - base media decode time from tfdt
  43649. @see ISO-BMFF-12/2015, Section 8.8.12
  43650. * @param {Object} tfhd - The parsed Track Fragment Header
  43651. * @see inspect.parseTfhd
  43652. * @return {Object[]} the parsed samples
  43653. *
  43654. * @see ISO-BMFF-12/2015, Section 8.8.8
  43655. **/
  43656. var parseSamples = function parseSamples(truns, baseMediaDecodeTime, tfhd) {
  43657. var currentDts = baseMediaDecodeTime;
  43658. var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
  43659. var defaultSampleSize = tfhd.defaultSampleSize || 0;
  43660. var trackId = tfhd.trackId;
  43661. var allSamples = [];
  43662. truns.forEach(function (trun) {
  43663. // Note: We currently do not parse the sample table as well
  43664. // as the trun. It's possible some sources will require this.
  43665. // moov > trak > mdia > minf > stbl
  43666. var trackRun = parseTrun(trun);
  43667. var samples = trackRun.samples;
  43668. samples.forEach(function (sample) {
  43669. if (sample.duration === undefined) {
  43670. sample.duration = defaultSampleDuration;
  43671. }
  43672. if (sample.size === undefined) {
  43673. sample.size = defaultSampleSize;
  43674. }
  43675. sample.trackId = trackId;
  43676. sample.dts = currentDts;
  43677. if (sample.compositionTimeOffset === undefined) {
  43678. sample.compositionTimeOffset = 0;
  43679. }
  43680. if (typeof currentDts === 'bigint') {
  43681. sample.pts = currentDts + window_1.BigInt(sample.compositionTimeOffset);
  43682. currentDts += window_1.BigInt(sample.duration);
  43683. } else {
  43684. sample.pts = currentDts + sample.compositionTimeOffset;
  43685. currentDts += sample.duration;
  43686. }
  43687. });
  43688. allSamples = allSamples.concat(samples);
  43689. });
  43690. return allSamples;
  43691. };
  43692. /**
  43693. * Parses out caption nals from an FMP4 segment's video tracks.
  43694. *
  43695. * @param {Uint8Array} segment - The bytes of a single segment
  43696. * @param {Number} videoTrackId - The trackId of a video track in the segment
  43697. * @return {Object.<Number, Object[]>} A mapping of video trackId to
  43698. * a list of seiNals found in that track
  43699. **/
  43700. var parseCaptionNals = function parseCaptionNals(segment, videoTrackId) {
  43701. // To get the samples
  43702. var trafs = findBox_1(segment, ['moof', 'traf']); // To get SEI NAL units
  43703. var mdats = findBox_1(segment, ['mdat']);
  43704. var captionNals = {};
  43705. var mdatTrafPairs = []; // Pair up each traf with a mdat as moofs and mdats are in pairs
  43706. mdats.forEach(function (mdat, index) {
  43707. var matchingTraf = trafs[index];
  43708. mdatTrafPairs.push({
  43709. mdat: mdat,
  43710. traf: matchingTraf
  43711. });
  43712. });
  43713. mdatTrafPairs.forEach(function (pair) {
  43714. var mdat = pair.mdat;
  43715. var traf = pair.traf;
  43716. var tfhd = findBox_1(traf, ['tfhd']); // Exactly 1 tfhd per traf
  43717. var headerInfo = parseTfhd(tfhd[0]);
  43718. var trackId = headerInfo.trackId;
  43719. var tfdt = findBox_1(traf, ['tfdt']); // Either 0 or 1 tfdt per traf
  43720. var baseMediaDecodeTime = tfdt.length > 0 ? parseTfdt(tfdt[0]).baseMediaDecodeTime : 0;
  43721. var truns = findBox_1(traf, ['trun']);
  43722. var samples;
  43723. var result; // Only parse video data for the chosen video track
  43724. if (videoTrackId === trackId && truns.length > 0) {
  43725. samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);
  43726. result = findSeiNals(mdat, samples, trackId);
  43727. if (!captionNals[trackId]) {
  43728. captionNals[trackId] = {
  43729. seiNals: [],
  43730. logs: []
  43731. };
  43732. }
  43733. captionNals[trackId].seiNals = captionNals[trackId].seiNals.concat(result.seiNals);
  43734. captionNals[trackId].logs = captionNals[trackId].logs.concat(result.logs);
  43735. }
  43736. });
  43737. return captionNals;
  43738. };
  43739. /**
  43740. * Parses out inband captions from an MP4 container and returns
  43741. * caption objects that can be used by WebVTT and the TextTrack API.
  43742. * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
  43743. * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
  43744. * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
  43745. *
  43746. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  43747. * @param {Number} trackId - The id of the video track to parse
  43748. * @param {Number} timescale - The timescale for the video track from the init segment
  43749. *
  43750. * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
  43751. * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
  43752. * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
  43753. * @return {String} parsedCaptions[].text - The visible content of the caption
  43754. **/
  43755. var parseEmbeddedCaptions = function parseEmbeddedCaptions(segment, trackId, timescale) {
  43756. var captionNals; // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  43757. if (trackId === null) {
  43758. return null;
  43759. }
  43760. captionNals = parseCaptionNals(segment, trackId);
  43761. var trackNals = captionNals[trackId] || {};
  43762. return {
  43763. seiNals: trackNals.seiNals,
  43764. logs: trackNals.logs,
  43765. timescale: timescale
  43766. };
  43767. };
  43768. /**
  43769. * Converts SEI NALUs into captions that can be used by video.js
  43770. **/
  43771. var CaptionParser = function CaptionParser() {
  43772. var isInitialized = false;
  43773. var captionStream; // Stores segments seen before trackId and timescale are set
  43774. var segmentCache; // Stores video track ID of the track being parsed
  43775. var trackId; // Stores the timescale of the track being parsed
  43776. var timescale; // Stores captions parsed so far
  43777. var parsedCaptions; // Stores whether we are receiving partial data or not
  43778. var parsingPartial;
  43779. /**
  43780. * A method to indicate whether a CaptionParser has been initalized
  43781. * @returns {Boolean}
  43782. **/
  43783. this.isInitialized = function () {
  43784. return isInitialized;
  43785. };
  43786. /**
  43787. * Initializes the underlying CaptionStream, SEI NAL parsing
  43788. * and management, and caption collection
  43789. **/
  43790. this.init = function (options) {
  43791. captionStream = new CaptionStream();
  43792. isInitialized = true;
  43793. parsingPartial = options ? options.isPartial : false; // Collect dispatched captions
  43794. captionStream.on('data', function (event) {
  43795. // Convert to seconds in the source's timescale
  43796. event.startTime = event.startPts / timescale;
  43797. event.endTime = event.endPts / timescale;
  43798. parsedCaptions.captions.push(event);
  43799. parsedCaptions.captionStreams[event.stream] = true;
  43800. });
  43801. captionStream.on('log', function (log) {
  43802. parsedCaptions.logs.push(log);
  43803. });
  43804. };
  43805. /**
  43806. * Determines if a new video track will be selected
  43807. * or if the timescale changed
  43808. * @return {Boolean}
  43809. **/
  43810. this.isNewInit = function (videoTrackIds, timescales) {
  43811. if (videoTrackIds && videoTrackIds.length === 0 || timescales && typeof timescales === 'object' && Object.keys(timescales).length === 0) {
  43812. return false;
  43813. }
  43814. return trackId !== videoTrackIds[0] || timescale !== timescales[trackId];
  43815. };
  43816. /**
  43817. * Parses out SEI captions and interacts with underlying
  43818. * CaptionStream to return dispatched captions
  43819. *
  43820. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  43821. * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
  43822. * @param {Object.<Number, Number>} timescales - The timescales found in the init segment
  43823. * @see parseEmbeddedCaptions
  43824. * @see m2ts/caption-stream.js
  43825. **/
  43826. this.parse = function (segment, videoTrackIds, timescales) {
  43827. var parsedData;
  43828. if (!this.isInitialized()) {
  43829. return null; // This is not likely to be a video segment
  43830. } else if (!videoTrackIds || !timescales) {
  43831. return null;
  43832. } else if (this.isNewInit(videoTrackIds, timescales)) {
  43833. // Use the first video track only as there is no
  43834. // mechanism to switch to other video tracks
  43835. trackId = videoTrackIds[0];
  43836. timescale = timescales[trackId]; // If an init segment has not been seen yet, hold onto segment
  43837. // data until we have one.
  43838. // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  43839. } else if (trackId === null || !timescale) {
  43840. segmentCache.push(segment);
  43841. return null;
  43842. } // Now that a timescale and trackId is set, parse cached segments
  43843. while (segmentCache.length > 0) {
  43844. var cachedSegment = segmentCache.shift();
  43845. this.parse(cachedSegment, videoTrackIds, timescales);
  43846. }
  43847. parsedData = parseEmbeddedCaptions(segment, trackId, timescale);
  43848. if (parsedData && parsedData.logs) {
  43849. parsedCaptions.logs = parsedCaptions.logs.concat(parsedData.logs);
  43850. }
  43851. if (parsedData === null || !parsedData.seiNals) {
  43852. if (parsedCaptions.logs.length) {
  43853. return {
  43854. logs: parsedCaptions.logs,
  43855. captions: [],
  43856. captionStreams: []
  43857. };
  43858. }
  43859. return null;
  43860. }
  43861. this.pushNals(parsedData.seiNals); // Force the parsed captions to be dispatched
  43862. this.flushStream();
  43863. return parsedCaptions;
  43864. };
  43865. /**
  43866. * Pushes SEI NALUs onto CaptionStream
  43867. * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
  43868. * Assumes that `parseCaptionNals` has been called first
  43869. * @see m2ts/caption-stream.js
  43870. **/
  43871. this.pushNals = function (nals) {
  43872. if (!this.isInitialized() || !nals || nals.length === 0) {
  43873. return null;
  43874. }
  43875. nals.forEach(function (nal) {
  43876. captionStream.push(nal);
  43877. });
  43878. };
  43879. /**
  43880. * Flushes underlying CaptionStream to dispatch processed, displayable captions
  43881. * @see m2ts/caption-stream.js
  43882. **/
  43883. this.flushStream = function () {
  43884. if (!this.isInitialized()) {
  43885. return null;
  43886. }
  43887. if (!parsingPartial) {
  43888. captionStream.flush();
  43889. } else {
  43890. captionStream.partialFlush();
  43891. }
  43892. };
  43893. /**
  43894. * Reset caption buckets for new data
  43895. **/
  43896. this.clearParsedCaptions = function () {
  43897. parsedCaptions.captions = [];
  43898. parsedCaptions.captionStreams = {};
  43899. parsedCaptions.logs = [];
  43900. };
  43901. /**
  43902. * Resets underlying CaptionStream
  43903. * @see m2ts/caption-stream.js
  43904. **/
  43905. this.resetCaptionStream = function () {
  43906. if (!this.isInitialized()) {
  43907. return null;
  43908. }
  43909. captionStream.reset();
  43910. };
  43911. /**
  43912. * Convenience method to clear all captions flushed from the
  43913. * CaptionStream and still being parsed
  43914. * @see m2ts/caption-stream.js
  43915. **/
  43916. this.clearAllCaptions = function () {
  43917. this.clearParsedCaptions();
  43918. this.resetCaptionStream();
  43919. };
  43920. /**
  43921. * Reset caption parser
  43922. **/
  43923. this.reset = function () {
  43924. segmentCache = [];
  43925. trackId = null;
  43926. timescale = null;
  43927. if (!parsedCaptions) {
  43928. parsedCaptions = {
  43929. captions: [],
  43930. // CC1, CC2, CC3, CC4
  43931. captionStreams: {},
  43932. logs: []
  43933. };
  43934. } else {
  43935. this.clearParsedCaptions();
  43936. }
  43937. this.resetCaptionStream();
  43938. };
  43939. this.reset();
  43940. };
  43941. var captionParser = CaptionParser;
  43942. var toUnsigned = bin.toUnsigned;
  43943. var toHexString = bin.toHexString;
  43944. var getUint64 = numbers.getUint64;
  43945. var timescale, startTime, compositionStartTime, getVideoTrackIds, getTracks, getTimescaleFromMediaHeader;
  43946. /**
  43947. * Parses an MP4 initialization segment and extracts the timescale
  43948. * values for any declared tracks. Timescale values indicate the
  43949. * number of clock ticks per second to assume for time-based values
  43950. * elsewhere in the MP4.
  43951. *
  43952. * To determine the start time of an MP4, you need two pieces of
  43953. * information: the timescale unit and the earliest base media decode
  43954. * time. Multiple timescales can be specified within an MP4 but the
  43955. * base media decode time is always expressed in the timescale from
  43956. * the media header box for the track:
  43957. * ```
  43958. * moov > trak > mdia > mdhd.timescale
  43959. * ```
  43960. * @param init {Uint8Array} the bytes of the init segment
  43961. * @return {object} a hash of track ids to timescale values or null if
  43962. * the init segment is malformed.
  43963. */
  43964. timescale = function timescale(init) {
  43965. var result = {},
  43966. traks = findBox_1(init, ['moov', 'trak']); // mdhd timescale
  43967. return traks.reduce(function (result, trak) {
  43968. var tkhd, version, index, id, mdhd;
  43969. tkhd = findBox_1(trak, ['tkhd'])[0];
  43970. if (!tkhd) {
  43971. return null;
  43972. }
  43973. version = tkhd[0];
  43974. index = version === 0 ? 12 : 20;
  43975. id = toUnsigned(tkhd[index] << 24 | tkhd[index + 1] << 16 | tkhd[index + 2] << 8 | tkhd[index + 3]);
  43976. mdhd = findBox_1(trak, ['mdia', 'mdhd'])[0];
  43977. if (!mdhd) {
  43978. return null;
  43979. }
  43980. version = mdhd[0];
  43981. index = version === 0 ? 12 : 20;
  43982. result[id] = toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  43983. return result;
  43984. }, result);
  43985. };
  43986. /**
  43987. * Determine the base media decode start time, in seconds, for an MP4
  43988. * fragment. If multiple fragments are specified, the earliest time is
  43989. * returned.
  43990. *
  43991. * The base media decode time can be parsed from track fragment
  43992. * metadata:
  43993. * ```
  43994. * moof > traf > tfdt.baseMediaDecodeTime
  43995. * ```
  43996. * It requires the timescale value from the mdhd to interpret.
  43997. *
  43998. * @param timescale {object} a hash of track ids to timescale values.
  43999. * @return {number} the earliest base media decode start time for the
  44000. * fragment, in seconds
  44001. */
  44002. startTime = function startTime(timescale, fragment) {
  44003. var trafs; // we need info from two childrend of each track fragment box
  44004. trafs = findBox_1(fragment, ['moof', 'traf']); // determine the start times for each track
  44005. var lowestTime = trafs.reduce(function (acc, traf) {
  44006. var tfhd = findBox_1(traf, ['tfhd'])[0]; // get the track id from the tfhd
  44007. var id = toUnsigned(tfhd[4] << 24 | tfhd[5] << 16 | tfhd[6] << 8 | tfhd[7]); // assume a 90kHz clock if no timescale was specified
  44008. var scale = timescale[id] || 90e3; // get the base media decode time from the tfdt
  44009. var tfdt = findBox_1(traf, ['tfdt'])[0];
  44010. var dv = new DataView(tfdt.buffer, tfdt.byteOffset, tfdt.byteLength);
  44011. var baseTime; // version 1 is 64 bit
  44012. if (tfdt[0] === 1) {
  44013. baseTime = getUint64(tfdt.subarray(4, 12));
  44014. } else {
  44015. baseTime = dv.getUint32(4);
  44016. } // convert base time to seconds if it is a valid number.
  44017. var seconds;
  44018. if (typeof baseTime === 'bigint') {
  44019. seconds = baseTime / window_1.BigInt(scale);
  44020. } else if (typeof baseTime === 'number' && !isNaN(baseTime)) {
  44021. seconds = baseTime / scale;
  44022. }
  44023. if (seconds < Number.MAX_SAFE_INTEGER) {
  44024. seconds = Number(seconds);
  44025. }
  44026. if (seconds < acc) {
  44027. acc = seconds;
  44028. }
  44029. return acc;
  44030. }, Infinity);
  44031. return typeof lowestTime === 'bigint' || isFinite(lowestTime) ? lowestTime : 0;
  44032. };
  44033. /**
  44034. * Determine the composition start, in seconds, for an MP4
  44035. * fragment.
  44036. *
  44037. * The composition start time of a fragment can be calculated using the base
  44038. * media decode time, composition time offset, and timescale, as follows:
  44039. *
  44040. * compositionStartTime = (baseMediaDecodeTime + compositionTimeOffset) / timescale
  44041. *
  44042. * All of the aforementioned information is contained within a media fragment's
  44043. * `traf` box, except for timescale info, which comes from the initialization
  44044. * segment, so a track id (also contained within a `traf`) is also necessary to
  44045. * associate it with a timescale
  44046. *
  44047. *
  44048. * @param timescales {object} - a hash of track ids to timescale values.
  44049. * @param fragment {Unit8Array} - the bytes of a media segment
  44050. * @return {number} the composition start time for the fragment, in seconds
  44051. **/
  44052. compositionStartTime = function compositionStartTime(timescales, fragment) {
  44053. var trafBoxes = findBox_1(fragment, ['moof', 'traf']);
  44054. var baseMediaDecodeTime = 0;
  44055. var compositionTimeOffset = 0;
  44056. var trackId;
  44057. if (trafBoxes && trafBoxes.length) {
  44058. // The spec states that track run samples contained within a `traf` box are contiguous, but
  44059. // it does not explicitly state whether the `traf` boxes themselves are contiguous.
  44060. // We will assume that they are, so we only need the first to calculate start time.
  44061. var tfhd = findBox_1(trafBoxes[0], ['tfhd'])[0];
  44062. var trun = findBox_1(trafBoxes[0], ['trun'])[0];
  44063. var tfdt = findBox_1(trafBoxes[0], ['tfdt'])[0];
  44064. if (tfhd) {
  44065. var parsedTfhd = parseTfhd(tfhd);
  44066. trackId = parsedTfhd.trackId;
  44067. }
  44068. if (tfdt) {
  44069. var parsedTfdt = parseTfdt(tfdt);
  44070. baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;
  44071. }
  44072. if (trun) {
  44073. var parsedTrun = parseTrun(trun);
  44074. if (parsedTrun.samples && parsedTrun.samples.length) {
  44075. compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;
  44076. }
  44077. }
  44078. } // Get timescale for this specific track. Assume a 90kHz clock if no timescale was
  44079. // specified.
  44080. var timescale = timescales[trackId] || 90e3; // return the composition start time, in seconds
  44081. if (typeof baseMediaDecodeTime === 'bigint') {
  44082. compositionTimeOffset = window_1.BigInt(compositionTimeOffset);
  44083. timescale = window_1.BigInt(timescale);
  44084. }
  44085. var result = (baseMediaDecodeTime + compositionTimeOffset) / timescale;
  44086. if (typeof result === 'bigint' && result < Number.MAX_SAFE_INTEGER) {
  44087. result = Number(result);
  44088. }
  44089. return result;
  44090. };
  44091. /**
  44092. * Find the trackIds of the video tracks in this source.
  44093. * Found by parsing the Handler Reference and Track Header Boxes:
  44094. * moov > trak > mdia > hdlr
  44095. * moov > trak > tkhd
  44096. *
  44097. * @param {Uint8Array} init - The bytes of the init segment for this source
  44098. * @return {Number[]} A list of trackIds
  44099. *
  44100. * @see ISO-BMFF-12/2015, Section 8.4.3
  44101. **/
  44102. getVideoTrackIds = function getVideoTrackIds(init) {
  44103. var traks = findBox_1(init, ['moov', 'trak']);
  44104. var videoTrackIds = [];
  44105. traks.forEach(function (trak) {
  44106. var hdlrs = findBox_1(trak, ['mdia', 'hdlr']);
  44107. var tkhds = findBox_1(trak, ['tkhd']);
  44108. hdlrs.forEach(function (hdlr, index) {
  44109. var handlerType = parseType_1(hdlr.subarray(8, 12));
  44110. var tkhd = tkhds[index];
  44111. var view;
  44112. var version;
  44113. var trackId;
  44114. if (handlerType === 'vide') {
  44115. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  44116. version = view.getUint8(0);
  44117. trackId = version === 0 ? view.getUint32(12) : view.getUint32(20);
  44118. videoTrackIds.push(trackId);
  44119. }
  44120. });
  44121. });
  44122. return videoTrackIds;
  44123. };
  44124. getTimescaleFromMediaHeader = function getTimescaleFromMediaHeader(mdhd) {
  44125. // mdhd is a FullBox, meaning it will have its own version as the first byte
  44126. var version = mdhd[0];
  44127. var index = version === 0 ? 12 : 20;
  44128. return toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  44129. };
  44130. /**
  44131. * Get all the video, audio, and hint tracks from a non fragmented
  44132. * mp4 segment
  44133. */
  44134. getTracks = function getTracks(init) {
  44135. var traks = findBox_1(init, ['moov', 'trak']);
  44136. var tracks = [];
  44137. traks.forEach(function (trak) {
  44138. var track = {};
  44139. var tkhd = findBox_1(trak, ['tkhd'])[0];
  44140. var view, tkhdVersion; // id
  44141. if (tkhd) {
  44142. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  44143. tkhdVersion = view.getUint8(0);
  44144. track.id = tkhdVersion === 0 ? view.getUint32(12) : view.getUint32(20);
  44145. }
  44146. var hdlr = findBox_1(trak, ['mdia', 'hdlr'])[0]; // type
  44147. if (hdlr) {
  44148. var type = parseType_1(hdlr.subarray(8, 12));
  44149. if (type === 'vide') {
  44150. track.type = 'video';
  44151. } else if (type === 'soun') {
  44152. track.type = 'audio';
  44153. } else {
  44154. track.type = type;
  44155. }
  44156. } // codec
  44157. var stsd = findBox_1(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  44158. if (stsd) {
  44159. var sampleDescriptions = stsd.subarray(8); // gives the codec type string
  44160. track.codec = parseType_1(sampleDescriptions.subarray(4, 8));
  44161. var codecBox = findBox_1(sampleDescriptions, [track.codec])[0];
  44162. var codecConfig, codecConfigType;
  44163. if (codecBox) {
  44164. // https://tools.ietf.org/html/rfc6381#section-3.3
  44165. if (/^[asm]vc[1-9]$/i.test(track.codec)) {
  44166. // we don't need anything but the "config" parameter of the
  44167. // avc1 codecBox
  44168. codecConfig = codecBox.subarray(78);
  44169. codecConfigType = parseType_1(codecConfig.subarray(4, 8));
  44170. if (codecConfigType === 'avcC' && codecConfig.length > 11) {
  44171. track.codec += '.'; // left padded with zeroes for single digit hex
  44172. // profile idc
  44173. track.codec += toHexString(codecConfig[9]); // the byte containing the constraint_set flags
  44174. track.codec += toHexString(codecConfig[10]); // level idc
  44175. track.codec += toHexString(codecConfig[11]);
  44176. } else {
  44177. // TODO: show a warning that we couldn't parse the codec
  44178. // and are using the default
  44179. track.codec = 'avc1.4d400d';
  44180. }
  44181. } else if (/^mp4[a,v]$/i.test(track.codec)) {
  44182. // we do not need anything but the streamDescriptor of the mp4a codecBox
  44183. codecConfig = codecBox.subarray(28);
  44184. codecConfigType = parseType_1(codecConfig.subarray(4, 8));
  44185. if (codecConfigType === 'esds' && codecConfig.length > 20 && codecConfig[19] !== 0) {
  44186. track.codec += '.' + toHexString(codecConfig[19]); // this value is only a single digit
  44187. track.codec += '.' + toHexString(codecConfig[20] >>> 2 & 0x3f).replace(/^0/, '');
  44188. } else {
  44189. // TODO: show a warning that we couldn't parse the codec
  44190. // and are using the default
  44191. track.codec = 'mp4a.40.2';
  44192. }
  44193. } else {
  44194. // flac, opus, etc
  44195. track.codec = track.codec.toLowerCase();
  44196. }
  44197. }
  44198. }
  44199. var mdhd = findBox_1(trak, ['mdia', 'mdhd'])[0];
  44200. if (mdhd) {
  44201. track.timescale = getTimescaleFromMediaHeader(mdhd);
  44202. }
  44203. tracks.push(track);
  44204. });
  44205. return tracks;
  44206. };
  44207. var probe$2 = {
  44208. // export mp4 inspector's findBox and parseType for backwards compatibility
  44209. findBox: findBox_1,
  44210. parseType: parseType_1,
  44211. timescale: timescale,
  44212. startTime: startTime,
  44213. compositionStartTime: compositionStartTime,
  44214. videoTrackIds: getVideoTrackIds,
  44215. tracks: getTracks,
  44216. getTimescaleFromMediaHeader: getTimescaleFromMediaHeader
  44217. };
  44218. var parsePid = function parsePid(packet) {
  44219. var pid = packet[1] & 0x1f;
  44220. pid <<= 8;
  44221. pid |= packet[2];
  44222. return pid;
  44223. };
  44224. var parsePayloadUnitStartIndicator = function parsePayloadUnitStartIndicator(packet) {
  44225. return !!(packet[1] & 0x40);
  44226. };
  44227. var parseAdaptionField = function parseAdaptionField(packet) {
  44228. var offset = 0; // if an adaption field is present, its length is specified by the
  44229. // fifth byte of the TS packet header. The adaptation field is
  44230. // used to add stuffing to PES packets that don't fill a complete
  44231. // TS packet, and to specify some forms of timing and control data
  44232. // that we do not currently use.
  44233. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  44234. offset += packet[4] + 1;
  44235. }
  44236. return offset;
  44237. };
  44238. var parseType = function parseType(packet, pmtPid) {
  44239. var pid = parsePid(packet);
  44240. if (pid === 0) {
  44241. return 'pat';
  44242. } else if (pid === pmtPid) {
  44243. return 'pmt';
  44244. } else if (pmtPid) {
  44245. return 'pes';
  44246. }
  44247. return null;
  44248. };
  44249. var parsePat = function parsePat(packet) {
  44250. var pusi = parsePayloadUnitStartIndicator(packet);
  44251. var offset = 4 + parseAdaptionField(packet);
  44252. if (pusi) {
  44253. offset += packet[offset] + 1;
  44254. }
  44255. return (packet[offset + 10] & 0x1f) << 8 | packet[offset + 11];
  44256. };
  44257. var parsePmt = function parsePmt(packet) {
  44258. var programMapTable = {};
  44259. var pusi = parsePayloadUnitStartIndicator(packet);
  44260. var payloadOffset = 4 + parseAdaptionField(packet);
  44261. if (pusi) {
  44262. payloadOffset += packet[payloadOffset] + 1;
  44263. } // PMTs can be sent ahead of the time when they should actually
  44264. // take effect. We don't believe this should ever be the case
  44265. // for HLS but we'll ignore "forward" PMT declarations if we see
  44266. // them. Future PMT declarations have the current_next_indicator
  44267. // set to zero.
  44268. if (!(packet[payloadOffset + 5] & 0x01)) {
  44269. return;
  44270. }
  44271. var sectionLength, tableEnd, programInfoLength; // the mapping table ends at the end of the current section
  44272. sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];
  44273. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  44274. // long the program info descriptors are
  44275. programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11]; // advance the offset to the first entry in the mapping table
  44276. var offset = 12 + programInfoLength;
  44277. while (offset < tableEnd) {
  44278. var i = payloadOffset + offset; // add an entry that maps the elementary_pid to the stream_type
  44279. programMapTable[(packet[i + 1] & 0x1F) << 8 | packet[i + 2]] = packet[i]; // move to the next table entry
  44280. // skip past the elementary stream descriptors, if present
  44281. offset += ((packet[i + 3] & 0x0F) << 8 | packet[i + 4]) + 5;
  44282. }
  44283. return programMapTable;
  44284. };
  44285. var parsePesType = function parsePesType(packet, programMapTable) {
  44286. var pid = parsePid(packet);
  44287. var type = programMapTable[pid];
  44288. switch (type) {
  44289. case streamTypes.H264_STREAM_TYPE:
  44290. return 'video';
  44291. case streamTypes.ADTS_STREAM_TYPE:
  44292. return 'audio';
  44293. case streamTypes.METADATA_STREAM_TYPE:
  44294. return 'timed-metadata';
  44295. default:
  44296. return null;
  44297. }
  44298. };
  44299. var parsePesTime = function parsePesTime(packet) {
  44300. var pusi = parsePayloadUnitStartIndicator(packet);
  44301. if (!pusi) {
  44302. return null;
  44303. }
  44304. var offset = 4 + parseAdaptionField(packet);
  44305. if (offset >= packet.byteLength) {
  44306. // From the H 222.0 MPEG-TS spec
  44307. // "For transport stream packets carrying PES packets, stuffing is needed when there
  44308. // is insufficient PES packet data to completely fill the transport stream packet
  44309. // payload bytes. Stuffing is accomplished by defining an adaptation field longer than
  44310. // the sum of the lengths of the data elements in it, so that the payload bytes
  44311. // remaining after the adaptation field exactly accommodates the available PES packet
  44312. // data."
  44313. //
  44314. // If the offset is >= the length of the packet, then the packet contains no data
  44315. // and instead is just adaption field stuffing bytes
  44316. return null;
  44317. }
  44318. var pes = null;
  44319. var ptsDtsFlags; // PES packets may be annotated with a PTS value, or a PTS value
  44320. // and a DTS value. Determine what combination of values is
  44321. // available to work with.
  44322. ptsDtsFlags = packet[offset + 7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  44323. // performs all bitwise operations on 32-bit integers but javascript
  44324. // supports a much greater range (52-bits) of integer using standard
  44325. // mathematical operations.
  44326. // We construct a 31-bit value using bitwise operators over the 31
  44327. // most significant bits and then multiply by 4 (equal to a left-shift
  44328. // of 2) before we add the final 2 least significant bits of the
  44329. // timestamp (equal to an OR.)
  44330. if (ptsDtsFlags & 0xC0) {
  44331. pes = {}; // the PTS and DTS are not written out directly. For information
  44332. // on how they are encoded, see
  44333. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  44334. pes.pts = (packet[offset + 9] & 0x0E) << 27 | (packet[offset + 10] & 0xFF) << 20 | (packet[offset + 11] & 0xFE) << 12 | (packet[offset + 12] & 0xFF) << 5 | (packet[offset + 13] & 0xFE) >>> 3;
  44335. pes.pts *= 4; // Left shift by 2
  44336. pes.pts += (packet[offset + 13] & 0x06) >>> 1; // OR by the two LSBs
  44337. pes.dts = pes.pts;
  44338. if (ptsDtsFlags & 0x40) {
  44339. pes.dts = (packet[offset + 14] & 0x0E) << 27 | (packet[offset + 15] & 0xFF) << 20 | (packet[offset + 16] & 0xFE) << 12 | (packet[offset + 17] & 0xFF) << 5 | (packet[offset + 18] & 0xFE) >>> 3;
  44340. pes.dts *= 4; // Left shift by 2
  44341. pes.dts += (packet[offset + 18] & 0x06) >>> 1; // OR by the two LSBs
  44342. }
  44343. }
  44344. return pes;
  44345. };
  44346. var parseNalUnitType = function parseNalUnitType(type) {
  44347. switch (type) {
  44348. case 0x05:
  44349. return 'slice_layer_without_partitioning_rbsp_idr';
  44350. case 0x06:
  44351. return 'sei_rbsp';
  44352. case 0x07:
  44353. return 'seq_parameter_set_rbsp';
  44354. case 0x08:
  44355. return 'pic_parameter_set_rbsp';
  44356. case 0x09:
  44357. return 'access_unit_delimiter_rbsp';
  44358. default:
  44359. return null;
  44360. }
  44361. };
  44362. var videoPacketContainsKeyFrame = function videoPacketContainsKeyFrame(packet) {
  44363. var offset = 4 + parseAdaptionField(packet);
  44364. var frameBuffer = packet.subarray(offset);
  44365. var frameI = 0;
  44366. var frameSyncPoint = 0;
  44367. var foundKeyFrame = false;
  44368. var nalType; // advance the sync point to a NAL start, if necessary
  44369. for (; frameSyncPoint < frameBuffer.byteLength - 3; frameSyncPoint++) {
  44370. if (frameBuffer[frameSyncPoint + 2] === 1) {
  44371. // the sync point is properly aligned
  44372. frameI = frameSyncPoint + 5;
  44373. break;
  44374. }
  44375. }
  44376. while (frameI < frameBuffer.byteLength) {
  44377. // look at the current byte to determine if we've hit the end of
  44378. // a NAL unit boundary
  44379. switch (frameBuffer[frameI]) {
  44380. case 0:
  44381. // skip past non-sync sequences
  44382. if (frameBuffer[frameI - 1] !== 0) {
  44383. frameI += 2;
  44384. break;
  44385. } else if (frameBuffer[frameI - 2] !== 0) {
  44386. frameI++;
  44387. break;
  44388. }
  44389. if (frameSyncPoint + 3 !== frameI - 2) {
  44390. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  44391. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  44392. foundKeyFrame = true;
  44393. }
  44394. } // drop trailing zeroes
  44395. do {
  44396. frameI++;
  44397. } while (frameBuffer[frameI] !== 1 && frameI < frameBuffer.length);
  44398. frameSyncPoint = frameI - 2;
  44399. frameI += 3;
  44400. break;
  44401. case 1:
  44402. // skip past non-sync sequences
  44403. if (frameBuffer[frameI - 1] !== 0 || frameBuffer[frameI - 2] !== 0) {
  44404. frameI += 3;
  44405. break;
  44406. }
  44407. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  44408. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  44409. foundKeyFrame = true;
  44410. }
  44411. frameSyncPoint = frameI - 2;
  44412. frameI += 3;
  44413. break;
  44414. default:
  44415. // the current byte isn't a one or zero, so it cannot be part
  44416. // of a sync sequence
  44417. frameI += 3;
  44418. break;
  44419. }
  44420. }
  44421. frameBuffer = frameBuffer.subarray(frameSyncPoint);
  44422. frameI -= frameSyncPoint;
  44423. frameSyncPoint = 0; // parse the final nal
  44424. if (frameBuffer && frameBuffer.byteLength > 3) {
  44425. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  44426. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  44427. foundKeyFrame = true;
  44428. }
  44429. }
  44430. return foundKeyFrame;
  44431. };
  44432. var probe$1 = {
  44433. parseType: parseType,
  44434. parsePat: parsePat,
  44435. parsePmt: parsePmt,
  44436. parsePayloadUnitStartIndicator: parsePayloadUnitStartIndicator,
  44437. parsePesType: parsePesType,
  44438. parsePesTime: parsePesTime,
  44439. videoPacketContainsKeyFrame: videoPacketContainsKeyFrame
  44440. };
  44441. var handleRollover = timestampRolloverStream.handleRollover;
  44442. var probe = {};
  44443. probe.ts = probe$1;
  44444. probe.aac = utils;
  44445. var ONE_SECOND_IN_TS = clock.ONE_SECOND_IN_TS;
  44446. var MP2T_PACKET_LENGTH = 188,
  44447. // bytes
  44448. SYNC_BYTE = 0x47;
  44449. /**
  44450. * walks through segment data looking for pat and pmt packets to parse out
  44451. * program map table information
  44452. */
  44453. var parsePsi_ = function parsePsi_(bytes, pmt) {
  44454. var startIndex = 0,
  44455. endIndex = MP2T_PACKET_LENGTH,
  44456. packet,
  44457. type;
  44458. while (endIndex < bytes.byteLength) {
  44459. // Look for a pair of start and end sync bytes in the data..
  44460. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  44461. // We found a packet
  44462. packet = bytes.subarray(startIndex, endIndex);
  44463. type = probe.ts.parseType(packet, pmt.pid);
  44464. switch (type) {
  44465. case 'pat':
  44466. pmt.pid = probe.ts.parsePat(packet);
  44467. break;
  44468. case 'pmt':
  44469. var table = probe.ts.parsePmt(packet);
  44470. pmt.table = pmt.table || {};
  44471. Object.keys(table).forEach(function (key) {
  44472. pmt.table[key] = table[key];
  44473. });
  44474. break;
  44475. }
  44476. startIndex += MP2T_PACKET_LENGTH;
  44477. endIndex += MP2T_PACKET_LENGTH;
  44478. continue;
  44479. } // If we get here, we have somehow become de-synchronized and we need to step
  44480. // forward one byte at a time until we find a pair of sync bytes that denote
  44481. // a packet
  44482. startIndex++;
  44483. endIndex++;
  44484. }
  44485. };
  44486. /**
  44487. * walks through the segment data from the start and end to get timing information
  44488. * for the first and last audio pes packets
  44489. */
  44490. var parseAudioPes_ = function parseAudioPes_(bytes, pmt, result) {
  44491. var startIndex = 0,
  44492. endIndex = MP2T_PACKET_LENGTH,
  44493. packet,
  44494. type,
  44495. pesType,
  44496. pusi,
  44497. parsed;
  44498. var endLoop = false; // Start walking from start of segment to get first audio packet
  44499. while (endIndex <= bytes.byteLength) {
  44500. // Look for a pair of start and end sync bytes in the data..
  44501. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  44502. // We found a packet
  44503. packet = bytes.subarray(startIndex, endIndex);
  44504. type = probe.ts.parseType(packet, pmt.pid);
  44505. switch (type) {
  44506. case 'pes':
  44507. pesType = probe.ts.parsePesType(packet, pmt.table);
  44508. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  44509. if (pesType === 'audio' && pusi) {
  44510. parsed = probe.ts.parsePesTime(packet);
  44511. if (parsed) {
  44512. parsed.type = 'audio';
  44513. result.audio.push(parsed);
  44514. endLoop = true;
  44515. }
  44516. }
  44517. break;
  44518. }
  44519. if (endLoop) {
  44520. break;
  44521. }
  44522. startIndex += MP2T_PACKET_LENGTH;
  44523. endIndex += MP2T_PACKET_LENGTH;
  44524. continue;
  44525. } // If we get here, we have somehow become de-synchronized and we need to step
  44526. // forward one byte at a time until we find a pair of sync bytes that denote
  44527. // a packet
  44528. startIndex++;
  44529. endIndex++;
  44530. } // Start walking from end of segment to get last audio packet
  44531. endIndex = bytes.byteLength;
  44532. startIndex = endIndex - MP2T_PACKET_LENGTH;
  44533. endLoop = false;
  44534. while (startIndex >= 0) {
  44535. // Look for a pair of start and end sync bytes in the data..
  44536. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  44537. // We found a packet
  44538. packet = bytes.subarray(startIndex, endIndex);
  44539. type = probe.ts.parseType(packet, pmt.pid);
  44540. switch (type) {
  44541. case 'pes':
  44542. pesType = probe.ts.parsePesType(packet, pmt.table);
  44543. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  44544. if (pesType === 'audio' && pusi) {
  44545. parsed = probe.ts.parsePesTime(packet);
  44546. if (parsed) {
  44547. parsed.type = 'audio';
  44548. result.audio.push(parsed);
  44549. endLoop = true;
  44550. }
  44551. }
  44552. break;
  44553. }
  44554. if (endLoop) {
  44555. break;
  44556. }
  44557. startIndex -= MP2T_PACKET_LENGTH;
  44558. endIndex -= MP2T_PACKET_LENGTH;
  44559. continue;
  44560. } // If we get here, we have somehow become de-synchronized and we need to step
  44561. // forward one byte at a time until we find a pair of sync bytes that denote
  44562. // a packet
  44563. startIndex--;
  44564. endIndex--;
  44565. }
  44566. };
  44567. /**
  44568. * walks through the segment data from the start and end to get timing information
  44569. * for the first and last video pes packets as well as timing information for the first
  44570. * key frame.
  44571. */
  44572. var parseVideoPes_ = function parseVideoPes_(bytes, pmt, result) {
  44573. var startIndex = 0,
  44574. endIndex = MP2T_PACKET_LENGTH,
  44575. packet,
  44576. type,
  44577. pesType,
  44578. pusi,
  44579. parsed,
  44580. frame,
  44581. i,
  44582. pes;
  44583. var endLoop = false;
  44584. var currentFrame = {
  44585. data: [],
  44586. size: 0
  44587. }; // Start walking from start of segment to get first video packet
  44588. while (endIndex < bytes.byteLength) {
  44589. // Look for a pair of start and end sync bytes in the data..
  44590. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  44591. // We found a packet
  44592. packet = bytes.subarray(startIndex, endIndex);
  44593. type = probe.ts.parseType(packet, pmt.pid);
  44594. switch (type) {
  44595. case 'pes':
  44596. pesType = probe.ts.parsePesType(packet, pmt.table);
  44597. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  44598. if (pesType === 'video') {
  44599. if (pusi && !endLoop) {
  44600. parsed = probe.ts.parsePesTime(packet);
  44601. if (parsed) {
  44602. parsed.type = 'video';
  44603. result.video.push(parsed);
  44604. endLoop = true;
  44605. }
  44606. }
  44607. if (!result.firstKeyFrame) {
  44608. if (pusi) {
  44609. if (currentFrame.size !== 0) {
  44610. frame = new Uint8Array(currentFrame.size);
  44611. i = 0;
  44612. while (currentFrame.data.length) {
  44613. pes = currentFrame.data.shift();
  44614. frame.set(pes, i);
  44615. i += pes.byteLength;
  44616. }
  44617. if (probe.ts.videoPacketContainsKeyFrame(frame)) {
  44618. var firstKeyFrame = probe.ts.parsePesTime(frame); // PTS/DTS may not be available. Simply *not* setting
  44619. // the keyframe seems to work fine with HLS playback
  44620. // and definitely preferable to a crash with TypeError...
  44621. if (firstKeyFrame) {
  44622. result.firstKeyFrame = firstKeyFrame;
  44623. result.firstKeyFrame.type = 'video';
  44624. } else {
  44625. // eslint-disable-next-line
  44626. console.warn('Failed to extract PTS/DTS from PES at first keyframe. ' + 'This could be an unusual TS segment, or else mux.js did not ' + 'parse your TS segment correctly. If you know your TS ' + 'segments do contain PTS/DTS on keyframes please file a bug ' + 'report! You can try ffprobe to double check for yourself.');
  44627. }
  44628. }
  44629. currentFrame.size = 0;
  44630. }
  44631. }
  44632. currentFrame.data.push(packet);
  44633. currentFrame.size += packet.byteLength;
  44634. }
  44635. }
  44636. break;
  44637. }
  44638. if (endLoop && result.firstKeyFrame) {
  44639. break;
  44640. }
  44641. startIndex += MP2T_PACKET_LENGTH;
  44642. endIndex += MP2T_PACKET_LENGTH;
  44643. continue;
  44644. } // If we get here, we have somehow become de-synchronized and we need to step
  44645. // forward one byte at a time until we find a pair of sync bytes that denote
  44646. // a packet
  44647. startIndex++;
  44648. endIndex++;
  44649. } // Start walking from end of segment to get last video packet
  44650. endIndex = bytes.byteLength;
  44651. startIndex = endIndex - MP2T_PACKET_LENGTH;
  44652. endLoop = false;
  44653. while (startIndex >= 0) {
  44654. // Look for a pair of start and end sync bytes in the data..
  44655. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  44656. // We found a packet
  44657. packet = bytes.subarray(startIndex, endIndex);
  44658. type = probe.ts.parseType(packet, pmt.pid);
  44659. switch (type) {
  44660. case 'pes':
  44661. pesType = probe.ts.parsePesType(packet, pmt.table);
  44662. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  44663. if (pesType === 'video' && pusi) {
  44664. parsed = probe.ts.parsePesTime(packet);
  44665. if (parsed) {
  44666. parsed.type = 'video';
  44667. result.video.push(parsed);
  44668. endLoop = true;
  44669. }
  44670. }
  44671. break;
  44672. }
  44673. if (endLoop) {
  44674. break;
  44675. }
  44676. startIndex -= MP2T_PACKET_LENGTH;
  44677. endIndex -= MP2T_PACKET_LENGTH;
  44678. continue;
  44679. } // If we get here, we have somehow become de-synchronized and we need to step
  44680. // forward one byte at a time until we find a pair of sync bytes that denote
  44681. // a packet
  44682. startIndex--;
  44683. endIndex--;
  44684. }
  44685. };
  44686. /**
  44687. * Adjusts the timestamp information for the segment to account for
  44688. * rollover and convert to seconds based on pes packet timescale (90khz clock)
  44689. */
  44690. var adjustTimestamp_ = function adjustTimestamp_(segmentInfo, baseTimestamp) {
  44691. if (segmentInfo.audio && segmentInfo.audio.length) {
  44692. var audioBaseTimestamp = baseTimestamp;
  44693. if (typeof audioBaseTimestamp === 'undefined' || isNaN(audioBaseTimestamp)) {
  44694. audioBaseTimestamp = segmentInfo.audio[0].dts;
  44695. }
  44696. segmentInfo.audio.forEach(function (info) {
  44697. info.dts = handleRollover(info.dts, audioBaseTimestamp);
  44698. info.pts = handleRollover(info.pts, audioBaseTimestamp); // time in seconds
  44699. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  44700. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  44701. });
  44702. }
  44703. if (segmentInfo.video && segmentInfo.video.length) {
  44704. var videoBaseTimestamp = baseTimestamp;
  44705. if (typeof videoBaseTimestamp === 'undefined' || isNaN(videoBaseTimestamp)) {
  44706. videoBaseTimestamp = segmentInfo.video[0].dts;
  44707. }
  44708. segmentInfo.video.forEach(function (info) {
  44709. info.dts = handleRollover(info.dts, videoBaseTimestamp);
  44710. info.pts = handleRollover(info.pts, videoBaseTimestamp); // time in seconds
  44711. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  44712. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  44713. });
  44714. if (segmentInfo.firstKeyFrame) {
  44715. var frame = segmentInfo.firstKeyFrame;
  44716. frame.dts = handleRollover(frame.dts, videoBaseTimestamp);
  44717. frame.pts = handleRollover(frame.pts, videoBaseTimestamp); // time in seconds
  44718. frame.dtsTime = frame.dts / ONE_SECOND_IN_TS;
  44719. frame.ptsTime = frame.pts / ONE_SECOND_IN_TS;
  44720. }
  44721. }
  44722. };
  44723. /**
  44724. * inspects the aac data stream for start and end time information
  44725. */
  44726. var inspectAac_ = function inspectAac_(bytes) {
  44727. var endLoop = false,
  44728. audioCount = 0,
  44729. sampleRate = null,
  44730. timestamp = null,
  44731. frameSize = 0,
  44732. byteIndex = 0,
  44733. packet;
  44734. while (bytes.length - byteIndex >= 3) {
  44735. var type = probe.aac.parseType(bytes, byteIndex);
  44736. switch (type) {
  44737. case 'timed-metadata':
  44738. // Exit early because we don't have enough to parse
  44739. // the ID3 tag header
  44740. if (bytes.length - byteIndex < 10) {
  44741. endLoop = true;
  44742. break;
  44743. }
  44744. frameSize = probe.aac.parseId3TagSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  44745. // to emit a full packet
  44746. if (frameSize > bytes.length) {
  44747. endLoop = true;
  44748. break;
  44749. }
  44750. if (timestamp === null) {
  44751. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  44752. timestamp = probe.aac.parseAacTimestamp(packet);
  44753. }
  44754. byteIndex += frameSize;
  44755. break;
  44756. case 'audio':
  44757. // Exit early because we don't have enough to parse
  44758. // the ADTS frame header
  44759. if (bytes.length - byteIndex < 7) {
  44760. endLoop = true;
  44761. break;
  44762. }
  44763. frameSize = probe.aac.parseAdtsSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  44764. // to emit a full packet
  44765. if (frameSize > bytes.length) {
  44766. endLoop = true;
  44767. break;
  44768. }
  44769. if (sampleRate === null) {
  44770. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  44771. sampleRate = probe.aac.parseSampleRate(packet);
  44772. }
  44773. audioCount++;
  44774. byteIndex += frameSize;
  44775. break;
  44776. default:
  44777. byteIndex++;
  44778. break;
  44779. }
  44780. if (endLoop) {
  44781. return null;
  44782. }
  44783. }
  44784. if (sampleRate === null || timestamp === null) {
  44785. return null;
  44786. }
  44787. var audioTimescale = ONE_SECOND_IN_TS / sampleRate;
  44788. var result = {
  44789. audio: [{
  44790. type: 'audio',
  44791. dts: timestamp,
  44792. pts: timestamp
  44793. }, {
  44794. type: 'audio',
  44795. dts: timestamp + audioCount * 1024 * audioTimescale,
  44796. pts: timestamp + audioCount * 1024 * audioTimescale
  44797. }]
  44798. };
  44799. return result;
  44800. };
  44801. /**
  44802. * inspects the transport stream segment data for start and end time information
  44803. * of the audio and video tracks (when present) as well as the first key frame's
  44804. * start time.
  44805. */
  44806. var inspectTs_ = function inspectTs_(bytes) {
  44807. var pmt = {
  44808. pid: null,
  44809. table: null
  44810. };
  44811. var result = {};
  44812. parsePsi_(bytes, pmt);
  44813. for (var pid in pmt.table) {
  44814. if (pmt.table.hasOwnProperty(pid)) {
  44815. var type = pmt.table[pid];
  44816. switch (type) {
  44817. case streamTypes.H264_STREAM_TYPE:
  44818. result.video = [];
  44819. parseVideoPes_(bytes, pmt, result);
  44820. if (result.video.length === 0) {
  44821. delete result.video;
  44822. }
  44823. break;
  44824. case streamTypes.ADTS_STREAM_TYPE:
  44825. result.audio = [];
  44826. parseAudioPes_(bytes, pmt, result);
  44827. if (result.audio.length === 0) {
  44828. delete result.audio;
  44829. }
  44830. break;
  44831. }
  44832. }
  44833. }
  44834. return result;
  44835. };
  44836. /**
  44837. * Inspects segment byte data and returns an object with start and end timing information
  44838. *
  44839. * @param {Uint8Array} bytes The segment byte data
  44840. * @param {Number} baseTimestamp Relative reference timestamp used when adjusting frame
  44841. * timestamps for rollover. This value must be in 90khz clock.
  44842. * @return {Object} Object containing start and end frame timing info of segment.
  44843. */
  44844. var inspect = function inspect(bytes, baseTimestamp) {
  44845. var isAacData = probe.aac.isLikelyAacData(bytes);
  44846. var result;
  44847. if (isAacData) {
  44848. result = inspectAac_(bytes);
  44849. } else {
  44850. result = inspectTs_(bytes);
  44851. }
  44852. if (!result || !result.audio && !result.video) {
  44853. return null;
  44854. }
  44855. adjustTimestamp_(result, baseTimestamp);
  44856. return result;
  44857. };
  44858. var tsInspector = {
  44859. inspect: inspect,
  44860. parseAudioPes_: parseAudioPes_
  44861. };
  44862. /* global self */
  44863. /**
  44864. * Re-emits transmuxer events by converting them into messages to the
  44865. * world outside the worker.
  44866. *
  44867. * @param {Object} transmuxer the transmuxer to wire events on
  44868. * @private
  44869. */
  44870. var wireTransmuxerEvents = function wireTransmuxerEvents(self, transmuxer) {
  44871. transmuxer.on('data', function (segment) {
  44872. // transfer ownership of the underlying ArrayBuffer
  44873. // instead of doing a copy to save memory
  44874. // ArrayBuffers are transferable but generic TypedArrays are not
  44875. // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
  44876. var initArray = segment.initSegment;
  44877. segment.initSegment = {
  44878. data: initArray.buffer,
  44879. byteOffset: initArray.byteOffset,
  44880. byteLength: initArray.byteLength
  44881. };
  44882. var typedArray = segment.data;
  44883. segment.data = typedArray.buffer;
  44884. self.postMessage({
  44885. action: 'data',
  44886. segment: segment,
  44887. byteOffset: typedArray.byteOffset,
  44888. byteLength: typedArray.byteLength
  44889. }, [segment.data]);
  44890. });
  44891. transmuxer.on('done', function (data) {
  44892. self.postMessage({
  44893. action: 'done'
  44894. });
  44895. });
  44896. transmuxer.on('gopInfo', function (gopInfo) {
  44897. self.postMessage({
  44898. action: 'gopInfo',
  44899. gopInfo: gopInfo
  44900. });
  44901. });
  44902. transmuxer.on('videoSegmentTimingInfo', function (timingInfo) {
  44903. var videoSegmentTimingInfo = {
  44904. start: {
  44905. decode: clock.videoTsToSeconds(timingInfo.start.dts),
  44906. presentation: clock.videoTsToSeconds(timingInfo.start.pts)
  44907. },
  44908. end: {
  44909. decode: clock.videoTsToSeconds(timingInfo.end.dts),
  44910. presentation: clock.videoTsToSeconds(timingInfo.end.pts)
  44911. },
  44912. baseMediaDecodeTime: clock.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  44913. };
  44914. if (timingInfo.prependedContentDuration) {
  44915. videoSegmentTimingInfo.prependedContentDuration = clock.videoTsToSeconds(timingInfo.prependedContentDuration);
  44916. }
  44917. self.postMessage({
  44918. action: 'videoSegmentTimingInfo',
  44919. videoSegmentTimingInfo: videoSegmentTimingInfo
  44920. });
  44921. });
  44922. transmuxer.on('audioSegmentTimingInfo', function (timingInfo) {
  44923. // Note that all times for [audio/video]SegmentTimingInfo events are in video clock
  44924. var audioSegmentTimingInfo = {
  44925. start: {
  44926. decode: clock.videoTsToSeconds(timingInfo.start.dts),
  44927. presentation: clock.videoTsToSeconds(timingInfo.start.pts)
  44928. },
  44929. end: {
  44930. decode: clock.videoTsToSeconds(timingInfo.end.dts),
  44931. presentation: clock.videoTsToSeconds(timingInfo.end.pts)
  44932. },
  44933. baseMediaDecodeTime: clock.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  44934. };
  44935. if (timingInfo.prependedContentDuration) {
  44936. audioSegmentTimingInfo.prependedContentDuration = clock.videoTsToSeconds(timingInfo.prependedContentDuration);
  44937. }
  44938. self.postMessage({
  44939. action: 'audioSegmentTimingInfo',
  44940. audioSegmentTimingInfo: audioSegmentTimingInfo
  44941. });
  44942. });
  44943. transmuxer.on('id3Frame', function (id3Frame) {
  44944. self.postMessage({
  44945. action: 'id3Frame',
  44946. id3Frame: id3Frame
  44947. });
  44948. });
  44949. transmuxer.on('caption', function (caption) {
  44950. self.postMessage({
  44951. action: 'caption',
  44952. caption: caption
  44953. });
  44954. });
  44955. transmuxer.on('trackinfo', function (trackInfo) {
  44956. self.postMessage({
  44957. action: 'trackinfo',
  44958. trackInfo: trackInfo
  44959. });
  44960. });
  44961. transmuxer.on('audioTimingInfo', function (audioTimingInfo) {
  44962. // convert to video TS since we prioritize video time over audio
  44963. self.postMessage({
  44964. action: 'audioTimingInfo',
  44965. audioTimingInfo: {
  44966. start: clock.videoTsToSeconds(audioTimingInfo.start),
  44967. end: clock.videoTsToSeconds(audioTimingInfo.end)
  44968. }
  44969. });
  44970. });
  44971. transmuxer.on('videoTimingInfo', function (videoTimingInfo) {
  44972. self.postMessage({
  44973. action: 'videoTimingInfo',
  44974. videoTimingInfo: {
  44975. start: clock.videoTsToSeconds(videoTimingInfo.start),
  44976. end: clock.videoTsToSeconds(videoTimingInfo.end)
  44977. }
  44978. });
  44979. });
  44980. transmuxer.on('log', function (log) {
  44981. self.postMessage({
  44982. action: 'log',
  44983. log: log
  44984. });
  44985. });
  44986. };
  44987. /**
  44988. * All incoming messages route through this hash. If no function exists
  44989. * to handle an incoming message, then we ignore the message.
  44990. *
  44991. * @class MessageHandlers
  44992. * @param {Object} options the options to initialize with
  44993. */
  44994. var MessageHandlers = /*#__PURE__*/function () {
  44995. function MessageHandlers(self, options) {
  44996. this.options = options || {};
  44997. this.self = self;
  44998. this.init();
  44999. }
  45000. /**
  45001. * initialize our web worker and wire all the events.
  45002. */
  45003. var _proto = MessageHandlers.prototype;
  45004. _proto.init = function init() {
  45005. if (this.transmuxer) {
  45006. this.transmuxer.dispose();
  45007. }
  45008. this.transmuxer = new transmuxer.Transmuxer(this.options);
  45009. wireTransmuxerEvents(this.self, this.transmuxer);
  45010. };
  45011. _proto.pushMp4Captions = function pushMp4Captions(data) {
  45012. if (!this.captionParser) {
  45013. this.captionParser = new captionParser();
  45014. this.captionParser.init();
  45015. }
  45016. var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  45017. var parsed = this.captionParser.parse(segment, data.trackIds, data.timescales);
  45018. this.self.postMessage({
  45019. action: 'mp4Captions',
  45020. captions: parsed && parsed.captions || [],
  45021. logs: parsed && parsed.logs || [],
  45022. data: segment.buffer
  45023. }, [segment.buffer]);
  45024. };
  45025. _proto.probeMp4StartTime = function probeMp4StartTime(_ref) {
  45026. var timescales = _ref.timescales,
  45027. data = _ref.data;
  45028. var startTime = probe$2.startTime(timescales, data);
  45029. this.self.postMessage({
  45030. action: 'probeMp4StartTime',
  45031. startTime: startTime,
  45032. data: data
  45033. }, [data.buffer]);
  45034. };
  45035. _proto.probeMp4Tracks = function probeMp4Tracks(_ref2) {
  45036. var data = _ref2.data;
  45037. var tracks = probe$2.tracks(data);
  45038. this.self.postMessage({
  45039. action: 'probeMp4Tracks',
  45040. tracks: tracks,
  45041. data: data
  45042. }, [data.buffer]);
  45043. }
  45044. /**
  45045. * Probe an mpeg2-ts segment to determine the start time of the segment in it's
  45046. * internal "media time," as well as whether it contains video and/or audio.
  45047. *
  45048. * @private
  45049. * @param {Uint8Array} bytes - segment bytes
  45050. * @param {number} baseStartTime
  45051. * Relative reference timestamp used when adjusting frame timestamps for rollover.
  45052. * This value should be in seconds, as it's converted to a 90khz clock within the
  45053. * function body.
  45054. * @return {Object} The start time of the current segment in "media time" as well as
  45055. * whether it contains video and/or audio
  45056. */
  45057. ;
  45058. _proto.probeTs = function probeTs(_ref3) {
  45059. var data = _ref3.data,
  45060. baseStartTime = _ref3.baseStartTime;
  45061. var tsStartTime = typeof baseStartTime === 'number' && !isNaN(baseStartTime) ? baseStartTime * clock.ONE_SECOND_IN_TS : void 0;
  45062. var timeInfo = tsInspector.inspect(data, tsStartTime);
  45063. var result = null;
  45064. if (timeInfo) {
  45065. result = {
  45066. // each type's time info comes back as an array of 2 times, start and end
  45067. hasVideo: timeInfo.video && timeInfo.video.length === 2 || false,
  45068. hasAudio: timeInfo.audio && timeInfo.audio.length === 2 || false
  45069. };
  45070. if (result.hasVideo) {
  45071. result.videoStart = timeInfo.video[0].ptsTime;
  45072. }
  45073. if (result.hasAudio) {
  45074. result.audioStart = timeInfo.audio[0].ptsTime;
  45075. }
  45076. }
  45077. this.self.postMessage({
  45078. action: 'probeTs',
  45079. result: result,
  45080. data: data
  45081. }, [data.buffer]);
  45082. };
  45083. _proto.clearAllMp4Captions = function clearAllMp4Captions() {
  45084. if (this.captionParser) {
  45085. this.captionParser.clearAllCaptions();
  45086. }
  45087. };
  45088. _proto.clearParsedMp4Captions = function clearParsedMp4Captions() {
  45089. if (this.captionParser) {
  45090. this.captionParser.clearParsedCaptions();
  45091. }
  45092. }
  45093. /**
  45094. * Adds data (a ts segment) to the start of the transmuxer pipeline for
  45095. * processing.
  45096. *
  45097. * @param {ArrayBuffer} data data to push into the muxer
  45098. */
  45099. ;
  45100. _proto.push = function push(data) {
  45101. // Cast array buffer to correct type for transmuxer
  45102. var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  45103. this.transmuxer.push(segment);
  45104. }
  45105. /**
  45106. * Recreate the transmuxer so that the next segment added via `push`
  45107. * start with a fresh transmuxer.
  45108. */
  45109. ;
  45110. _proto.reset = function reset() {
  45111. this.transmuxer.reset();
  45112. }
  45113. /**
  45114. * Set the value that will be used as the `baseMediaDecodeTime` time for the
  45115. * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`
  45116. * set relative to the first based on the PTS values.
  45117. *
  45118. * @param {Object} data used to set the timestamp offset in the muxer
  45119. */
  45120. ;
  45121. _proto.setTimestampOffset = function setTimestampOffset(data) {
  45122. var timestampOffset = data.timestampOffset || 0;
  45123. this.transmuxer.setBaseMediaDecodeTime(Math.round(clock.secondsToVideoTs(timestampOffset)));
  45124. };
  45125. _proto.setAudioAppendStart = function setAudioAppendStart(data) {
  45126. this.transmuxer.setAudioAppendStart(Math.ceil(clock.secondsToVideoTs(data.appendStart)));
  45127. };
  45128. _proto.setRemux = function setRemux(data) {
  45129. this.transmuxer.setRemux(data.remux);
  45130. }
  45131. /**
  45132. * Forces the pipeline to finish processing the last segment and emit it's
  45133. * results.
  45134. *
  45135. * @param {Object} data event data, not really used
  45136. */
  45137. ;
  45138. _proto.flush = function flush(data) {
  45139. this.transmuxer.flush(); // transmuxed done action is fired after both audio/video pipelines are flushed
  45140. self.postMessage({
  45141. action: 'done',
  45142. type: 'transmuxed'
  45143. });
  45144. };
  45145. _proto.endTimeline = function endTimeline() {
  45146. this.transmuxer.endTimeline(); // transmuxed endedtimeline action is fired after both audio/video pipelines end their
  45147. // timelines
  45148. self.postMessage({
  45149. action: 'endedtimeline',
  45150. type: 'transmuxed'
  45151. });
  45152. };
  45153. _proto.alignGopsWith = function alignGopsWith(data) {
  45154. this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice());
  45155. };
  45156. return MessageHandlers;
  45157. }();
  45158. /**
  45159. * Our web worker interface so that things can talk to mux.js
  45160. * that will be running in a web worker. the scope is passed to this by
  45161. * webworkify.
  45162. *
  45163. * @param {Object} self the scope for the web worker
  45164. */
  45165. self.onmessage = function (event) {
  45166. if (event.data.action === 'init' && event.data.options) {
  45167. this.messageHandlers = new MessageHandlers(self, event.data.options);
  45168. return;
  45169. }
  45170. if (!this.messageHandlers) {
  45171. this.messageHandlers = new MessageHandlers(self);
  45172. }
  45173. if (event.data && event.data.action && event.data.action !== 'init') {
  45174. if (this.messageHandlers[event.data.action]) {
  45175. this.messageHandlers[event.data.action](event.data);
  45176. }
  45177. }
  45178. };
  45179. }));
  45180. var TransmuxWorker = factory(workerCode$1);
  45181. /* rollup-plugin-worker-factory end for worker!/Users/ddashkevich/projects/http-streaming/src/transmuxer-worker.js */
  45182. var handleData_ = function handleData_(event, transmuxedData, callback) {
  45183. var _event$data$segment = event.data.segment,
  45184. type = _event$data$segment.type,
  45185. initSegment = _event$data$segment.initSegment,
  45186. captions = _event$data$segment.captions,
  45187. captionStreams = _event$data$segment.captionStreams,
  45188. metadata = _event$data$segment.metadata,
  45189. videoFrameDtsTime = _event$data$segment.videoFrameDtsTime,
  45190. videoFramePtsTime = _event$data$segment.videoFramePtsTime;
  45191. transmuxedData.buffer.push({
  45192. captions: captions,
  45193. captionStreams: captionStreams,
  45194. metadata: metadata
  45195. });
  45196. var boxes = event.data.segment.boxes || {
  45197. data: event.data.segment.data
  45198. };
  45199. var result = {
  45200. type: type,
  45201. // cast ArrayBuffer to TypedArray
  45202. data: new Uint8Array(boxes.data, boxes.data.byteOffset, boxes.data.byteLength),
  45203. initSegment: new Uint8Array(initSegment.data, initSegment.byteOffset, initSegment.byteLength)
  45204. };
  45205. if (typeof videoFrameDtsTime !== 'undefined') {
  45206. result.videoFrameDtsTime = videoFrameDtsTime;
  45207. }
  45208. if (typeof videoFramePtsTime !== 'undefined') {
  45209. result.videoFramePtsTime = videoFramePtsTime;
  45210. }
  45211. callback(result);
  45212. };
  45213. var handleDone_ = function handleDone_(_ref) {
  45214. var transmuxedData = _ref.transmuxedData,
  45215. callback = _ref.callback; // Previously we only returned data on data events,
  45216. // not on done events. Clear out the buffer to keep that consistent.
  45217. transmuxedData.buffer = []; // all buffers should have been flushed from the muxer, so start processing anything we
  45218. // have received
  45219. callback(transmuxedData);
  45220. };
  45221. var handleGopInfo_ = function handleGopInfo_(event, transmuxedData) {
  45222. transmuxedData.gopInfo = event.data.gopInfo;
  45223. };
  45224. var processTransmux = function processTransmux(options) {
  45225. var transmuxer = options.transmuxer,
  45226. bytes = options.bytes,
  45227. audioAppendStart = options.audioAppendStart,
  45228. gopsToAlignWith = options.gopsToAlignWith,
  45229. remux = options.remux,
  45230. onData = options.onData,
  45231. onTrackInfo = options.onTrackInfo,
  45232. onAudioTimingInfo = options.onAudioTimingInfo,
  45233. onVideoTimingInfo = options.onVideoTimingInfo,
  45234. onVideoSegmentTimingInfo = options.onVideoSegmentTimingInfo,
  45235. onAudioSegmentTimingInfo = options.onAudioSegmentTimingInfo,
  45236. onId3 = options.onId3,
  45237. onCaptions = options.onCaptions,
  45238. onDone = options.onDone,
  45239. onEndedTimeline = options.onEndedTimeline,
  45240. onTransmuxerLog = options.onTransmuxerLog,
  45241. isEndOfTimeline = options.isEndOfTimeline;
  45242. var transmuxedData = {
  45243. buffer: []
  45244. };
  45245. var waitForEndedTimelineEvent = isEndOfTimeline;
  45246. var handleMessage = function handleMessage(event) {
  45247. if (transmuxer.currentTransmux !== options) {
  45248. // disposed
  45249. return;
  45250. }
  45251. if (event.data.action === 'data') {
  45252. handleData_(event, transmuxedData, onData);
  45253. }
  45254. if (event.data.action === 'trackinfo') {
  45255. onTrackInfo(event.data.trackInfo);
  45256. }
  45257. if (event.data.action === 'gopInfo') {
  45258. handleGopInfo_(event, transmuxedData);
  45259. }
  45260. if (event.data.action === 'audioTimingInfo') {
  45261. onAudioTimingInfo(event.data.audioTimingInfo);
  45262. }
  45263. if (event.data.action === 'videoTimingInfo') {
  45264. onVideoTimingInfo(event.data.videoTimingInfo);
  45265. }
  45266. if (event.data.action === 'videoSegmentTimingInfo') {
  45267. onVideoSegmentTimingInfo(event.data.videoSegmentTimingInfo);
  45268. }
  45269. if (event.data.action === 'audioSegmentTimingInfo') {
  45270. onAudioSegmentTimingInfo(event.data.audioSegmentTimingInfo);
  45271. }
  45272. if (event.data.action === 'id3Frame') {
  45273. onId3([event.data.id3Frame], event.data.id3Frame.dispatchType);
  45274. }
  45275. if (event.data.action === 'caption') {
  45276. onCaptions(event.data.caption);
  45277. }
  45278. if (event.data.action === 'endedtimeline') {
  45279. waitForEndedTimelineEvent = false;
  45280. onEndedTimeline();
  45281. }
  45282. if (event.data.action === 'log') {
  45283. onTransmuxerLog(event.data.log);
  45284. } // wait for the transmuxed event since we may have audio and video
  45285. if (event.data.type !== 'transmuxed') {
  45286. return;
  45287. } // If the "endedtimeline" event has not yet fired, and this segment represents the end
  45288. // of a timeline, that means there may still be data events before the segment
  45289. // processing can be considerred complete. In that case, the final event should be
  45290. // an "endedtimeline" event with the type "transmuxed."
  45291. if (waitForEndedTimelineEvent) {
  45292. return;
  45293. }
  45294. transmuxer.onmessage = null;
  45295. handleDone_({
  45296. transmuxedData: transmuxedData,
  45297. callback: onDone
  45298. });
  45299. /* eslint-disable no-use-before-define */
  45300. dequeue(transmuxer);
  45301. /* eslint-enable */
  45302. };
  45303. transmuxer.onmessage = handleMessage;
  45304. if (audioAppendStart) {
  45305. transmuxer.postMessage({
  45306. action: 'setAudioAppendStart',
  45307. appendStart: audioAppendStart
  45308. });
  45309. } // allow empty arrays to be passed to clear out GOPs
  45310. if (Array.isArray(gopsToAlignWith)) {
  45311. transmuxer.postMessage({
  45312. action: 'alignGopsWith',
  45313. gopsToAlignWith: gopsToAlignWith
  45314. });
  45315. }
  45316. if (typeof remux !== 'undefined') {
  45317. transmuxer.postMessage({
  45318. action: 'setRemux',
  45319. remux: remux
  45320. });
  45321. }
  45322. if (bytes.byteLength) {
  45323. var buffer = bytes instanceof ArrayBuffer ? bytes : bytes.buffer;
  45324. var byteOffset = bytes instanceof ArrayBuffer ? 0 : bytes.byteOffset;
  45325. transmuxer.postMessage({
  45326. action: 'push',
  45327. // Send the typed-array of data as an ArrayBuffer so that
  45328. // it can be sent as a "Transferable" and avoid the costly
  45329. // memory copy
  45330. data: buffer,
  45331. // To recreate the original typed-array, we need information
  45332. // about what portion of the ArrayBuffer it was a view into
  45333. byteOffset: byteOffset,
  45334. byteLength: bytes.byteLength
  45335. }, [buffer]);
  45336. }
  45337. if (isEndOfTimeline) {
  45338. transmuxer.postMessage({
  45339. action: 'endTimeline'
  45340. });
  45341. } // even if we didn't push any bytes, we have to make sure we flush in case we reached
  45342. // the end of the segment
  45343. transmuxer.postMessage({
  45344. action: 'flush'
  45345. });
  45346. };
  45347. var dequeue = function dequeue(transmuxer) {
  45348. transmuxer.currentTransmux = null;
  45349. if (transmuxer.transmuxQueue.length) {
  45350. transmuxer.currentTransmux = transmuxer.transmuxQueue.shift();
  45351. if (typeof transmuxer.currentTransmux === 'function') {
  45352. transmuxer.currentTransmux();
  45353. } else {
  45354. processTransmux(transmuxer.currentTransmux);
  45355. }
  45356. }
  45357. };
  45358. var processAction = function processAction(transmuxer, action) {
  45359. transmuxer.postMessage({
  45360. action: action
  45361. });
  45362. dequeue(transmuxer);
  45363. };
  45364. var enqueueAction = function enqueueAction(action, transmuxer) {
  45365. if (!transmuxer.currentTransmux) {
  45366. transmuxer.currentTransmux = action;
  45367. processAction(transmuxer, action);
  45368. return;
  45369. }
  45370. transmuxer.transmuxQueue.push(processAction.bind(null, transmuxer, action));
  45371. };
  45372. var reset = function reset(transmuxer) {
  45373. enqueueAction('reset', transmuxer);
  45374. };
  45375. var endTimeline = function endTimeline(transmuxer) {
  45376. enqueueAction('endTimeline', transmuxer);
  45377. };
  45378. var transmux = function transmux(options) {
  45379. if (!options.transmuxer.currentTransmux) {
  45380. options.transmuxer.currentTransmux = options;
  45381. processTransmux(options);
  45382. return;
  45383. }
  45384. options.transmuxer.transmuxQueue.push(options);
  45385. };
  45386. var createTransmuxer = function createTransmuxer(options) {
  45387. var transmuxer = new TransmuxWorker();
  45388. transmuxer.currentTransmux = null;
  45389. transmuxer.transmuxQueue = [];
  45390. var term = transmuxer.terminate;
  45391. transmuxer.terminate = function () {
  45392. transmuxer.currentTransmux = null;
  45393. transmuxer.transmuxQueue.length = 0;
  45394. return term.call(transmuxer);
  45395. };
  45396. transmuxer.postMessage({
  45397. action: 'init',
  45398. options: options
  45399. });
  45400. return transmuxer;
  45401. };
  45402. var segmentTransmuxer = {
  45403. reset: reset,
  45404. endTimeline: endTimeline,
  45405. transmux: transmux,
  45406. createTransmuxer: createTransmuxer
  45407. };
  45408. var workerCallback = function workerCallback(options) {
  45409. var transmuxer = options.transmuxer;
  45410. var endAction = options.endAction || options.action;
  45411. var callback = options.callback;
  45412. var message = _extends_1({}, options, {
  45413. endAction: null,
  45414. transmuxer: null,
  45415. callback: null
  45416. });
  45417. var listenForEndEvent = function listenForEndEvent(event) {
  45418. if (event.data.action !== endAction) {
  45419. return;
  45420. }
  45421. transmuxer.removeEventListener('message', listenForEndEvent); // transfer ownership of bytes back to us.
  45422. if (event.data.data) {
  45423. event.data.data = new Uint8Array(event.data.data, options.byteOffset || 0, options.byteLength || event.data.data.byteLength);
  45424. if (options.data) {
  45425. options.data = event.data.data;
  45426. }
  45427. }
  45428. callback(event.data);
  45429. };
  45430. transmuxer.addEventListener('message', listenForEndEvent);
  45431. if (options.data) {
  45432. var isArrayBuffer = options.data instanceof ArrayBuffer;
  45433. message.byteOffset = isArrayBuffer ? 0 : options.data.byteOffset;
  45434. message.byteLength = options.data.byteLength;
  45435. var transfers = [isArrayBuffer ? options.data : options.data.buffer];
  45436. transmuxer.postMessage(message, transfers);
  45437. } else {
  45438. transmuxer.postMessage(message);
  45439. }
  45440. };
  45441. var REQUEST_ERRORS = {
  45442. FAILURE: 2,
  45443. TIMEOUT: -101,
  45444. ABORTED: -102
  45445. };
  45446. /**
  45447. * Abort all requests
  45448. *
  45449. * @param {Object} activeXhrs - an object that tracks all XHR requests
  45450. */
  45451. var abortAll = function abortAll(activeXhrs) {
  45452. activeXhrs.forEach(function (xhr) {
  45453. xhr.abort();
  45454. });
  45455. };
  45456. /**
  45457. * Gather important bandwidth stats once a request has completed
  45458. *
  45459. * @param {Object} request - the XHR request from which to gather stats
  45460. */
  45461. var getRequestStats = function getRequestStats(request) {
  45462. return {
  45463. bandwidth: request.bandwidth,
  45464. bytesReceived: request.bytesReceived || 0,
  45465. roundTripTime: request.roundTripTime || 0
  45466. };
  45467. };
  45468. /**
  45469. * If possible gather bandwidth stats as a request is in
  45470. * progress
  45471. *
  45472. * @param {Event} progressEvent - an event object from an XHR's progress event
  45473. */
  45474. var getProgressStats = function getProgressStats(progressEvent) {
  45475. var request = progressEvent.target;
  45476. var roundTripTime = Date.now() - request.requestTime;
  45477. var stats = {
  45478. bandwidth: Infinity,
  45479. bytesReceived: 0,
  45480. roundTripTime: roundTripTime || 0
  45481. };
  45482. stats.bytesReceived = progressEvent.loaded; // This can result in Infinity if stats.roundTripTime is 0 but that is ok
  45483. // because we should only use bandwidth stats on progress to determine when
  45484. // abort a request early due to insufficient bandwidth
  45485. stats.bandwidth = Math.floor(stats.bytesReceived / stats.roundTripTime * 8 * 1000);
  45486. return stats;
  45487. };
  45488. /**
  45489. * Handle all error conditions in one place and return an object
  45490. * with all the information
  45491. *
  45492. * @param {Error|null} error - if non-null signals an error occured with the XHR
  45493. * @param {Object} request - the XHR request that possibly generated the error
  45494. */
  45495. var handleErrors = function handleErrors(error, request) {
  45496. if (request.timedout) {
  45497. return {
  45498. status: request.status,
  45499. message: 'HLS request timed-out at URL: ' + request.uri,
  45500. code: REQUEST_ERRORS.TIMEOUT,
  45501. xhr: request
  45502. };
  45503. }
  45504. if (request.aborted) {
  45505. return {
  45506. status: request.status,
  45507. message: 'HLS request aborted at URL: ' + request.uri,
  45508. code: REQUEST_ERRORS.ABORTED,
  45509. xhr: request
  45510. };
  45511. }
  45512. if (error) {
  45513. return {
  45514. status: request.status,
  45515. message: 'HLS request errored at URL: ' + request.uri,
  45516. code: REQUEST_ERRORS.FAILURE,
  45517. xhr: request
  45518. };
  45519. }
  45520. if (request.responseType === 'arraybuffer' && request.response.byteLength === 0) {
  45521. return {
  45522. status: request.status,
  45523. message: 'Empty HLS response at URL: ' + request.uri,
  45524. code: REQUEST_ERRORS.FAILURE,
  45525. xhr: request
  45526. };
  45527. }
  45528. return null;
  45529. };
  45530. /**
  45531. * Handle responses for key data and convert the key data to the correct format
  45532. * for the decryption step later
  45533. *
  45534. * @param {Object} segment - a simplified copy of the segmentInfo object
  45535. * from SegmentLoader
  45536. * @param {Array} objects - objects to add the key bytes to.
  45537. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  45538. * this request
  45539. */
  45540. var handleKeyResponse = function handleKeyResponse(segment, objects, finishProcessingFn) {
  45541. return function (error, request) {
  45542. var response = request.response;
  45543. var errorObj = handleErrors(error, request);
  45544. if (errorObj) {
  45545. return finishProcessingFn(errorObj, segment);
  45546. }
  45547. if (response.byteLength !== 16) {
  45548. return finishProcessingFn({
  45549. status: request.status,
  45550. message: 'Invalid HLS key at URL: ' + request.uri,
  45551. code: REQUEST_ERRORS.FAILURE,
  45552. xhr: request
  45553. }, segment);
  45554. }
  45555. var view = new DataView(response);
  45556. var bytes = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
  45557. for (var i = 0; i < objects.length; i++) {
  45558. objects[i].bytes = bytes;
  45559. }
  45560. return finishProcessingFn(null, segment);
  45561. };
  45562. };
  45563. var parseInitSegment = function parseInitSegment(segment, _callback) {
  45564. var type = detectContainerForBytes(segment.map.bytes); // TODO: We should also handle ts init segments here, but we
  45565. // only know how to parse mp4 init segments at the moment
  45566. if (type !== 'mp4') {
  45567. var uri = segment.map.resolvedUri || segment.map.uri;
  45568. return _callback({
  45569. internal: true,
  45570. message: "Found unsupported " + (type || 'unknown') + " container for initialization segment at URL: " + uri,
  45571. code: REQUEST_ERRORS.FAILURE
  45572. });
  45573. }
  45574. workerCallback({
  45575. action: 'probeMp4Tracks',
  45576. data: segment.map.bytes,
  45577. transmuxer: segment.transmuxer,
  45578. callback: function callback(_ref) {
  45579. var tracks = _ref.tracks,
  45580. data = _ref.data; // transfer bytes back to us
  45581. segment.map.bytes = data;
  45582. tracks.forEach(function (track) {
  45583. segment.map.tracks = segment.map.tracks || {}; // only support one track of each type for now
  45584. if (segment.map.tracks[track.type]) {
  45585. return;
  45586. }
  45587. segment.map.tracks[track.type] = track;
  45588. if (typeof track.id === 'number' && track.timescale) {
  45589. segment.map.timescales = segment.map.timescales || {};
  45590. segment.map.timescales[track.id] = track.timescale;
  45591. }
  45592. });
  45593. return _callback(null);
  45594. }
  45595. });
  45596. };
  45597. /**
  45598. * Handle init-segment responses
  45599. *
  45600. * @param {Object} segment - a simplified copy of the segmentInfo object
  45601. * from SegmentLoader
  45602. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  45603. * this request
  45604. */
  45605. var handleInitSegmentResponse = function handleInitSegmentResponse(_ref2) {
  45606. var segment = _ref2.segment,
  45607. finishProcessingFn = _ref2.finishProcessingFn;
  45608. return function (error, request) {
  45609. var errorObj = handleErrors(error, request);
  45610. if (errorObj) {
  45611. return finishProcessingFn(errorObj, segment);
  45612. }
  45613. var bytes = new Uint8Array(request.response); // init segment is encypted, we will have to wait
  45614. // until the key request is done to decrypt.
  45615. if (segment.map.key) {
  45616. segment.map.encryptedBytes = bytes;
  45617. return finishProcessingFn(null, segment);
  45618. }
  45619. segment.map.bytes = bytes;
  45620. parseInitSegment(segment, function (parseError) {
  45621. if (parseError) {
  45622. parseError.xhr = request;
  45623. parseError.status = request.status;
  45624. return finishProcessingFn(parseError, segment);
  45625. }
  45626. finishProcessingFn(null, segment);
  45627. });
  45628. };
  45629. };
  45630. /**
  45631. * Response handler for segment-requests being sure to set the correct
  45632. * property depending on whether the segment is encryped or not
  45633. * Also records and keeps track of stats that are used for ABR purposes
  45634. *
  45635. * @param {Object} segment - a simplified copy of the segmentInfo object
  45636. * from SegmentLoader
  45637. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  45638. * this request
  45639. */
  45640. var handleSegmentResponse = function handleSegmentResponse(_ref3) {
  45641. var segment = _ref3.segment,
  45642. finishProcessingFn = _ref3.finishProcessingFn,
  45643. responseType = _ref3.responseType;
  45644. return function (error, request) {
  45645. var errorObj = handleErrors(error, request);
  45646. if (errorObj) {
  45647. return finishProcessingFn(errorObj, segment);
  45648. }
  45649. var newBytes = // although responseText "should" exist, this guard serves to prevent an error being
  45650. // thrown for two primary cases:
  45651. // 1. the mime type override stops working, or is not implemented for a specific
  45652. // browser
  45653. // 2. when using mock XHR libraries like sinon that do not allow the override behavior
  45654. responseType === 'arraybuffer' || !request.responseText ? request.response : stringToArrayBuffer(request.responseText.substring(segment.lastReachedChar || 0));
  45655. segment.stats = getRequestStats(request);
  45656. if (segment.key) {
  45657. segment.encryptedBytes = new Uint8Array(newBytes);
  45658. } else {
  45659. segment.bytes = new Uint8Array(newBytes);
  45660. }
  45661. return finishProcessingFn(null, segment);
  45662. };
  45663. };
  45664. var transmuxAndNotify = function transmuxAndNotify(_ref4) {
  45665. var segment = _ref4.segment,
  45666. bytes = _ref4.bytes,
  45667. trackInfoFn = _ref4.trackInfoFn,
  45668. timingInfoFn = _ref4.timingInfoFn,
  45669. videoSegmentTimingInfoFn = _ref4.videoSegmentTimingInfoFn,
  45670. audioSegmentTimingInfoFn = _ref4.audioSegmentTimingInfoFn,
  45671. id3Fn = _ref4.id3Fn,
  45672. captionsFn = _ref4.captionsFn,
  45673. isEndOfTimeline = _ref4.isEndOfTimeline,
  45674. endedTimelineFn = _ref4.endedTimelineFn,
  45675. dataFn = _ref4.dataFn,
  45676. doneFn = _ref4.doneFn,
  45677. onTransmuxerLog = _ref4.onTransmuxerLog;
  45678. var fmp4Tracks = segment.map && segment.map.tracks || {};
  45679. var isMuxed = Boolean(fmp4Tracks.audio && fmp4Tracks.video); // Keep references to each function so we can null them out after we're done with them.
  45680. // One reason for this is that in the case of full segments, we want to trust start
  45681. // times from the probe, rather than the transmuxer.
  45682. var audioStartFn = timingInfoFn.bind(null, segment, 'audio', 'start');
  45683. var audioEndFn = timingInfoFn.bind(null, segment, 'audio', 'end');
  45684. var videoStartFn = timingInfoFn.bind(null, segment, 'video', 'start');
  45685. var videoEndFn = timingInfoFn.bind(null, segment, 'video', 'end');
  45686. var finish = function finish() {
  45687. return transmux({
  45688. bytes: bytes,
  45689. transmuxer: segment.transmuxer,
  45690. audioAppendStart: segment.audioAppendStart,
  45691. gopsToAlignWith: segment.gopsToAlignWith,
  45692. remux: isMuxed,
  45693. onData: function onData(result) {
  45694. result.type = result.type === 'combined' ? 'video' : result.type;
  45695. dataFn(segment, result);
  45696. },
  45697. onTrackInfo: function onTrackInfo(trackInfo) {
  45698. if (trackInfoFn) {
  45699. if (isMuxed) {
  45700. trackInfo.isMuxed = true;
  45701. }
  45702. trackInfoFn(segment, trackInfo);
  45703. }
  45704. },
  45705. onAudioTimingInfo: function onAudioTimingInfo(audioTimingInfo) {
  45706. // we only want the first start value we encounter
  45707. if (audioStartFn && typeof audioTimingInfo.start !== 'undefined') {
  45708. audioStartFn(audioTimingInfo.start);
  45709. audioStartFn = null;
  45710. } // we want to continually update the end time
  45711. if (audioEndFn && typeof audioTimingInfo.end !== 'undefined') {
  45712. audioEndFn(audioTimingInfo.end);
  45713. }
  45714. },
  45715. onVideoTimingInfo: function onVideoTimingInfo(videoTimingInfo) {
  45716. // we only want the first start value we encounter
  45717. if (videoStartFn && typeof videoTimingInfo.start !== 'undefined') {
  45718. videoStartFn(videoTimingInfo.start);
  45719. videoStartFn = null;
  45720. } // we want to continually update the end time
  45721. if (videoEndFn && typeof videoTimingInfo.end !== 'undefined') {
  45722. videoEndFn(videoTimingInfo.end);
  45723. }
  45724. },
  45725. onVideoSegmentTimingInfo: function onVideoSegmentTimingInfo(videoSegmentTimingInfo) {
  45726. videoSegmentTimingInfoFn(videoSegmentTimingInfo);
  45727. },
  45728. onAudioSegmentTimingInfo: function onAudioSegmentTimingInfo(audioSegmentTimingInfo) {
  45729. audioSegmentTimingInfoFn(audioSegmentTimingInfo);
  45730. },
  45731. onId3: function onId3(id3Frames, dispatchType) {
  45732. id3Fn(segment, id3Frames, dispatchType);
  45733. },
  45734. onCaptions: function onCaptions(captions) {
  45735. captionsFn(segment, [captions]);
  45736. },
  45737. isEndOfTimeline: isEndOfTimeline,
  45738. onEndedTimeline: function onEndedTimeline() {
  45739. endedTimelineFn();
  45740. },
  45741. onTransmuxerLog: onTransmuxerLog,
  45742. onDone: function onDone(result) {
  45743. if (!doneFn) {
  45744. return;
  45745. }
  45746. result.type = result.type === 'combined' ? 'video' : result.type;
  45747. doneFn(null, segment, result);
  45748. }
  45749. });
  45750. }; // In the transmuxer, we don't yet have the ability to extract a "proper" start time.
  45751. // Meaning cached frame data may corrupt our notion of where this segment
  45752. // really starts. To get around this, probe for the info needed.
  45753. workerCallback({
  45754. action: 'probeTs',
  45755. transmuxer: segment.transmuxer,
  45756. data: bytes,
  45757. baseStartTime: segment.baseStartTime,
  45758. callback: function callback(data) {
  45759. segment.bytes = bytes = data.data;
  45760. var probeResult = data.result;
  45761. if (probeResult) {
  45762. trackInfoFn(segment, {
  45763. hasAudio: probeResult.hasAudio,
  45764. hasVideo: probeResult.hasVideo,
  45765. isMuxed: isMuxed
  45766. });
  45767. trackInfoFn = null;
  45768. if (probeResult.hasAudio && !isMuxed) {
  45769. audioStartFn(probeResult.audioStart);
  45770. }
  45771. if (probeResult.hasVideo) {
  45772. videoStartFn(probeResult.videoStart);
  45773. }
  45774. audioStartFn = null;
  45775. videoStartFn = null;
  45776. }
  45777. finish();
  45778. }
  45779. });
  45780. };
  45781. var handleSegmentBytes = function handleSegmentBytes(_ref5) {
  45782. var segment = _ref5.segment,
  45783. bytes = _ref5.bytes,
  45784. trackInfoFn = _ref5.trackInfoFn,
  45785. timingInfoFn = _ref5.timingInfoFn,
  45786. videoSegmentTimingInfoFn = _ref5.videoSegmentTimingInfoFn,
  45787. audioSegmentTimingInfoFn = _ref5.audioSegmentTimingInfoFn,
  45788. id3Fn = _ref5.id3Fn,
  45789. captionsFn = _ref5.captionsFn,
  45790. isEndOfTimeline = _ref5.isEndOfTimeline,
  45791. endedTimelineFn = _ref5.endedTimelineFn,
  45792. dataFn = _ref5.dataFn,
  45793. doneFn = _ref5.doneFn,
  45794. onTransmuxerLog = _ref5.onTransmuxerLog;
  45795. var bytesAsUint8Array = new Uint8Array(bytes); // TODO:
  45796. // We should have a handler that fetches the number of bytes required
  45797. // to check if something is fmp4. This will allow us to save bandwidth
  45798. // because we can only blacklist a playlist and abort requests
  45799. // by codec after trackinfo triggers.
  45800. if (isLikelyFmp4MediaSegment(bytesAsUint8Array)) {
  45801. segment.isFmp4 = true;
  45802. var tracks = segment.map.tracks;
  45803. var trackInfo = {
  45804. isFmp4: true,
  45805. hasVideo: !!tracks.video,
  45806. hasAudio: !!tracks.audio
  45807. }; // if we have a audio track, with a codec that is not set to
  45808. // encrypted audio
  45809. if (tracks.audio && tracks.audio.codec && tracks.audio.codec !== 'enca') {
  45810. trackInfo.audioCodec = tracks.audio.codec;
  45811. } // if we have a video track, with a codec that is not set to
  45812. // encrypted video
  45813. if (tracks.video && tracks.video.codec && tracks.video.codec !== 'encv') {
  45814. trackInfo.videoCodec = tracks.video.codec;
  45815. }
  45816. if (tracks.video && tracks.audio) {
  45817. trackInfo.isMuxed = true;
  45818. } // since we don't support appending fmp4 data on progress, we know we have the full
  45819. // segment here
  45820. trackInfoFn(segment, trackInfo); // The probe doesn't provide the segment end time, so only callback with the start
  45821. // time. The end time can be roughly calculated by the receiver using the duration.
  45822. //
  45823. // Note that the start time returned by the probe reflects the baseMediaDecodeTime, as
  45824. // that is the true start of the segment (where the playback engine should begin
  45825. // decoding).
  45826. var finishLoading = function finishLoading(captions) {
  45827. // if the track still has audio at this point it is only possible
  45828. // for it to be audio only. See `tracks.video && tracks.audio` if statement
  45829. // above.
  45830. // we make sure to use segment.bytes here as that
  45831. dataFn(segment, {
  45832. data: bytesAsUint8Array,
  45833. type: trackInfo.hasAudio && !trackInfo.isMuxed ? 'audio' : 'video'
  45834. });
  45835. if (captions && captions.length) {
  45836. captionsFn(segment, captions);
  45837. }
  45838. doneFn(null, segment, {});
  45839. };
  45840. workerCallback({
  45841. action: 'probeMp4StartTime',
  45842. timescales: segment.map.timescales,
  45843. data: bytesAsUint8Array,
  45844. transmuxer: segment.transmuxer,
  45845. callback: function callback(_ref6) {
  45846. var data = _ref6.data,
  45847. startTime = _ref6.startTime; // transfer bytes back to us
  45848. bytes = data.buffer;
  45849. segment.bytes = bytesAsUint8Array = data;
  45850. if (trackInfo.hasAudio && !trackInfo.isMuxed) {
  45851. timingInfoFn(segment, 'audio', 'start', startTime);
  45852. }
  45853. if (trackInfo.hasVideo) {
  45854. timingInfoFn(segment, 'video', 'start', startTime);
  45855. } // Run through the CaptionParser in case there are captions.
  45856. // Initialize CaptionParser if it hasn't been yet
  45857. if (!tracks.video || !data.byteLength || !segment.transmuxer) {
  45858. finishLoading();
  45859. return;
  45860. }
  45861. workerCallback({
  45862. action: 'pushMp4Captions',
  45863. endAction: 'mp4Captions',
  45864. transmuxer: segment.transmuxer,
  45865. data: bytesAsUint8Array,
  45866. timescales: segment.map.timescales,
  45867. trackIds: [tracks.video.id],
  45868. callback: function callback(message) {
  45869. // transfer bytes back to us
  45870. bytes = message.data.buffer;
  45871. segment.bytes = bytesAsUint8Array = message.data;
  45872. message.logs.forEach(function (log) {
  45873. onTransmuxerLog(videojs.mergeOptions(log, {
  45874. stream: 'mp4CaptionParser'
  45875. }));
  45876. });
  45877. finishLoading(message.captions);
  45878. }
  45879. });
  45880. }
  45881. });
  45882. return;
  45883. } // VTT or other segments that don't need processing
  45884. if (!segment.transmuxer) {
  45885. doneFn(null, segment, {});
  45886. return;
  45887. }
  45888. if (typeof segment.container === 'undefined') {
  45889. segment.container = detectContainerForBytes(bytesAsUint8Array);
  45890. }
  45891. if (segment.container !== 'ts' && segment.container !== 'aac') {
  45892. trackInfoFn(segment, {
  45893. hasAudio: false,
  45894. hasVideo: false
  45895. });
  45896. doneFn(null, segment, {});
  45897. return;
  45898. } // ts or aac
  45899. transmuxAndNotify({
  45900. segment: segment,
  45901. bytes: bytes,
  45902. trackInfoFn: trackInfoFn,
  45903. timingInfoFn: timingInfoFn,
  45904. videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
  45905. audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
  45906. id3Fn: id3Fn,
  45907. captionsFn: captionsFn,
  45908. isEndOfTimeline: isEndOfTimeline,
  45909. endedTimelineFn: endedTimelineFn,
  45910. dataFn: dataFn,
  45911. doneFn: doneFn,
  45912. onTransmuxerLog: onTransmuxerLog
  45913. });
  45914. };
  45915. var decrypt = function decrypt(_ref7, callback) {
  45916. var id = _ref7.id,
  45917. key = _ref7.key,
  45918. encryptedBytes = _ref7.encryptedBytes,
  45919. decryptionWorker = _ref7.decryptionWorker;
  45920. var decryptionHandler = function decryptionHandler(event) {
  45921. if (event.data.source === id) {
  45922. decryptionWorker.removeEventListener('message', decryptionHandler);
  45923. var decrypted = event.data.decrypted;
  45924. callback(new Uint8Array(decrypted.bytes, decrypted.byteOffset, decrypted.byteLength));
  45925. }
  45926. };
  45927. decryptionWorker.addEventListener('message', decryptionHandler);
  45928. var keyBytes;
  45929. if (key.bytes.slice) {
  45930. keyBytes = key.bytes.slice();
  45931. } else {
  45932. keyBytes = new Uint32Array(Array.prototype.slice.call(key.bytes));
  45933. } // incrementally decrypt the bytes
  45934. decryptionWorker.postMessage(createTransferableMessage({
  45935. source: id,
  45936. encrypted: encryptedBytes,
  45937. key: keyBytes,
  45938. iv: key.iv
  45939. }), [encryptedBytes.buffer, keyBytes.buffer]);
  45940. };
  45941. /**
  45942. * Decrypt the segment via the decryption web worker
  45943. *
  45944. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  45945. * routines
  45946. * @param {Object} segment - a simplified copy of the segmentInfo object
  45947. * from SegmentLoader
  45948. * @param {Function} trackInfoFn - a callback that receives track info
  45949. * @param {Function} timingInfoFn - a callback that receives timing info
  45950. * @param {Function} videoSegmentTimingInfoFn
  45951. * a callback that receives video timing info based on media times and
  45952. * any adjustments made by the transmuxer
  45953. * @param {Function} audioSegmentTimingInfoFn
  45954. * a callback that receives audio timing info based on media times and
  45955. * any adjustments made by the transmuxer
  45956. * @param {boolean} isEndOfTimeline
  45957. * true if this segment represents the last segment in a timeline
  45958. * @param {Function} endedTimelineFn
  45959. * a callback made when a timeline is ended, will only be called if
  45960. * isEndOfTimeline is true
  45961. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  45962. * and ready to use
  45963. * @param {Function} doneFn - a callback that is executed after decryption has completed
  45964. */
  45965. var decryptSegment = function decryptSegment(_ref8) {
  45966. var decryptionWorker = _ref8.decryptionWorker,
  45967. segment = _ref8.segment,
  45968. trackInfoFn = _ref8.trackInfoFn,
  45969. timingInfoFn = _ref8.timingInfoFn,
  45970. videoSegmentTimingInfoFn = _ref8.videoSegmentTimingInfoFn,
  45971. audioSegmentTimingInfoFn = _ref8.audioSegmentTimingInfoFn,
  45972. id3Fn = _ref8.id3Fn,
  45973. captionsFn = _ref8.captionsFn,
  45974. isEndOfTimeline = _ref8.isEndOfTimeline,
  45975. endedTimelineFn = _ref8.endedTimelineFn,
  45976. dataFn = _ref8.dataFn,
  45977. doneFn = _ref8.doneFn,
  45978. onTransmuxerLog = _ref8.onTransmuxerLog;
  45979. decrypt({
  45980. id: segment.requestId,
  45981. key: segment.key,
  45982. encryptedBytes: segment.encryptedBytes,
  45983. decryptionWorker: decryptionWorker
  45984. }, function (decryptedBytes) {
  45985. segment.bytes = decryptedBytes;
  45986. handleSegmentBytes({
  45987. segment: segment,
  45988. bytes: segment.bytes,
  45989. trackInfoFn: trackInfoFn,
  45990. timingInfoFn: timingInfoFn,
  45991. videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
  45992. audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
  45993. id3Fn: id3Fn,
  45994. captionsFn: captionsFn,
  45995. isEndOfTimeline: isEndOfTimeline,
  45996. endedTimelineFn: endedTimelineFn,
  45997. dataFn: dataFn,
  45998. doneFn: doneFn,
  45999. onTransmuxerLog: onTransmuxerLog
  46000. });
  46001. });
  46002. };
  46003. /**
  46004. * This function waits for all XHRs to finish (with either success or failure)
  46005. * before continueing processing via it's callback. The function gathers errors
  46006. * from each request into a single errors array so that the error status for
  46007. * each request can be examined later.
  46008. *
  46009. * @param {Object} activeXhrs - an object that tracks all XHR requests
  46010. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  46011. * routines
  46012. * @param {Function} trackInfoFn - a callback that receives track info
  46013. * @param {Function} timingInfoFn - a callback that receives timing info
  46014. * @param {Function} videoSegmentTimingInfoFn
  46015. * a callback that receives video timing info based on media times and
  46016. * any adjustments made by the transmuxer
  46017. * @param {Function} audioSegmentTimingInfoFn
  46018. * a callback that receives audio timing info based on media times and
  46019. * any adjustments made by the transmuxer
  46020. * @param {Function} id3Fn - a callback that receives ID3 metadata
  46021. * @param {Function} captionsFn - a callback that receives captions
  46022. * @param {boolean} isEndOfTimeline
  46023. * true if this segment represents the last segment in a timeline
  46024. * @param {Function} endedTimelineFn
  46025. * a callback made when a timeline is ended, will only be called if
  46026. * isEndOfTimeline is true
  46027. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  46028. * and ready to use
  46029. * @param {Function} doneFn - a callback that is executed after all resources have been
  46030. * downloaded and any decryption completed
  46031. */
  46032. var waitForCompletion = function waitForCompletion(_ref9) {
  46033. var activeXhrs = _ref9.activeXhrs,
  46034. decryptionWorker = _ref9.decryptionWorker,
  46035. trackInfoFn = _ref9.trackInfoFn,
  46036. timingInfoFn = _ref9.timingInfoFn,
  46037. videoSegmentTimingInfoFn = _ref9.videoSegmentTimingInfoFn,
  46038. audioSegmentTimingInfoFn = _ref9.audioSegmentTimingInfoFn,
  46039. id3Fn = _ref9.id3Fn,
  46040. captionsFn = _ref9.captionsFn,
  46041. isEndOfTimeline = _ref9.isEndOfTimeline,
  46042. endedTimelineFn = _ref9.endedTimelineFn,
  46043. dataFn = _ref9.dataFn,
  46044. doneFn = _ref9.doneFn,
  46045. onTransmuxerLog = _ref9.onTransmuxerLog;
  46046. var count = 0;
  46047. var didError = false;
  46048. return function (error, segment) {
  46049. if (didError) {
  46050. return;
  46051. }
  46052. if (error) {
  46053. didError = true; // If there are errors, we have to abort any outstanding requests
  46054. abortAll(activeXhrs); // Even though the requests above are aborted, and in theory we could wait until we
  46055. // handle the aborted events from those requests, there are some cases where we may
  46056. // never get an aborted event. For instance, if the network connection is lost and
  46057. // there were two requests, the first may have triggered an error immediately, while
  46058. // the second request remains unsent. In that case, the aborted algorithm will not
  46059. // trigger an abort: see https://xhr.spec.whatwg.org/#the-abort()-method
  46060. //
  46061. // We also can't rely on the ready state of the XHR, since the request that
  46062. // triggered the connection error may also show as a ready state of 0 (unsent).
  46063. // Therefore, we have to finish this group of requests immediately after the first
  46064. // seen error.
  46065. return doneFn(error, segment);
  46066. }
  46067. count += 1;
  46068. if (count === activeXhrs.length) {
  46069. var segmentFinish = function segmentFinish() {
  46070. if (segment.encryptedBytes) {
  46071. return decryptSegment({
  46072. decryptionWorker: decryptionWorker,
  46073. segment: segment,
  46074. trackInfoFn: trackInfoFn,
  46075. timingInfoFn: timingInfoFn,
  46076. videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
  46077. audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
  46078. id3Fn: id3Fn,
  46079. captionsFn: captionsFn,
  46080. isEndOfTimeline: isEndOfTimeline,
  46081. endedTimelineFn: endedTimelineFn,
  46082. dataFn: dataFn,
  46083. doneFn: doneFn,
  46084. onTransmuxerLog: onTransmuxerLog
  46085. });
  46086. } // Otherwise, everything is ready just continue
  46087. handleSegmentBytes({
  46088. segment: segment,
  46089. bytes: segment.bytes,
  46090. trackInfoFn: trackInfoFn,
  46091. timingInfoFn: timingInfoFn,
  46092. videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
  46093. audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
  46094. id3Fn: id3Fn,
  46095. captionsFn: captionsFn,
  46096. isEndOfTimeline: isEndOfTimeline,
  46097. endedTimelineFn: endedTimelineFn,
  46098. dataFn: dataFn,
  46099. doneFn: doneFn,
  46100. onTransmuxerLog: onTransmuxerLog
  46101. });
  46102. }; // Keep track of when *all* of the requests have completed
  46103. segment.endOfAllRequests = Date.now();
  46104. if (segment.map && segment.map.encryptedBytes && !segment.map.bytes) {
  46105. return decrypt({
  46106. decryptionWorker: decryptionWorker,
  46107. // add -init to the "id" to differentiate between segment
  46108. // and init segment decryption, just in case they happen
  46109. // at the same time at some point in the future.
  46110. id: segment.requestId + '-init',
  46111. encryptedBytes: segment.map.encryptedBytes,
  46112. key: segment.map.key
  46113. }, function (decryptedBytes) {
  46114. segment.map.bytes = decryptedBytes;
  46115. parseInitSegment(segment, function (parseError) {
  46116. if (parseError) {
  46117. abortAll(activeXhrs);
  46118. return doneFn(parseError, segment);
  46119. }
  46120. segmentFinish();
  46121. });
  46122. });
  46123. }
  46124. segmentFinish();
  46125. }
  46126. };
  46127. };
  46128. /**
  46129. * Calls the abort callback if any request within the batch was aborted. Will only call
  46130. * the callback once per batch of requests, even if multiple were aborted.
  46131. *
  46132. * @param {Object} loadendState - state to check to see if the abort function was called
  46133. * @param {Function} abortFn - callback to call for abort
  46134. */
  46135. var handleLoadEnd = function handleLoadEnd(_ref10) {
  46136. var loadendState = _ref10.loadendState,
  46137. abortFn = _ref10.abortFn;
  46138. return function (event) {
  46139. var request = event.target;
  46140. if (request.aborted && abortFn && !loadendState.calledAbortFn) {
  46141. abortFn();
  46142. loadendState.calledAbortFn = true;
  46143. }
  46144. };
  46145. };
  46146. /**
  46147. * Simple progress event callback handler that gathers some stats before
  46148. * executing a provided callback with the `segment` object
  46149. *
  46150. * @param {Object} segment - a simplified copy of the segmentInfo object
  46151. * from SegmentLoader
  46152. * @param {Function} progressFn - a callback that is executed each time a progress event
  46153. * is received
  46154. * @param {Function} trackInfoFn - a callback that receives track info
  46155. * @param {Function} timingInfoFn - a callback that receives timing info
  46156. * @param {Function} videoSegmentTimingInfoFn
  46157. * a callback that receives video timing info based on media times and
  46158. * any adjustments made by the transmuxer
  46159. * @param {Function} audioSegmentTimingInfoFn
  46160. * a callback that receives audio timing info based on media times and
  46161. * any adjustments made by the transmuxer
  46162. * @param {boolean} isEndOfTimeline
  46163. * true if this segment represents the last segment in a timeline
  46164. * @param {Function} endedTimelineFn
  46165. * a callback made when a timeline is ended, will only be called if
  46166. * isEndOfTimeline is true
  46167. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  46168. * and ready to use
  46169. * @param {Event} event - the progress event object from XMLHttpRequest
  46170. */
  46171. var handleProgress = function handleProgress(_ref11) {
  46172. var segment = _ref11.segment,
  46173. progressFn = _ref11.progressFn;
  46174. _ref11.trackInfoFn;
  46175. _ref11.timingInfoFn;
  46176. _ref11.videoSegmentTimingInfoFn;
  46177. _ref11.audioSegmentTimingInfoFn;
  46178. _ref11.id3Fn;
  46179. _ref11.captionsFn;
  46180. _ref11.isEndOfTimeline;
  46181. _ref11.endedTimelineFn;
  46182. _ref11.dataFn;
  46183. return function (event) {
  46184. var request = event.target;
  46185. if (request.aborted) {
  46186. return;
  46187. }
  46188. segment.stats = videojs.mergeOptions(segment.stats, getProgressStats(event)); // record the time that we receive the first byte of data
  46189. if (!segment.stats.firstBytesReceivedAt && segment.stats.bytesReceived) {
  46190. segment.stats.firstBytesReceivedAt = Date.now();
  46191. }
  46192. return progressFn(event, segment);
  46193. };
  46194. };
  46195. /**
  46196. * Load all resources and does any processing necessary for a media-segment
  46197. *
  46198. * Features:
  46199. * decrypts the media-segment if it has a key uri and an iv
  46200. * aborts *all* requests if *any* one request fails
  46201. *
  46202. * The segment object, at minimum, has the following format:
  46203. * {
  46204. * resolvedUri: String,
  46205. * [transmuxer]: Object,
  46206. * [byterange]: {
  46207. * offset: Number,
  46208. * length: Number
  46209. * },
  46210. * [key]: {
  46211. * resolvedUri: String
  46212. * [byterange]: {
  46213. * offset: Number,
  46214. * length: Number
  46215. * },
  46216. * iv: {
  46217. * bytes: Uint32Array
  46218. * }
  46219. * },
  46220. * [map]: {
  46221. * resolvedUri: String,
  46222. * [byterange]: {
  46223. * offset: Number,
  46224. * length: Number
  46225. * },
  46226. * [bytes]: Uint8Array
  46227. * }
  46228. * }
  46229. * ...where [name] denotes optional properties
  46230. *
  46231. * @param {Function} xhr - an instance of the xhr wrapper in xhr.js
  46232. * @param {Object} xhrOptions - the base options to provide to all xhr requests
  46233. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128
  46234. * decryption routines
  46235. * @param {Object} segment - a simplified copy of the segmentInfo object
  46236. * from SegmentLoader
  46237. * @param {Function} abortFn - a callback called (only once) if any piece of a request was
  46238. * aborted
  46239. * @param {Function} progressFn - a callback that receives progress events from the main
  46240. * segment's xhr request
  46241. * @param {Function} trackInfoFn - a callback that receives track info
  46242. * @param {Function} timingInfoFn - a callback that receives timing info
  46243. * @param {Function} videoSegmentTimingInfoFn
  46244. * a callback that receives video timing info based on media times and
  46245. * any adjustments made by the transmuxer
  46246. * @param {Function} audioSegmentTimingInfoFn
  46247. * a callback that receives audio timing info based on media times and
  46248. * any adjustments made by the transmuxer
  46249. * @param {Function} id3Fn - a callback that receives ID3 metadata
  46250. * @param {Function} captionsFn - a callback that receives captions
  46251. * @param {boolean} isEndOfTimeline
  46252. * true if this segment represents the last segment in a timeline
  46253. * @param {Function} endedTimelineFn
  46254. * a callback made when a timeline is ended, will only be called if
  46255. * isEndOfTimeline is true
  46256. * @param {Function} dataFn - a callback that receives data from the main segment's xhr
  46257. * request, transmuxed if needed
  46258. * @param {Function} doneFn - a callback that is executed only once all requests have
  46259. * succeeded or failed
  46260. * @return {Function} a function that, when invoked, immediately aborts all
  46261. * outstanding requests
  46262. */
  46263. var mediaSegmentRequest = function mediaSegmentRequest(_ref12) {
  46264. var xhr = _ref12.xhr,
  46265. xhrOptions = _ref12.xhrOptions,
  46266. decryptionWorker = _ref12.decryptionWorker,
  46267. segment = _ref12.segment,
  46268. abortFn = _ref12.abortFn,
  46269. progressFn = _ref12.progressFn,
  46270. trackInfoFn = _ref12.trackInfoFn,
  46271. timingInfoFn = _ref12.timingInfoFn,
  46272. videoSegmentTimingInfoFn = _ref12.videoSegmentTimingInfoFn,
  46273. audioSegmentTimingInfoFn = _ref12.audioSegmentTimingInfoFn,
  46274. id3Fn = _ref12.id3Fn,
  46275. captionsFn = _ref12.captionsFn,
  46276. isEndOfTimeline = _ref12.isEndOfTimeline,
  46277. endedTimelineFn = _ref12.endedTimelineFn,
  46278. dataFn = _ref12.dataFn,
  46279. doneFn = _ref12.doneFn,
  46280. onTransmuxerLog = _ref12.onTransmuxerLog;
  46281. var activeXhrs = [];
  46282. var finishProcessingFn = waitForCompletion({
  46283. activeXhrs: activeXhrs,
  46284. decryptionWorker: decryptionWorker,
  46285. trackInfoFn: trackInfoFn,
  46286. timingInfoFn: timingInfoFn,
  46287. videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
  46288. audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
  46289. id3Fn: id3Fn,
  46290. captionsFn: captionsFn,
  46291. isEndOfTimeline: isEndOfTimeline,
  46292. endedTimelineFn: endedTimelineFn,
  46293. dataFn: dataFn,
  46294. doneFn: doneFn,
  46295. onTransmuxerLog: onTransmuxerLog
  46296. }); // optionally, request the decryption key
  46297. if (segment.key && !segment.key.bytes) {
  46298. var objects = [segment.key];
  46299. if (segment.map && !segment.map.bytes && segment.map.key && segment.map.key.resolvedUri === segment.key.resolvedUri) {
  46300. objects.push(segment.map.key);
  46301. }
  46302. var keyRequestOptions = videojs.mergeOptions(xhrOptions, {
  46303. uri: segment.key.resolvedUri,
  46304. responseType: 'arraybuffer'
  46305. });
  46306. var keyRequestCallback = handleKeyResponse(segment, objects, finishProcessingFn);
  46307. var keyXhr = xhr(keyRequestOptions, keyRequestCallback);
  46308. activeXhrs.push(keyXhr);
  46309. } // optionally, request the associated media init segment
  46310. if (segment.map && !segment.map.bytes) {
  46311. var differentMapKey = segment.map.key && (!segment.key || segment.key.resolvedUri !== segment.map.key.resolvedUri);
  46312. if (differentMapKey) {
  46313. var mapKeyRequestOptions = videojs.mergeOptions(xhrOptions, {
  46314. uri: segment.map.key.resolvedUri,
  46315. responseType: 'arraybuffer'
  46316. });
  46317. var mapKeyRequestCallback = handleKeyResponse(segment, [segment.map.key], finishProcessingFn);
  46318. var mapKeyXhr = xhr(mapKeyRequestOptions, mapKeyRequestCallback);
  46319. activeXhrs.push(mapKeyXhr);
  46320. }
  46321. var initSegmentOptions = videojs.mergeOptions(xhrOptions, {
  46322. uri: segment.map.resolvedUri,
  46323. responseType: 'arraybuffer',
  46324. headers: segmentXhrHeaders(segment.map)
  46325. });
  46326. var initSegmentRequestCallback = handleInitSegmentResponse({
  46327. segment: segment,
  46328. finishProcessingFn: finishProcessingFn
  46329. });
  46330. var initSegmentXhr = xhr(initSegmentOptions, initSegmentRequestCallback);
  46331. activeXhrs.push(initSegmentXhr);
  46332. }
  46333. var segmentRequestOptions = videojs.mergeOptions(xhrOptions, {
  46334. uri: segment.part && segment.part.resolvedUri || segment.resolvedUri,
  46335. responseType: 'arraybuffer',
  46336. headers: segmentXhrHeaders(segment)
  46337. });
  46338. var segmentRequestCallback = handleSegmentResponse({
  46339. segment: segment,
  46340. finishProcessingFn: finishProcessingFn,
  46341. responseType: segmentRequestOptions.responseType
  46342. });
  46343. var segmentXhr = xhr(segmentRequestOptions, segmentRequestCallback);
  46344. segmentXhr.addEventListener('progress', handleProgress({
  46345. segment: segment,
  46346. progressFn: progressFn,
  46347. trackInfoFn: trackInfoFn,
  46348. timingInfoFn: timingInfoFn,
  46349. videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
  46350. audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
  46351. id3Fn: id3Fn,
  46352. captionsFn: captionsFn,
  46353. isEndOfTimeline: isEndOfTimeline,
  46354. endedTimelineFn: endedTimelineFn,
  46355. dataFn: dataFn
  46356. }));
  46357. activeXhrs.push(segmentXhr); // since all parts of the request must be considered, but should not make callbacks
  46358. // multiple times, provide a shared state object
  46359. var loadendState = {};
  46360. activeXhrs.forEach(function (activeXhr) {
  46361. activeXhr.addEventListener('loadend', handleLoadEnd({
  46362. loadendState: loadendState,
  46363. abortFn: abortFn
  46364. }));
  46365. });
  46366. return function () {
  46367. return abortAll(activeXhrs);
  46368. };
  46369. };
  46370. /**
  46371. * @file - codecs.js - Handles tasks regarding codec strings such as translating them to
  46372. * codec strings, or translating codec strings into objects that can be examined.
  46373. */
  46374. var logFn$1 = logger('CodecUtils');
  46375. /**
  46376. * Returns a set of codec strings parsed from the playlist or the default
  46377. * codec strings if no codecs were specified in the playlist
  46378. *
  46379. * @param {Playlist} media the current media playlist
  46380. * @return {Object} an object with the video and audio codecs
  46381. */
  46382. var getCodecs = function getCodecs(media) {
  46383. // if the codecs were explicitly specified, use them instead of the
  46384. // defaults
  46385. var mediaAttributes = media.attributes || {};
  46386. if (mediaAttributes.CODECS) {
  46387. return parseCodecs(mediaAttributes.CODECS);
  46388. }
  46389. };
  46390. var isMaat = function isMaat(master, media) {
  46391. var mediaAttributes = media.attributes || {};
  46392. return master && master.mediaGroups && master.mediaGroups.AUDIO && mediaAttributes.AUDIO && master.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  46393. };
  46394. var isMuxed = function isMuxed(master, media) {
  46395. if (!isMaat(master, media)) {
  46396. return true;
  46397. }
  46398. var mediaAttributes = media.attributes || {};
  46399. var audioGroup = master.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  46400. for (var groupId in audioGroup) {
  46401. // If an audio group has a URI (the case for HLS, as HLS will use external playlists),
  46402. // or there are listed playlists (the case for DASH, as the manifest will have already
  46403. // provided all of the details necessary to generate the audio playlist, as opposed to
  46404. // HLS' externally requested playlists), then the content is demuxed.
  46405. if (!audioGroup[groupId].uri && !audioGroup[groupId].playlists) {
  46406. return true;
  46407. }
  46408. }
  46409. return false;
  46410. };
  46411. var unwrapCodecList = function unwrapCodecList(codecList) {
  46412. var codecs = {};
  46413. codecList.forEach(function (_ref) {
  46414. var mediaType = _ref.mediaType,
  46415. type = _ref.type,
  46416. details = _ref.details;
  46417. codecs[mediaType] = codecs[mediaType] || [];
  46418. codecs[mediaType].push(translateLegacyCodec("" + type + details));
  46419. });
  46420. Object.keys(codecs).forEach(function (mediaType) {
  46421. if (codecs[mediaType].length > 1) {
  46422. logFn$1("multiple " + mediaType + " codecs found as attributes: " + codecs[mediaType].join(', ') + ". Setting playlist codecs to null so that we wait for mux.js to probe segments for real codecs.");
  46423. codecs[mediaType] = null;
  46424. return;
  46425. }
  46426. codecs[mediaType] = codecs[mediaType][0];
  46427. });
  46428. return codecs;
  46429. };
  46430. var codecCount = function codecCount(codecObj) {
  46431. var count = 0;
  46432. if (codecObj.audio) {
  46433. count++;
  46434. }
  46435. if (codecObj.video) {
  46436. count++;
  46437. }
  46438. return count;
  46439. };
  46440. /**
  46441. * Calculates the codec strings for a working configuration of
  46442. * SourceBuffers to play variant streams in a master playlist. If
  46443. * there is no possible working configuration, an empty object will be
  46444. * returned.
  46445. *
  46446. * @param master {Object} the m3u8 object for the master playlist
  46447. * @param media {Object} the m3u8 object for the variant playlist
  46448. * @return {Object} the codec strings.
  46449. *
  46450. * @private
  46451. */
  46452. var codecsForPlaylist = function codecsForPlaylist(master, media) {
  46453. var mediaAttributes = media.attributes || {};
  46454. var codecInfo = unwrapCodecList(getCodecs(media) || []); // HLS with multiple-audio tracks must always get an audio codec.
  46455. // Put another way, there is no way to have a video-only multiple-audio HLS!
  46456. if (isMaat(master, media) && !codecInfo.audio) {
  46457. if (!isMuxed(master, media)) {
  46458. // It is possible for codecs to be specified on the audio media group playlist but
  46459. // not on the rendition playlist. This is mostly the case for DASH, where audio and
  46460. // video are always separate (and separately specified).
  46461. var defaultCodecs = unwrapCodecList(codecsFromDefault(master, mediaAttributes.AUDIO) || []);
  46462. if (defaultCodecs.audio) {
  46463. codecInfo.audio = defaultCodecs.audio;
  46464. }
  46465. }
  46466. }
  46467. return codecInfo;
  46468. };
  46469. var logFn = logger('PlaylistSelector');
  46470. var representationToString = function representationToString(representation) {
  46471. if (!representation || !representation.playlist) {
  46472. return;
  46473. }
  46474. var playlist = representation.playlist;
  46475. return JSON.stringify({
  46476. id: playlist.id,
  46477. bandwidth: representation.bandwidth,
  46478. width: representation.width,
  46479. height: representation.height,
  46480. codecs: playlist.attributes && playlist.attributes.CODECS || ''
  46481. });
  46482. }; // Utilities
  46483. /**
  46484. * Returns the CSS value for the specified property on an element
  46485. * using `getComputedStyle`. Firefox has a long-standing issue where
  46486. * getComputedStyle() may return null when running in an iframe with
  46487. * `display: none`.
  46488. *
  46489. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  46490. * @param {HTMLElement} el the htmlelement to work on
  46491. * @param {string} the proprety to get the style for
  46492. */
  46493. var safeGetComputedStyle = function safeGetComputedStyle(el, property) {
  46494. if (!el) {
  46495. return '';
  46496. }
  46497. var result = window.getComputedStyle(el);
  46498. if (!result) {
  46499. return '';
  46500. }
  46501. return result[property];
  46502. };
  46503. /**
  46504. * Resuable stable sort function
  46505. *
  46506. * @param {Playlists} array
  46507. * @param {Function} sortFn Different comparators
  46508. * @function stableSort
  46509. */
  46510. var stableSort = function stableSort(array, sortFn) {
  46511. var newArray = array.slice();
  46512. array.sort(function (left, right) {
  46513. var cmp = sortFn(left, right);
  46514. if (cmp === 0) {
  46515. return newArray.indexOf(left) - newArray.indexOf(right);
  46516. }
  46517. return cmp;
  46518. });
  46519. };
  46520. /**
  46521. * A comparator function to sort two playlist object by bandwidth.
  46522. *
  46523. * @param {Object} left a media playlist object
  46524. * @param {Object} right a media playlist object
  46525. * @return {number} Greater than zero if the bandwidth attribute of
  46526. * left is greater than the corresponding attribute of right. Less
  46527. * than zero if the bandwidth of right is greater than left and
  46528. * exactly zero if the two are equal.
  46529. */
  46530. var comparePlaylistBandwidth = function comparePlaylistBandwidth(left, right) {
  46531. var leftBandwidth;
  46532. var rightBandwidth;
  46533. if (left.attributes.BANDWIDTH) {
  46534. leftBandwidth = left.attributes.BANDWIDTH;
  46535. }
  46536. leftBandwidth = leftBandwidth || window.Number.MAX_VALUE;
  46537. if (right.attributes.BANDWIDTH) {
  46538. rightBandwidth = right.attributes.BANDWIDTH;
  46539. }
  46540. rightBandwidth = rightBandwidth || window.Number.MAX_VALUE;
  46541. return leftBandwidth - rightBandwidth;
  46542. };
  46543. /**
  46544. * A comparator function to sort two playlist object by resolution (width).
  46545. *
  46546. * @param {Object} left a media playlist object
  46547. * @param {Object} right a media playlist object
  46548. * @return {number} Greater than zero if the resolution.width attribute of
  46549. * left is greater than the corresponding attribute of right. Less
  46550. * than zero if the resolution.width of right is greater than left and
  46551. * exactly zero if the two are equal.
  46552. */
  46553. var comparePlaylistResolution = function comparePlaylistResolution(left, right) {
  46554. var leftWidth;
  46555. var rightWidth;
  46556. if (left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {
  46557. leftWidth = left.attributes.RESOLUTION.width;
  46558. }
  46559. leftWidth = leftWidth || window.Number.MAX_VALUE;
  46560. if (right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {
  46561. rightWidth = right.attributes.RESOLUTION.width;
  46562. }
  46563. rightWidth = rightWidth || window.Number.MAX_VALUE; // NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions
  46564. // have the same media dimensions/ resolution
  46565. if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {
  46566. return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
  46567. }
  46568. return leftWidth - rightWidth;
  46569. };
  46570. /**
  46571. * Chooses the appropriate media playlist based on bandwidth and player size
  46572. *
  46573. * @param {Object} master
  46574. * Object representation of the master manifest
  46575. * @param {number} playerBandwidth
  46576. * Current calculated bandwidth of the player
  46577. * @param {number} playerWidth
  46578. * Current width of the player element (should account for the device pixel ratio)
  46579. * @param {number} playerHeight
  46580. * Current height of the player element (should account for the device pixel ratio)
  46581. * @param {boolean} limitRenditionByPlayerDimensions
  46582. * True if the player width and height should be used during the selection, false otherwise
  46583. * @param {Object} masterPlaylistController
  46584. * the current masterPlaylistController object
  46585. * @return {Playlist} the highest bitrate playlist less than the
  46586. * currently detected bandwidth, accounting for some amount of
  46587. * bandwidth variance
  46588. */
  46589. var simpleSelector = function simpleSelector(master, playerBandwidth, playerWidth, playerHeight, limitRenditionByPlayerDimensions, masterPlaylistController) {
  46590. // If we end up getting called before `master` is available, exit early
  46591. if (!master) {
  46592. return;
  46593. }
  46594. var options = {
  46595. bandwidth: playerBandwidth,
  46596. width: playerWidth,
  46597. height: playerHeight,
  46598. limitRenditionByPlayerDimensions: limitRenditionByPlayerDimensions
  46599. };
  46600. var playlists = master.playlists; // if playlist is audio only, select between currently active audio group playlists.
  46601. if (Playlist.isAudioOnly(master)) {
  46602. playlists = masterPlaylistController.getAudioTrackPlaylists_(); // add audioOnly to options so that we log audioOnly: true
  46603. // at the buttom of this function for debugging.
  46604. options.audioOnly = true;
  46605. } // convert the playlists to an intermediary representation to make comparisons easier
  46606. var sortedPlaylistReps = playlists.map(function (playlist) {
  46607. var bandwidth;
  46608. var width = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.width;
  46609. var height = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height;
  46610. bandwidth = playlist.attributes && playlist.attributes.BANDWIDTH;
  46611. bandwidth = bandwidth || window.Number.MAX_VALUE;
  46612. return {
  46613. bandwidth: bandwidth,
  46614. width: width,
  46615. height: height,
  46616. playlist: playlist
  46617. };
  46618. });
  46619. stableSort(sortedPlaylistReps, function (left, right) {
  46620. return left.bandwidth - right.bandwidth;
  46621. }); // filter out any playlists that have been excluded due to
  46622. // incompatible configurations
  46623. sortedPlaylistReps = sortedPlaylistReps.filter(function (rep) {
  46624. return !Playlist.isIncompatible(rep.playlist);
  46625. }); // filter out any playlists that have been disabled manually through the representations
  46626. // api or blacklisted temporarily due to playback errors.
  46627. var enabledPlaylistReps = sortedPlaylistReps.filter(function (rep) {
  46628. return Playlist.isEnabled(rep.playlist);
  46629. });
  46630. if (!enabledPlaylistReps.length) {
  46631. // if there are no enabled playlists, then they have all been blacklisted or disabled
  46632. // by the user through the representations api. In this case, ignore blacklisting and
  46633. // fallback to what the user wants by using playlists the user has not disabled.
  46634. enabledPlaylistReps = sortedPlaylistReps.filter(function (rep) {
  46635. return !Playlist.isDisabled(rep.playlist);
  46636. });
  46637. } // filter out any variant that has greater effective bitrate
  46638. // than the current estimated bandwidth
  46639. var bandwidthPlaylistReps = enabledPlaylistReps.filter(function (rep) {
  46640. return rep.bandwidth * Config.BANDWIDTH_VARIANCE < playerBandwidth;
  46641. });
  46642. var highestRemainingBandwidthRep = bandwidthPlaylistReps[bandwidthPlaylistReps.length - 1]; // get all of the renditions with the same (highest) bandwidth
  46643. // and then taking the very first element
  46644. var bandwidthBestRep = bandwidthPlaylistReps.filter(function (rep) {
  46645. return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
  46646. })[0]; // if we're not going to limit renditions by player size, make an early decision.
  46647. if (limitRenditionByPlayerDimensions === false) {
  46648. var _chosenRep = bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  46649. if (_chosenRep && _chosenRep.playlist) {
  46650. var type = 'sortedPlaylistReps';
  46651. if (bandwidthBestRep) {
  46652. type = 'bandwidthBestRep';
  46653. }
  46654. if (enabledPlaylistReps[0]) {
  46655. type = 'enabledPlaylistReps';
  46656. }
  46657. logFn("choosing " + representationToString(_chosenRep) + " using " + type + " with options", options);
  46658. return _chosenRep.playlist;
  46659. }
  46660. logFn('could not choose a playlist with options', options);
  46661. return null;
  46662. } // filter out playlists without resolution information
  46663. var haveResolution = bandwidthPlaylistReps.filter(function (rep) {
  46664. return rep.width && rep.height;
  46665. }); // sort variants by resolution
  46666. stableSort(haveResolution, function (left, right) {
  46667. return left.width - right.width;
  46668. }); // if we have the exact resolution as the player use it
  46669. var resolutionBestRepList = haveResolution.filter(function (rep) {
  46670. return rep.width === playerWidth && rep.height === playerHeight;
  46671. });
  46672. highestRemainingBandwidthRep = resolutionBestRepList[resolutionBestRepList.length - 1]; // ensure that we pick the highest bandwidth variant that have exact resolution
  46673. var resolutionBestRep = resolutionBestRepList.filter(function (rep) {
  46674. return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
  46675. })[0];
  46676. var resolutionPlusOneList;
  46677. var resolutionPlusOneSmallest;
  46678. var resolutionPlusOneRep; // find the smallest variant that is larger than the player
  46679. // if there is no match of exact resolution
  46680. if (!resolutionBestRep) {
  46681. resolutionPlusOneList = haveResolution.filter(function (rep) {
  46682. return rep.width > playerWidth || rep.height > playerHeight;
  46683. }); // find all the variants have the same smallest resolution
  46684. resolutionPlusOneSmallest = resolutionPlusOneList.filter(function (rep) {
  46685. return rep.width === resolutionPlusOneList[0].width && rep.height === resolutionPlusOneList[0].height;
  46686. }); // ensure that we also pick the highest bandwidth variant that
  46687. // is just-larger-than the video player
  46688. highestRemainingBandwidthRep = resolutionPlusOneSmallest[resolutionPlusOneSmallest.length - 1];
  46689. resolutionPlusOneRep = resolutionPlusOneSmallest.filter(function (rep) {
  46690. return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
  46691. })[0];
  46692. }
  46693. var leastPixelDiffRep; // If this selector proves to be better than others,
  46694. // resolutionPlusOneRep and resolutionBestRep and all
  46695. // the code involving them should be removed.
  46696. if (masterPlaylistController.experimentalLeastPixelDiffSelector) {
  46697. // find the variant that is closest to the player's pixel size
  46698. var leastPixelDiffList = haveResolution.map(function (rep) {
  46699. rep.pixelDiff = Math.abs(rep.width - playerWidth) + Math.abs(rep.height - playerHeight);
  46700. return rep;
  46701. }); // get the highest bandwidth, closest resolution playlist
  46702. stableSort(leastPixelDiffList, function (left, right) {
  46703. // sort by highest bandwidth if pixelDiff is the same
  46704. if (left.pixelDiff === right.pixelDiff) {
  46705. return right.bandwidth - left.bandwidth;
  46706. }
  46707. return left.pixelDiff - right.pixelDiff;
  46708. });
  46709. leastPixelDiffRep = leastPixelDiffList[0];
  46710. } // fallback chain of variants
  46711. var chosenRep = leastPixelDiffRep || resolutionPlusOneRep || resolutionBestRep || bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  46712. if (chosenRep && chosenRep.playlist) {
  46713. var _type = 'sortedPlaylistReps';
  46714. if (leastPixelDiffRep) {
  46715. _type = 'leastPixelDiffRep';
  46716. } else if (resolutionPlusOneRep) {
  46717. _type = 'resolutionPlusOneRep';
  46718. } else if (resolutionBestRep) {
  46719. _type = 'resolutionBestRep';
  46720. } else if (bandwidthBestRep) {
  46721. _type = 'bandwidthBestRep';
  46722. } else if (enabledPlaylistReps[0]) {
  46723. _type = 'enabledPlaylistReps';
  46724. }
  46725. logFn("choosing " + representationToString(chosenRep) + " using " + _type + " with options", options);
  46726. return chosenRep.playlist;
  46727. }
  46728. logFn('could not choose a playlist with options', options);
  46729. return null;
  46730. };
  46731. /**
  46732. * Chooses the appropriate media playlist based on the most recent
  46733. * bandwidth estimate and the player size.
  46734. *
  46735. * Expects to be called within the context of an instance of VhsHandler
  46736. *
  46737. * @return {Playlist} the highest bitrate playlist less than the
  46738. * currently detected bandwidth, accounting for some amount of
  46739. * bandwidth variance
  46740. */
  46741. var lastBandwidthSelector = function lastBandwidthSelector() {
  46742. var pixelRatio = this.useDevicePixelRatio ? window.devicePixelRatio || 1 : 1;
  46743. return simpleSelector(this.playlists.master, this.systemBandwidth, parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10) * pixelRatio, parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10) * pixelRatio, this.limitRenditionByPlayerDimensions, this.masterPlaylistController_);
  46744. };
  46745. /**
  46746. * Chooses the appropriate media playlist based on an
  46747. * exponential-weighted moving average of the bandwidth after
  46748. * filtering for player size.
  46749. *
  46750. * Expects to be called within the context of an instance of VhsHandler
  46751. *
  46752. * @param {number} decay - a number between 0 and 1. Higher values of
  46753. * this parameter will cause previous bandwidth estimates to lose
  46754. * significance more quickly.
  46755. * @return {Function} a function which can be invoked to create a new
  46756. * playlist selector function.
  46757. * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  46758. */
  46759. var movingAverageBandwidthSelector = function movingAverageBandwidthSelector(decay) {
  46760. var average = -1;
  46761. var lastSystemBandwidth = -1;
  46762. if (decay < 0 || decay > 1) {
  46763. throw new Error('Moving average bandwidth decay must be between 0 and 1.');
  46764. }
  46765. return function () {
  46766. var pixelRatio = this.useDevicePixelRatio ? window.devicePixelRatio || 1 : 1;
  46767. if (average < 0) {
  46768. average = this.systemBandwidth;
  46769. lastSystemBandwidth = this.systemBandwidth;
  46770. } // stop the average value from decaying for every 250ms
  46771. // when the systemBandwidth is constant
  46772. // and
  46773. // stop average from setting to a very low value when the
  46774. // systemBandwidth becomes 0 in case of chunk cancellation
  46775. if (this.systemBandwidth > 0 && this.systemBandwidth !== lastSystemBandwidth) {
  46776. average = decay * this.systemBandwidth + (1 - decay) * average;
  46777. lastSystemBandwidth = this.systemBandwidth;
  46778. }
  46779. return simpleSelector(this.playlists.master, average, parseInt(safeGetComputedStyle(this.tech_.el(), 'width'), 10) * pixelRatio, parseInt(safeGetComputedStyle(this.tech_.el(), 'height'), 10) * pixelRatio, this.limitRenditionByPlayerDimensions, this.masterPlaylistController_);
  46780. };
  46781. };
  46782. /**
  46783. * Chooses the appropriate media playlist based on the potential to rebuffer
  46784. *
  46785. * @param {Object} settings
  46786. * Object of information required to use this selector
  46787. * @param {Object} settings.master
  46788. * Object representation of the master manifest
  46789. * @param {number} settings.currentTime
  46790. * The current time of the player
  46791. * @param {number} settings.bandwidth
  46792. * Current measured bandwidth
  46793. * @param {number} settings.duration
  46794. * Duration of the media
  46795. * @param {number} settings.segmentDuration
  46796. * Segment duration to be used in round trip time calculations
  46797. * @param {number} settings.timeUntilRebuffer
  46798. * Time left in seconds until the player has to rebuffer
  46799. * @param {number} settings.currentTimeline
  46800. * The current timeline segments are being loaded from
  46801. * @param {SyncController} settings.syncController
  46802. * SyncController for determining if we have a sync point for a given playlist
  46803. * @return {Object|null}
  46804. * {Object} return.playlist
  46805. * The highest bandwidth playlist with the least amount of rebuffering
  46806. * {Number} return.rebufferingImpact
  46807. * The amount of time in seconds switching to this playlist will rebuffer. A
  46808. * negative value means that switching will cause zero rebuffering.
  46809. */
  46810. var minRebufferMaxBandwidthSelector = function minRebufferMaxBandwidthSelector(settings) {
  46811. var master = settings.master,
  46812. currentTime = settings.currentTime,
  46813. bandwidth = settings.bandwidth,
  46814. duration = settings.duration,
  46815. segmentDuration = settings.segmentDuration,
  46816. timeUntilRebuffer = settings.timeUntilRebuffer,
  46817. currentTimeline = settings.currentTimeline,
  46818. syncController = settings.syncController; // filter out any playlists that have been excluded due to
  46819. // incompatible configurations
  46820. var compatiblePlaylists = master.playlists.filter(function (playlist) {
  46821. return !Playlist.isIncompatible(playlist);
  46822. }); // filter out any playlists that have been disabled manually through the representations
  46823. // api or blacklisted temporarily due to playback errors.
  46824. var enabledPlaylists = compatiblePlaylists.filter(Playlist.isEnabled);
  46825. if (!enabledPlaylists.length) {
  46826. // if there are no enabled playlists, then they have all been blacklisted or disabled
  46827. // by the user through the representations api. In this case, ignore blacklisting and
  46828. // fallback to what the user wants by using playlists the user has not disabled.
  46829. enabledPlaylists = compatiblePlaylists.filter(function (playlist) {
  46830. return !Playlist.isDisabled(playlist);
  46831. });
  46832. }
  46833. var bandwidthPlaylists = enabledPlaylists.filter(Playlist.hasAttribute.bind(null, 'BANDWIDTH'));
  46834. var rebufferingEstimates = bandwidthPlaylists.map(function (playlist) {
  46835. var syncPoint = syncController.getSyncPoint(playlist, duration, currentTimeline, currentTime); // If there is no sync point for this playlist, switching to it will require a
  46836. // sync request first. This will double the request time
  46837. var numRequests = syncPoint ? 1 : 2;
  46838. var requestTimeEstimate = Playlist.estimateSegmentRequestTime(segmentDuration, bandwidth, playlist);
  46839. var rebufferingImpact = requestTimeEstimate * numRequests - timeUntilRebuffer;
  46840. return {
  46841. playlist: playlist,
  46842. rebufferingImpact: rebufferingImpact
  46843. };
  46844. });
  46845. var noRebufferingPlaylists = rebufferingEstimates.filter(function (estimate) {
  46846. return estimate.rebufferingImpact <= 0;
  46847. }); // Sort by bandwidth DESC
  46848. stableSort(noRebufferingPlaylists, function (a, b) {
  46849. return comparePlaylistBandwidth(b.playlist, a.playlist);
  46850. });
  46851. if (noRebufferingPlaylists.length) {
  46852. return noRebufferingPlaylists[0];
  46853. }
  46854. stableSort(rebufferingEstimates, function (a, b) {
  46855. return a.rebufferingImpact - b.rebufferingImpact;
  46856. });
  46857. return rebufferingEstimates[0] || null;
  46858. };
  46859. /**
  46860. * Chooses the appropriate media playlist, which in this case is the lowest bitrate
  46861. * one with video. If no renditions with video exist, return the lowest audio rendition.
  46862. *
  46863. * Expects to be called within the context of an instance of VhsHandler
  46864. *
  46865. * @return {Object|null}
  46866. * {Object} return.playlist
  46867. * The lowest bitrate playlist that contains a video codec. If no such rendition
  46868. * exists pick the lowest audio rendition.
  46869. */
  46870. var lowestBitrateCompatibleVariantSelector = function lowestBitrateCompatibleVariantSelector() {
  46871. var _this = this; // filter out any playlists that have been excluded due to
  46872. // incompatible configurations or playback errors
  46873. var playlists = this.playlists.master.playlists.filter(Playlist.isEnabled); // Sort ascending by bitrate
  46874. stableSort(playlists, function (a, b) {
  46875. return comparePlaylistBandwidth(a, b);
  46876. }); // Parse and assume that playlists with no video codec have no video
  46877. // (this is not necessarily true, although it is generally true).
  46878. //
  46879. // If an entire manifest has no valid videos everything will get filtered
  46880. // out.
  46881. var playlistsWithVideo = playlists.filter(function (playlist) {
  46882. return !!codecsForPlaylist(_this.playlists.master, playlist).video;
  46883. });
  46884. return playlistsWithVideo[0] || null;
  46885. };
  46886. /**
  46887. * Combine all segments into a single Uint8Array
  46888. *
  46889. * @param {Object} segmentObj
  46890. * @return {Uint8Array} concatenated bytes
  46891. * @private
  46892. */
  46893. var concatSegments = function concatSegments(segmentObj) {
  46894. var offset = 0;
  46895. var tempBuffer;
  46896. if (segmentObj.bytes) {
  46897. tempBuffer = new Uint8Array(segmentObj.bytes); // combine the individual segments into one large typed-array
  46898. segmentObj.segments.forEach(function (segment) {
  46899. tempBuffer.set(segment, offset);
  46900. offset += segment.byteLength;
  46901. });
  46902. }
  46903. return tempBuffer;
  46904. };
  46905. /**
  46906. * @file text-tracks.js
  46907. */
  46908. /**
  46909. * Create captions text tracks on video.js if they do not exist
  46910. *
  46911. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  46912. * @param {Object} tech the video.js tech
  46913. * @param {Object} captionStream the caption stream to create
  46914. * @private
  46915. */
  46916. var createCaptionsTrackIfNotExists = function createCaptionsTrackIfNotExists(inbandTextTracks, tech, captionStream) {
  46917. if (!inbandTextTracks[captionStream]) {
  46918. tech.trigger({
  46919. type: 'usage',
  46920. name: 'vhs-608'
  46921. });
  46922. tech.trigger({
  46923. type: 'usage',
  46924. name: 'hls-608'
  46925. });
  46926. var instreamId = captionStream; // we need to translate SERVICEn for 708 to how mux.js currently labels them
  46927. if (/^cc708_/.test(captionStream)) {
  46928. instreamId = 'SERVICE' + captionStream.split('_')[1];
  46929. }
  46930. var track = tech.textTracks().getTrackById(instreamId);
  46931. if (track) {
  46932. // Resuse an existing track with a CC# id because this was
  46933. // very likely created by videojs-contrib-hls from information
  46934. // in the m3u8 for us to use
  46935. inbandTextTracks[captionStream] = track;
  46936. } else {
  46937. // This section gets called when we have caption services that aren't specified in the manifest.
  46938. // Manifest level caption services are handled in media-groups.js under CLOSED-CAPTIONS.
  46939. var captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  46940. var label = captionStream;
  46941. var language = captionStream;
  46942. var def = false;
  46943. var captionService = captionServices[instreamId];
  46944. if (captionService) {
  46945. label = captionService.label;
  46946. language = captionService.language;
  46947. def = captionService["default"];
  46948. } // Otherwise, create a track with the default `CC#` label and
  46949. // without a language
  46950. inbandTextTracks[captionStream] = tech.addRemoteTextTrack({
  46951. kind: 'captions',
  46952. id: instreamId,
  46953. // TODO: investigate why this doesn't seem to turn the caption on by default
  46954. "default": def,
  46955. label: label,
  46956. language: language
  46957. }, false).track;
  46958. }
  46959. }
  46960. };
  46961. /**
  46962. * Add caption text track data to a source handler given an array of captions
  46963. *
  46964. * @param {Object}
  46965. * @param {Object} inbandTextTracks the inband text tracks
  46966. * @param {number} timestampOffset the timestamp offset of the source buffer
  46967. * @param {Array} captionArray an array of caption data
  46968. * @private
  46969. */
  46970. var addCaptionData = function addCaptionData(_ref) {
  46971. var inbandTextTracks = _ref.inbandTextTracks,
  46972. captionArray = _ref.captionArray,
  46973. timestampOffset = _ref.timestampOffset;
  46974. if (!captionArray) {
  46975. return;
  46976. }
  46977. var Cue = window.WebKitDataCue || window.VTTCue;
  46978. captionArray.forEach(function (caption) {
  46979. var track = caption.stream;
  46980. inbandTextTracks[track].addCue(new Cue(caption.startTime + timestampOffset, caption.endTime + timestampOffset, caption.text));
  46981. });
  46982. };
  46983. /**
  46984. * Define properties on a cue for backwards compatability,
  46985. * but warn the user that the way that they are using it
  46986. * is depricated and will be removed at a later date.
  46987. *
  46988. * @param {Cue} cue the cue to add the properties on
  46989. * @private
  46990. */
  46991. var deprecateOldCue = function deprecateOldCue(cue) {
  46992. Object.defineProperties(cue.frame, {
  46993. id: {
  46994. get: function get() {
  46995. videojs.log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');
  46996. return cue.value.key;
  46997. }
  46998. },
  46999. value: {
  47000. get: function get() {
  47001. videojs.log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');
  47002. return cue.value.data;
  47003. }
  47004. },
  47005. privateData: {
  47006. get: function get() {
  47007. videojs.log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');
  47008. return cue.value.data;
  47009. }
  47010. }
  47011. });
  47012. };
  47013. /**
  47014. * Add metadata text track data to a source handler given an array of metadata
  47015. *
  47016. * @param {Object}
  47017. * @param {Object} inbandTextTracks the inband text tracks
  47018. * @param {Array} metadataArray an array of meta data
  47019. * @param {number} timestampOffset the timestamp offset of the source buffer
  47020. * @param {number} videoDuration the duration of the video
  47021. * @private
  47022. */
  47023. var addMetadata = function addMetadata(_ref2) {
  47024. var inbandTextTracks = _ref2.inbandTextTracks,
  47025. metadataArray = _ref2.metadataArray,
  47026. timestampOffset = _ref2.timestampOffset,
  47027. videoDuration = _ref2.videoDuration;
  47028. if (!metadataArray) {
  47029. return;
  47030. }
  47031. var Cue = window.WebKitDataCue || window.VTTCue;
  47032. var metadataTrack = inbandTextTracks.metadataTrack_;
  47033. if (!metadataTrack) {
  47034. return;
  47035. }
  47036. metadataArray.forEach(function (metadata) {
  47037. var time = metadata.cueTime + timestampOffset; // if time isn't a finite number between 0 and Infinity, like NaN,
  47038. // ignore this bit of metadata.
  47039. // This likely occurs when you have an non-timed ID3 tag like TIT2,
  47040. // which is the "Title/Songname/Content description" frame
  47041. if (typeof time !== 'number' || window.isNaN(time) || time < 0 || !(time < Infinity)) {
  47042. return;
  47043. }
  47044. metadata.frames.forEach(function (frame) {
  47045. var cue = new Cue(time, time, frame.value || frame.url || frame.data || '');
  47046. cue.frame = frame;
  47047. cue.value = frame;
  47048. deprecateOldCue(cue);
  47049. metadataTrack.addCue(cue);
  47050. });
  47051. });
  47052. if (!metadataTrack.cues || !metadataTrack.cues.length) {
  47053. return;
  47054. } // Updating the metadeta cues so that
  47055. // the endTime of each cue is the startTime of the next cue
  47056. // the endTime of last cue is the duration of the video
  47057. var cues = metadataTrack.cues;
  47058. var cuesArray = []; // Create a copy of the TextTrackCueList...
  47059. // ...disregarding cues with a falsey value
  47060. for (var i = 0; i < cues.length; i++) {
  47061. if (cues[i]) {
  47062. cuesArray.push(cues[i]);
  47063. }
  47064. } // Group cues by their startTime value
  47065. var cuesGroupedByStartTime = cuesArray.reduce(function (obj, cue) {
  47066. var timeSlot = obj[cue.startTime] || [];
  47067. timeSlot.push(cue);
  47068. obj[cue.startTime] = timeSlot;
  47069. return obj;
  47070. }, {}); // Sort startTimes by ascending order
  47071. var sortedStartTimes = Object.keys(cuesGroupedByStartTime).sort(function (a, b) {
  47072. return Number(a) - Number(b);
  47073. }); // Map each cue group's endTime to the next group's startTime
  47074. sortedStartTimes.forEach(function (startTime, idx) {
  47075. var cueGroup = cuesGroupedByStartTime[startTime];
  47076. var nextTime = Number(sortedStartTimes[idx + 1]) || videoDuration; // Map each cue's endTime the next group's startTime
  47077. cueGroup.forEach(function (cue) {
  47078. cue.endTime = nextTime;
  47079. });
  47080. });
  47081. };
  47082. /**
  47083. * Create metadata text track on video.js if it does not exist
  47084. *
  47085. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  47086. * @param {string} dispatchType the inband metadata track dispatch type
  47087. * @param {Object} tech the video.js tech
  47088. * @private
  47089. */
  47090. var createMetadataTrackIfNotExists = function createMetadataTrackIfNotExists(inbandTextTracks, dispatchType, tech) {
  47091. if (inbandTextTracks.metadataTrack_) {
  47092. return;
  47093. }
  47094. inbandTextTracks.metadataTrack_ = tech.addRemoteTextTrack({
  47095. kind: 'metadata',
  47096. label: 'Timed Metadata'
  47097. }, false).track;
  47098. inbandTextTracks.metadataTrack_.inBandMetadataTrackDispatchType = dispatchType;
  47099. };
  47100. /**
  47101. * Remove cues from a track on video.js.
  47102. *
  47103. * @param {Double} start start of where we should remove the cue
  47104. * @param {Double} end end of where the we should remove the cue
  47105. * @param {Object} track the text track to remove the cues from
  47106. * @private
  47107. */
  47108. var removeCuesFromTrack = function removeCuesFromTrack(start, end, track) {
  47109. var i;
  47110. var cue;
  47111. if (!track) {
  47112. return;
  47113. }
  47114. if (!track.cues) {
  47115. return;
  47116. }
  47117. i = track.cues.length;
  47118. while (i--) {
  47119. cue = track.cues[i]; // Remove any cue within the provided start and end time
  47120. if (cue.startTime >= start && cue.endTime <= end) {
  47121. track.removeCue(cue);
  47122. }
  47123. }
  47124. };
  47125. /**
  47126. * Remove duplicate cues from a track on video.js (a cue is considered a
  47127. * duplicate if it has the same time interval and text as another)
  47128. *
  47129. * @param {Object} track the text track to remove the duplicate cues from
  47130. * @private
  47131. */
  47132. var removeDuplicateCuesFromTrack = function removeDuplicateCuesFromTrack(track) {
  47133. var cues = track.cues;
  47134. if (!cues) {
  47135. return;
  47136. }
  47137. for (var i = 0; i < cues.length; i++) {
  47138. var duplicates = [];
  47139. var occurrences = 0;
  47140. for (var j = 0; j < cues.length; j++) {
  47141. if (cues[i].startTime === cues[j].startTime && cues[i].endTime === cues[j].endTime && cues[i].text === cues[j].text) {
  47142. occurrences++;
  47143. if (occurrences > 1) {
  47144. duplicates.push(cues[j]);
  47145. }
  47146. }
  47147. }
  47148. if (duplicates.length) {
  47149. duplicates.forEach(function (dupe) {
  47150. return track.removeCue(dupe);
  47151. });
  47152. }
  47153. }
  47154. };
  47155. /**
  47156. * Returns a list of gops in the buffer that have a pts value of 3 seconds or more in
  47157. * front of current time.
  47158. *
  47159. * @param {Array} buffer
  47160. * The current buffer of gop information
  47161. * @param {number} currentTime
  47162. * The current time
  47163. * @param {Double} mapping
  47164. * Offset to map display time to stream presentation time
  47165. * @return {Array}
  47166. * List of gops considered safe to append over
  47167. */
  47168. var gopsSafeToAlignWith = function gopsSafeToAlignWith(buffer, currentTime, mapping) {
  47169. if (typeof currentTime === 'undefined' || currentTime === null || !buffer.length) {
  47170. return [];
  47171. } // pts value for current time + 3 seconds to give a bit more wiggle room
  47172. var currentTimePts = Math.ceil((currentTime - mapping + 3) * clock_1);
  47173. var i;
  47174. for (i = 0; i < buffer.length; i++) {
  47175. if (buffer[i].pts > currentTimePts) {
  47176. break;
  47177. }
  47178. }
  47179. return buffer.slice(i);
  47180. };
  47181. /**
  47182. * Appends gop information (timing and byteLength) received by the transmuxer for the
  47183. * gops appended in the last call to appendBuffer
  47184. *
  47185. * @param {Array} buffer
  47186. * The current buffer of gop information
  47187. * @param {Array} gops
  47188. * List of new gop information
  47189. * @param {boolean} replace
  47190. * If true, replace the buffer with the new gop information. If false, append the
  47191. * new gop information to the buffer in the right location of time.
  47192. * @return {Array}
  47193. * Updated list of gop information
  47194. */
  47195. var updateGopBuffer = function updateGopBuffer(buffer, gops, replace) {
  47196. if (!gops.length) {
  47197. return buffer;
  47198. }
  47199. if (replace) {
  47200. // If we are in safe append mode, then completely overwrite the gop buffer
  47201. // with the most recent appeneded data. This will make sure that when appending
  47202. // future segments, we only try to align with gops that are both ahead of current
  47203. // time and in the last segment appended.
  47204. return gops.slice();
  47205. }
  47206. var start = gops[0].pts;
  47207. var i = 0;
  47208. for (i; i < buffer.length; i++) {
  47209. if (buffer[i].pts >= start) {
  47210. break;
  47211. }
  47212. }
  47213. return buffer.slice(0, i).concat(gops);
  47214. };
  47215. /**
  47216. * Removes gop information in buffer that overlaps with provided start and end
  47217. *
  47218. * @param {Array} buffer
  47219. * The current buffer of gop information
  47220. * @param {Double} start
  47221. * position to start the remove at
  47222. * @param {Double} end
  47223. * position to end the remove at
  47224. * @param {Double} mapping
  47225. * Offset to map display time to stream presentation time
  47226. */
  47227. var removeGopBuffer = function removeGopBuffer(buffer, start, end, mapping) {
  47228. var startPts = Math.ceil((start - mapping) * clock_1);
  47229. var endPts = Math.ceil((end - mapping) * clock_1);
  47230. var updatedBuffer = buffer.slice();
  47231. var i = buffer.length;
  47232. while (i--) {
  47233. if (buffer[i].pts <= endPts) {
  47234. break;
  47235. }
  47236. }
  47237. if (i === -1) {
  47238. // no removal because end of remove range is before start of buffer
  47239. return updatedBuffer;
  47240. }
  47241. var j = i + 1;
  47242. while (j--) {
  47243. if (buffer[j].pts <= startPts) {
  47244. break;
  47245. }
  47246. } // clamp remove range start to 0 index
  47247. j = Math.max(j, 0);
  47248. updatedBuffer.splice(j, i - j + 1);
  47249. return updatedBuffer;
  47250. };
  47251. var shallowEqual = function shallowEqual(a, b) {
  47252. // if both are undefined
  47253. // or one or the other is undefined
  47254. // they are not equal
  47255. if (!a && !b || !a && b || a && !b) {
  47256. return false;
  47257. } // they are the same object and thus, equal
  47258. if (a === b) {
  47259. return true;
  47260. } // sort keys so we can make sure they have
  47261. // all the same keys later.
  47262. var akeys = Object.keys(a).sort();
  47263. var bkeys = Object.keys(b).sort(); // different number of keys, not equal
  47264. if (akeys.length !== bkeys.length) {
  47265. return false;
  47266. }
  47267. for (var i = 0; i < akeys.length; i++) {
  47268. var key = akeys[i]; // different sorted keys, not equal
  47269. if (key !== bkeys[i]) {
  47270. return false;
  47271. } // different values, not equal
  47272. if (a[key] !== b[key]) {
  47273. return false;
  47274. }
  47275. }
  47276. return true;
  47277. }; // https://www.w3.org/TR/WebIDL-1/#quotaexceedederror
  47278. var QUOTA_EXCEEDED_ERR = 22;
  47279. /**
  47280. * The segment loader has no recourse except to fetch a segment in the
  47281. * current playlist and use the internal timestamps in that segment to
  47282. * generate a syncPoint. This function returns a good candidate index
  47283. * for that process.
  47284. *
  47285. * @param {Array} segments - the segments array from a playlist.
  47286. * @return {number} An index of a segment from the playlist to load
  47287. */
  47288. var getSyncSegmentCandidate = function getSyncSegmentCandidate(currentTimeline, segments, targetTime) {
  47289. segments = segments || [];
  47290. var timelineSegments = [];
  47291. var time = 0;
  47292. for (var i = 0; i < segments.length; i++) {
  47293. var segment = segments[i];
  47294. if (currentTimeline === segment.timeline) {
  47295. timelineSegments.push(i);
  47296. time += segment.duration;
  47297. if (time > targetTime) {
  47298. return i;
  47299. }
  47300. }
  47301. }
  47302. if (timelineSegments.length === 0) {
  47303. return 0;
  47304. } // default to the last timeline segment
  47305. return timelineSegments[timelineSegments.length - 1];
  47306. }; // In the event of a quota exceeded error, keep at least one second of back buffer. This
  47307. // number was arbitrarily chosen and may be updated in the future, but seemed reasonable
  47308. // as a start to prevent any potential issues with removing content too close to the
  47309. // playhead.
  47310. var MIN_BACK_BUFFER = 1; // in ms
  47311. var CHECK_BUFFER_DELAY = 500;
  47312. var finite = function finite(num) {
  47313. return typeof num === 'number' && isFinite(num);
  47314. }; // With most content hovering around 30fps, if a segment has a duration less than a half
  47315. // frame at 30fps or one frame at 60fps, the bandwidth and throughput calculations will
  47316. // not accurately reflect the rest of the content.
  47317. var MIN_SEGMENT_DURATION_TO_SAVE_STATS = 1 / 60;
  47318. var illegalMediaSwitch = function illegalMediaSwitch(loaderType, startingMedia, trackInfo) {
  47319. // Although these checks should most likely cover non 'main' types, for now it narrows
  47320. // the scope of our checks.
  47321. if (loaderType !== 'main' || !startingMedia || !trackInfo) {
  47322. return null;
  47323. }
  47324. if (!trackInfo.hasAudio && !trackInfo.hasVideo) {
  47325. return 'Neither audio nor video found in segment.';
  47326. }
  47327. if (startingMedia.hasVideo && !trackInfo.hasVideo) {
  47328. return 'Only audio found in segment when we expected video.' + ' We can\'t switch to audio only from a stream that had video.' + ' To get rid of this message, please add codec information to the manifest.';
  47329. }
  47330. if (!startingMedia.hasVideo && trackInfo.hasVideo) {
  47331. return 'Video found in segment when we expected only audio.' + ' We can\'t switch to a stream with video from an audio only stream.' + ' To get rid of this message, please add codec information to the manifest.';
  47332. }
  47333. return null;
  47334. };
  47335. /**
  47336. * Calculates a time value that is safe to remove from the back buffer without interrupting
  47337. * playback.
  47338. *
  47339. * @param {TimeRange} seekable
  47340. * The current seekable range
  47341. * @param {number} currentTime
  47342. * The current time of the player
  47343. * @param {number} targetDuration
  47344. * The target duration of the current playlist
  47345. * @return {number}
  47346. * Time that is safe to remove from the back buffer without interrupting playback
  47347. */
  47348. var safeBackBufferTrimTime = function safeBackBufferTrimTime(seekable, currentTime, targetDuration) {
  47349. // 30 seconds before the playhead provides a safe default for trimming.
  47350. //
  47351. // Choosing a reasonable default is particularly important for high bitrate content and
  47352. // VOD videos/live streams with large windows, as the buffer may end up overfilled and
  47353. // throw an APPEND_BUFFER_ERR.
  47354. var trimTime = currentTime - Config.BACK_BUFFER_LENGTH;
  47355. if (seekable.length) {
  47356. // Some live playlists may have a shorter window of content than the full allowed back
  47357. // buffer. For these playlists, don't save content that's no longer within the window.
  47358. trimTime = Math.max(trimTime, seekable.start(0));
  47359. } // Don't remove within target duration of the current time to avoid the possibility of
  47360. // removing the GOP currently being played, as removing it can cause playback stalls.
  47361. var maxTrimTime = currentTime - targetDuration;
  47362. return Math.min(maxTrimTime, trimTime);
  47363. };
  47364. var segmentInfoString = function segmentInfoString(segmentInfo) {
  47365. var startOfSegment = segmentInfo.startOfSegment,
  47366. duration = segmentInfo.duration,
  47367. segment = segmentInfo.segment,
  47368. part = segmentInfo.part,
  47369. _segmentInfo$playlist = segmentInfo.playlist,
  47370. seq = _segmentInfo$playlist.mediaSequence,
  47371. id = _segmentInfo$playlist.id,
  47372. _segmentInfo$playlist2 = _segmentInfo$playlist.segments,
  47373. segments = _segmentInfo$playlist2 === void 0 ? [] : _segmentInfo$playlist2,
  47374. index = segmentInfo.mediaIndex,
  47375. partIndex = segmentInfo.partIndex,
  47376. timeline = segmentInfo.timeline;
  47377. var segmentLen = segments.length - 1;
  47378. var selection = 'mediaIndex/partIndex increment';
  47379. if (segmentInfo.getMediaInfoForTime) {
  47380. selection = "getMediaInfoForTime (" + segmentInfo.getMediaInfoForTime + ")";
  47381. } else if (segmentInfo.isSyncRequest) {
  47382. selection = 'getSyncSegmentCandidate (isSyncRequest)';
  47383. }
  47384. if (segmentInfo.independent) {
  47385. selection += " with independent " + segmentInfo.independent;
  47386. }
  47387. var hasPartIndex = typeof partIndex === 'number';
  47388. var name = segmentInfo.segment.uri ? 'segment' : 'pre-segment';
  47389. var zeroBasedPartCount = hasPartIndex ? getKnownPartCount({
  47390. preloadSegment: segment
  47391. }) - 1 : 0;
  47392. return name + " [" + (seq + index) + "/" + (seq + segmentLen) + "]" + (hasPartIndex ? " part [" + partIndex + "/" + zeroBasedPartCount + "]" : '') + (" segment start/end [" + segment.start + " => " + segment.end + "]") + (hasPartIndex ? " part start/end [" + part.start + " => " + part.end + "]" : '') + (" startOfSegment [" + startOfSegment + "]") + (" duration [" + duration + "]") + (" timeline [" + timeline + "]") + (" selected by [" + selection + "]") + (" playlist [" + id + "]");
  47393. };
  47394. var timingInfoPropertyForMedia = function timingInfoPropertyForMedia(mediaType) {
  47395. return mediaType + "TimingInfo";
  47396. };
  47397. /**
  47398. * Returns the timestamp offset to use for the segment.
  47399. *
  47400. * @param {number} segmentTimeline
  47401. * The timeline of the segment
  47402. * @param {number} currentTimeline
  47403. * The timeline currently being followed by the loader
  47404. * @param {number} startOfSegment
  47405. * The estimated segment start
  47406. * @param {TimeRange[]} buffered
  47407. * The loader's buffer
  47408. * @param {boolean} overrideCheck
  47409. * If true, no checks are made to see if the timestamp offset value should be set,
  47410. * but sets it directly to a value.
  47411. *
  47412. * @return {number|null}
  47413. * Either a number representing a new timestamp offset, or null if the segment is
  47414. * part of the same timeline
  47415. */
  47416. var timestampOffsetForSegment = function timestampOffsetForSegment(_ref) {
  47417. var segmentTimeline = _ref.segmentTimeline,
  47418. currentTimeline = _ref.currentTimeline,
  47419. startOfSegment = _ref.startOfSegment,
  47420. buffered = _ref.buffered,
  47421. overrideCheck = _ref.overrideCheck; // Check to see if we are crossing a discontinuity to see if we need to set the
  47422. // timestamp offset on the transmuxer and source buffer.
  47423. //
  47424. // Previously, we changed the timestampOffset if the start of this segment was less than
  47425. // the currently set timestampOffset, but this isn't desirable as it can produce bad
  47426. // behavior, especially around long running live streams.
  47427. if (!overrideCheck && segmentTimeline === currentTimeline) {
  47428. return null;
  47429. } // When changing renditions, it's possible to request a segment on an older timeline. For
  47430. // instance, given two renditions with the following:
  47431. //
  47432. // #EXTINF:10
  47433. // segment1
  47434. // #EXT-X-DISCONTINUITY
  47435. // #EXTINF:10
  47436. // segment2
  47437. // #EXTINF:10
  47438. // segment3
  47439. //
  47440. // And the current player state:
  47441. //
  47442. // current time: 8
  47443. // buffer: 0 => 20
  47444. //
  47445. // The next segment on the current rendition would be segment3, filling the buffer from
  47446. // 20s onwards. However, if a rendition switch happens after segment2 was requested,
  47447. // then the next segment to be requested will be segment1 from the new rendition in
  47448. // order to fill time 8 and onwards. Using the buffered end would result in repeated
  47449. // content (since it would position segment1 of the new rendition starting at 20s). This
  47450. // case can be identified when the new segment's timeline is a prior value. Instead of
  47451. // using the buffered end, the startOfSegment can be used, which, hopefully, will be
  47452. // more accurate to the actual start time of the segment.
  47453. if (segmentTimeline < currentTimeline) {
  47454. return startOfSegment;
  47455. } // segmentInfo.startOfSegment used to be used as the timestamp offset, however, that
  47456. // value uses the end of the last segment if it is available. While this value
  47457. // should often be correct, it's better to rely on the buffered end, as the new
  47458. // content post discontinuity should line up with the buffered end as if it were
  47459. // time 0 for the new content.
  47460. return buffered.length ? buffered.end(buffered.length - 1) : startOfSegment;
  47461. };
  47462. /**
  47463. * Returns whether or not the loader should wait for a timeline change from the timeline
  47464. * change controller before processing the segment.
  47465. *
  47466. * Primary timing in VHS goes by video. This is different from most media players, as
  47467. * audio is more often used as the primary timing source. For the foreseeable future, VHS
  47468. * will continue to use video as the primary timing source, due to the current logic and
  47469. * expectations built around it.
  47470. * Since the timing follows video, in order to maintain sync, the video loader is
  47471. * responsible for setting both audio and video source buffer timestamp offsets.
  47472. *
  47473. * Setting different values for audio and video source buffers could lead to
  47474. * desyncing. The following examples demonstrate some of the situations where this
  47475. * distinction is important. Note that all of these cases involve demuxed content. When
  47476. * content is muxed, the audio and video are packaged together, therefore syncing
  47477. * separate media playlists is not an issue.
  47478. *
  47479. * CASE 1: Audio prepares to load a new timeline before video:
  47480. *
  47481. * Timeline: 0 1
  47482. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  47483. * Audio Loader: ^
  47484. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  47485. * Video Loader ^
  47486. *
  47487. * In the above example, the audio loader is preparing to load the 6th segment, the first
  47488. * after a discontinuity, while the video loader is still loading the 5th segment, before
  47489. * the discontinuity.
  47490. *
  47491. * If the audio loader goes ahead and loads and appends the 6th segment before the video
  47492. * loader crosses the discontinuity, then when appended, the 6th audio segment will use
  47493. * the timestamp offset from timeline 0. This will likely lead to desyncing. In addition,
  47494. * the audio loader must provide the audioAppendStart value to trim the content in the
  47495. * transmuxer, and that value relies on the audio timestamp offset. Since the audio
  47496. * timestamp offset is set by the video (main) loader, the audio loader shouldn't load the
  47497. * segment until that value is provided.
  47498. *
  47499. * CASE 2: Video prepares to load a new timeline before audio:
  47500. *
  47501. * Timeline: 0 1
  47502. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  47503. * Audio Loader: ^
  47504. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  47505. * Video Loader ^
  47506. *
  47507. * In the above example, the video loader is preparing to load the 6th segment, the first
  47508. * after a discontinuity, while the audio loader is still loading the 5th segment, before
  47509. * the discontinuity.
  47510. *
  47511. * If the video loader goes ahead and loads and appends the 6th segment, then once the
  47512. * segment is loaded and processed, both the video and audio timestamp offsets will be
  47513. * set, since video is used as the primary timing source. This is to ensure content lines
  47514. * up appropriately, as any modifications to the video timing are reflected by audio when
  47515. * the video loader sets the audio and video timestamp offsets to the same value. However,
  47516. * setting the timestamp offset for audio before audio has had a chance to change
  47517. * timelines will likely lead to desyncing, as the audio loader will append segment 5 with
  47518. * a timestamp intended to apply to segments from timeline 1 rather than timeline 0.
  47519. *
  47520. * CASE 3: When seeking, audio prepares to load a new timeline before video
  47521. *
  47522. * Timeline: 0 1
  47523. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  47524. * Audio Loader: ^
  47525. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  47526. * Video Loader ^
  47527. *
  47528. * In the above example, both audio and video loaders are loading segments from timeline
  47529. * 0, but imagine that the seek originated from timeline 1.
  47530. *
  47531. * When seeking to a new timeline, the timestamp offset will be set based on the expected
  47532. * segment start of the loaded video segment. In order to maintain sync, the audio loader
  47533. * must wait for the video loader to load its segment and update both the audio and video
  47534. * timestamp offsets before it may load and append its own segment. This is the case
  47535. * whether the seek results in a mismatched segment request (e.g., the audio loader
  47536. * chooses to load segment 3 and the video loader chooses to load segment 4) or the
  47537. * loaders choose to load the same segment index from each playlist, as the segments may
  47538. * not be aligned perfectly, even for matching segment indexes.
  47539. *
  47540. * @param {Object} timelinechangeController
  47541. * @param {number} currentTimeline
  47542. * The timeline currently being followed by the loader
  47543. * @param {number} segmentTimeline
  47544. * The timeline of the segment being loaded
  47545. * @param {('main'|'audio')} loaderType
  47546. * The loader type
  47547. * @param {boolean} audioDisabled
  47548. * Whether the audio is disabled for the loader. This should only be true when the
  47549. * loader may have muxed audio in its segment, but should not append it, e.g., for
  47550. * the main loader when an alternate audio playlist is active.
  47551. *
  47552. * @return {boolean}
  47553. * Whether the loader should wait for a timeline change from the timeline change
  47554. * controller before processing the segment
  47555. */
  47556. var shouldWaitForTimelineChange = function shouldWaitForTimelineChange(_ref2) {
  47557. var timelineChangeController = _ref2.timelineChangeController,
  47558. currentTimeline = _ref2.currentTimeline,
  47559. segmentTimeline = _ref2.segmentTimeline,
  47560. loaderType = _ref2.loaderType,
  47561. audioDisabled = _ref2.audioDisabled;
  47562. if (currentTimeline === segmentTimeline) {
  47563. return false;
  47564. }
  47565. if (loaderType === 'audio') {
  47566. var lastMainTimelineChange = timelineChangeController.lastTimelineChange({
  47567. type: 'main'
  47568. }); // Audio loader should wait if:
  47569. //
  47570. // * main hasn't had a timeline change yet (thus has not loaded its first segment)
  47571. // * main hasn't yet changed to the timeline audio is looking to load
  47572. return !lastMainTimelineChange || lastMainTimelineChange.to !== segmentTimeline;
  47573. } // The main loader only needs to wait for timeline changes if there's demuxed audio.
  47574. // Otherwise, there's nothing to wait for, since audio would be muxed into the main
  47575. // loader's segments (or the content is audio/video only and handled by the main
  47576. // loader).
  47577. if (loaderType === 'main' && audioDisabled) {
  47578. var pendingAudioTimelineChange = timelineChangeController.pendingTimelineChange({
  47579. type: 'audio'
  47580. }); // Main loader should wait for the audio loader if audio is not pending a timeline
  47581. // change to the current timeline.
  47582. //
  47583. // Since the main loader is responsible for setting the timestamp offset for both
  47584. // audio and video, the main loader must wait for audio to be about to change to its
  47585. // timeline before setting the offset, otherwise, if audio is behind in loading,
  47586. // segments from the previous timeline would be adjusted by the new timestamp offset.
  47587. //
  47588. // This requirement means that video will not cross a timeline until the audio is
  47589. // about to cross to it, so that way audio and video will always cross the timeline
  47590. // together.
  47591. //
  47592. // In addition to normal timeline changes, these rules also apply to the start of a
  47593. // stream (going from a non-existent timeline, -1, to timeline 0). It's important
  47594. // that these rules apply to the first timeline change because if they did not, it's
  47595. // possible that the main loader will cross two timelines before the audio loader has
  47596. // crossed one. Logic may be implemented to handle the startup as a special case, but
  47597. // it's easier to simply treat all timeline changes the same.
  47598. if (pendingAudioTimelineChange && pendingAudioTimelineChange.to === segmentTimeline) {
  47599. return false;
  47600. }
  47601. return true;
  47602. }
  47603. return false;
  47604. };
  47605. var mediaDuration = function mediaDuration(timingInfos) {
  47606. var maxDuration = 0;
  47607. ['video', 'audio'].forEach(function (type) {
  47608. var typeTimingInfo = timingInfos[type + "TimingInfo"];
  47609. if (!typeTimingInfo) {
  47610. return;
  47611. }
  47612. var start = typeTimingInfo.start,
  47613. end = typeTimingInfo.end;
  47614. var duration;
  47615. if (typeof start === 'bigint' || typeof end === 'bigint') {
  47616. duration = window.BigInt(end) - window.BigInt(start);
  47617. } else if (typeof start === 'number' && typeof end === 'number') {
  47618. duration = end - start;
  47619. }
  47620. if (typeof duration !== 'undefined' && duration > maxDuration) {
  47621. maxDuration = duration;
  47622. }
  47623. }); // convert back to a number if it is lower than MAX_SAFE_INTEGER
  47624. // as we only need BigInt when we are above that.
  47625. if (typeof maxDuration === 'bigint' && maxDuration < Number.MAX_SAFE_INTEGER) {
  47626. maxDuration = Number(maxDuration);
  47627. }
  47628. return maxDuration;
  47629. };
  47630. var segmentTooLong = function segmentTooLong(_ref3) {
  47631. var segmentDuration = _ref3.segmentDuration,
  47632. maxDuration = _ref3.maxDuration; // 0 duration segments are most likely due to metadata only segments or a lack of
  47633. // information.
  47634. if (!segmentDuration) {
  47635. return false;
  47636. } // For HLS:
  47637. //
  47638. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1
  47639. // The EXTINF duration of each Media Segment in the Playlist
  47640. // file, when rounded to the nearest integer, MUST be less than or equal
  47641. // to the target duration; longer segments can trigger playback stalls
  47642. // or other errors.
  47643. //
  47644. // For DASH, the mpd-parser uses the largest reported segment duration as the target
  47645. // duration. Although that reported duration is occasionally approximate (i.e., not
  47646. // exact), a strict check may report that a segment is too long more often in DASH.
  47647. return Math.round(segmentDuration) > maxDuration + TIME_FUDGE_FACTOR;
  47648. };
  47649. var getTroublesomeSegmentDurationMessage = function getTroublesomeSegmentDurationMessage(segmentInfo, sourceType) {
  47650. // Right now we aren't following DASH's timing model exactly, so only perform
  47651. // this check for HLS content.
  47652. if (sourceType !== 'hls') {
  47653. return null;
  47654. }
  47655. var segmentDuration = mediaDuration({
  47656. audioTimingInfo: segmentInfo.audioTimingInfo,
  47657. videoTimingInfo: segmentInfo.videoTimingInfo
  47658. }); // Don't report if we lack information.
  47659. //
  47660. // If the segment has a duration of 0 it is either a lack of information or a
  47661. // metadata only segment and shouldn't be reported here.
  47662. if (!segmentDuration) {
  47663. return null;
  47664. }
  47665. var targetDuration = segmentInfo.playlist.targetDuration;
  47666. var isSegmentWayTooLong = segmentTooLong({
  47667. segmentDuration: segmentDuration,
  47668. maxDuration: targetDuration * 2
  47669. });
  47670. var isSegmentSlightlyTooLong = segmentTooLong({
  47671. segmentDuration: segmentDuration,
  47672. maxDuration: targetDuration
  47673. });
  47674. var segmentTooLongMessage = "Segment with index " + segmentInfo.mediaIndex + " " + ("from playlist " + segmentInfo.playlist.id + " ") + ("has a duration of " + segmentDuration + " ") + ("when the reported duration is " + segmentInfo.duration + " ") + ("and the target duration is " + targetDuration + ". ") + 'For HLS content, a duration in excess of the target duration may result in ' + 'playback issues. See the HLS specification section on EXT-X-TARGETDURATION for ' + 'more details: ' + 'https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1';
  47675. if (isSegmentWayTooLong || isSegmentSlightlyTooLong) {
  47676. return {
  47677. severity: isSegmentWayTooLong ? 'warn' : 'info',
  47678. message: segmentTooLongMessage
  47679. };
  47680. }
  47681. return null;
  47682. };
  47683. /**
  47684. * An object that manages segment loading and appending.
  47685. *
  47686. * @class SegmentLoader
  47687. * @param {Object} options required and optional options
  47688. * @extends videojs.EventTarget
  47689. */
  47690. var SegmentLoader = /*#__PURE__*/function (_videojs$EventTarget) {
  47691. inheritsLoose(SegmentLoader, _videojs$EventTarget);
  47692. function SegmentLoader(settings, options) {
  47693. var _this;
  47694. _this = _videojs$EventTarget.call(this) || this; // check pre-conditions
  47695. if (!settings) {
  47696. throw new TypeError('Initialization settings are required');
  47697. }
  47698. if (typeof settings.currentTime !== 'function') {
  47699. throw new TypeError('No currentTime getter specified');
  47700. }
  47701. if (!settings.mediaSource) {
  47702. throw new TypeError('No MediaSource specified');
  47703. } // public properties
  47704. _this.bandwidth = settings.bandwidth;
  47705. _this.throughput = {
  47706. rate: 0,
  47707. count: 0
  47708. };
  47709. _this.roundTrip = NaN;
  47710. _this.resetStats_();
  47711. _this.mediaIndex = null;
  47712. _this.partIndex = null; // private settings
  47713. _this.hasPlayed_ = settings.hasPlayed;
  47714. _this.currentTime_ = settings.currentTime;
  47715. _this.seekable_ = settings.seekable;
  47716. _this.seeking_ = settings.seeking;
  47717. _this.duration_ = settings.duration;
  47718. _this.mediaSource_ = settings.mediaSource;
  47719. _this.vhs_ = settings.vhs;
  47720. _this.loaderType_ = settings.loaderType;
  47721. _this.currentMediaInfo_ = void 0;
  47722. _this.startingMediaInfo_ = void 0;
  47723. _this.segmentMetadataTrack_ = settings.segmentMetadataTrack;
  47724. _this.goalBufferLength_ = settings.goalBufferLength;
  47725. _this.sourceType_ = settings.sourceType;
  47726. _this.sourceUpdater_ = settings.sourceUpdater;
  47727. _this.inbandTextTracks_ = settings.inbandTextTracks;
  47728. _this.state_ = 'INIT';
  47729. _this.timelineChangeController_ = settings.timelineChangeController;
  47730. _this.shouldSaveSegmentTimingInfo_ = true;
  47731. _this.parse708captions_ = settings.parse708captions;
  47732. _this.useDtsForTimestampOffset_ = settings.useDtsForTimestampOffset;
  47733. _this.captionServices_ = settings.captionServices;
  47734. _this.experimentalExactManifestTimings = settings.experimentalExactManifestTimings; // private instance variables
  47735. _this.checkBufferTimeout_ = null;
  47736. _this.error_ = void 0;
  47737. _this.currentTimeline_ = -1;
  47738. _this.pendingSegment_ = null;
  47739. _this.xhrOptions_ = null;
  47740. _this.pendingSegments_ = [];
  47741. _this.audioDisabled_ = false;
  47742. _this.isPendingTimestampOffset_ = false; // TODO possibly move gopBuffer and timeMapping info to a separate controller
  47743. _this.gopBuffer_ = [];
  47744. _this.timeMapping_ = 0;
  47745. _this.safeAppend_ = videojs.browser.IE_VERSION >= 11;
  47746. _this.appendInitSegment_ = {
  47747. audio: true,
  47748. video: true
  47749. };
  47750. _this.playlistOfLastInitSegment_ = {
  47751. audio: null,
  47752. video: null
  47753. };
  47754. _this.callQueue_ = []; // If the segment loader prepares to load a segment, but does not have enough
  47755. // information yet to start the loading process (e.g., if the audio loader wants to
  47756. // load a segment from the next timeline but the main loader hasn't yet crossed that
  47757. // timeline), then the load call will be added to the queue until it is ready to be
  47758. // processed.
  47759. _this.loadQueue_ = [];
  47760. _this.metadataQueue_ = {
  47761. id3: [],
  47762. caption: []
  47763. };
  47764. _this.waitingOnRemove_ = false;
  47765. _this.quotaExceededErrorRetryTimeout_ = null; // Fragmented mp4 playback
  47766. _this.activeInitSegmentId_ = null;
  47767. _this.initSegments_ = {}; // HLSe playback
  47768. _this.cacheEncryptionKeys_ = settings.cacheEncryptionKeys;
  47769. _this.keyCache_ = {};
  47770. _this.decrypter_ = settings.decrypter; // Manages the tracking and generation of sync-points, mappings
  47771. // between a time in the display time and a segment index within
  47772. // a playlist
  47773. _this.syncController_ = settings.syncController;
  47774. _this.syncPoint_ = {
  47775. segmentIndex: 0,
  47776. time: 0
  47777. };
  47778. _this.transmuxer_ = _this.createTransmuxer_();
  47779. _this.triggerSyncInfoUpdate_ = function () {
  47780. return _this.trigger('syncinfoupdate');
  47781. };
  47782. _this.syncController_.on('syncinfoupdate', _this.triggerSyncInfoUpdate_);
  47783. _this.mediaSource_.addEventListener('sourceopen', function () {
  47784. if (!_this.isEndOfStream_()) {
  47785. _this.ended_ = false;
  47786. }
  47787. }); // ...for determining the fetch location
  47788. _this.fetchAtBuffer_ = false;
  47789. _this.logger_ = logger("SegmentLoader[" + _this.loaderType_ + "]");
  47790. Object.defineProperty(assertThisInitialized(_this), 'state', {
  47791. get: function get() {
  47792. return this.state_;
  47793. },
  47794. set: function set(newState) {
  47795. if (newState !== this.state_) {
  47796. this.logger_(this.state_ + " -> " + newState);
  47797. this.state_ = newState;
  47798. this.trigger('statechange');
  47799. }
  47800. }
  47801. });
  47802. _this.sourceUpdater_.on('ready', function () {
  47803. if (_this.hasEnoughInfoToAppend_()) {
  47804. _this.processCallQueue_();
  47805. }
  47806. }); // Only the main loader needs to listen for pending timeline changes, as the main
  47807. // loader should wait for audio to be ready to change its timeline so that both main
  47808. // and audio timelines change together. For more details, see the
  47809. // shouldWaitForTimelineChange function.
  47810. if (_this.loaderType_ === 'main') {
  47811. _this.timelineChangeController_.on('pendingtimelinechange', function () {
  47812. if (_this.hasEnoughInfoToAppend_()) {
  47813. _this.processCallQueue_();
  47814. }
  47815. });
  47816. } // The main loader only listens on pending timeline changes, but the audio loader,
  47817. // since its loads follow main, needs to listen on timeline changes. For more details,
  47818. // see the shouldWaitForTimelineChange function.
  47819. if (_this.loaderType_ === 'audio') {
  47820. _this.timelineChangeController_.on('timelinechange', function () {
  47821. if (_this.hasEnoughInfoToLoad_()) {
  47822. _this.processLoadQueue_();
  47823. }
  47824. if (_this.hasEnoughInfoToAppend_()) {
  47825. _this.processCallQueue_();
  47826. }
  47827. });
  47828. }
  47829. return _this;
  47830. }
  47831. var _proto = SegmentLoader.prototype;
  47832. _proto.createTransmuxer_ = function createTransmuxer_() {
  47833. return segmentTransmuxer.createTransmuxer({
  47834. remux: false,
  47835. alignGopsAtEnd: this.safeAppend_,
  47836. keepOriginalTimestamps: true,
  47837. parse708captions: this.parse708captions_,
  47838. captionServices: this.captionServices_
  47839. });
  47840. }
  47841. /**
  47842. * reset all of our media stats
  47843. *
  47844. * @private
  47845. */
  47846. ;
  47847. _proto.resetStats_ = function resetStats_() {
  47848. this.mediaBytesTransferred = 0;
  47849. this.mediaRequests = 0;
  47850. this.mediaRequestsAborted = 0;
  47851. this.mediaRequestsTimedout = 0;
  47852. this.mediaRequestsErrored = 0;
  47853. this.mediaTransferDuration = 0;
  47854. this.mediaSecondsLoaded = 0;
  47855. this.mediaAppends = 0;
  47856. }
  47857. /**
  47858. * dispose of the SegmentLoader and reset to the default state
  47859. */
  47860. ;
  47861. _proto.dispose = function dispose() {
  47862. this.trigger('dispose');
  47863. this.state = 'DISPOSED';
  47864. this.pause();
  47865. this.abort_();
  47866. if (this.transmuxer_) {
  47867. this.transmuxer_.terminate();
  47868. }
  47869. this.resetStats_();
  47870. if (this.checkBufferTimeout_) {
  47871. window.clearTimeout(this.checkBufferTimeout_);
  47872. }
  47873. if (this.syncController_ && this.triggerSyncInfoUpdate_) {
  47874. this.syncController_.off('syncinfoupdate', this.triggerSyncInfoUpdate_);
  47875. }
  47876. this.off();
  47877. };
  47878. _proto.setAudio = function setAudio(enable) {
  47879. this.audioDisabled_ = !enable;
  47880. if (enable) {
  47881. this.appendInitSegment_.audio = true;
  47882. } else {
  47883. // remove current track audio if it gets disabled
  47884. this.sourceUpdater_.removeAudio(0, this.duration_());
  47885. }
  47886. }
  47887. /**
  47888. * abort anything that is currently doing on with the SegmentLoader
  47889. * and reset to a default state
  47890. */
  47891. ;
  47892. _proto.abort = function abort() {
  47893. if (this.state !== 'WAITING') {
  47894. if (this.pendingSegment_) {
  47895. this.pendingSegment_ = null;
  47896. }
  47897. return;
  47898. }
  47899. this.abort_(); // We aborted the requests we were waiting on, so reset the loader's state to READY
  47900. // since we are no longer "waiting" on any requests. XHR callback is not always run
  47901. // when the request is aborted. This will prevent the loader from being stuck in the
  47902. // WAITING state indefinitely.
  47903. this.state = 'READY'; // don't wait for buffer check timeouts to begin fetching the
  47904. // next segment
  47905. if (!this.paused()) {
  47906. this.monitorBuffer_();
  47907. }
  47908. }
  47909. /**
  47910. * abort all pending xhr requests and null any pending segements
  47911. *
  47912. * @private
  47913. */
  47914. ;
  47915. _proto.abort_ = function abort_() {
  47916. if (this.pendingSegment_ && this.pendingSegment_.abortRequests) {
  47917. this.pendingSegment_.abortRequests();
  47918. } // clear out the segment being processed
  47919. this.pendingSegment_ = null;
  47920. this.callQueue_ = [];
  47921. this.loadQueue_ = [];
  47922. this.metadataQueue_.id3 = [];
  47923. this.metadataQueue_.caption = [];
  47924. this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);
  47925. this.waitingOnRemove_ = false;
  47926. window.clearTimeout(this.quotaExceededErrorRetryTimeout_);
  47927. this.quotaExceededErrorRetryTimeout_ = null;
  47928. };
  47929. _proto.checkForAbort_ = function checkForAbort_(requestId) {
  47930. // If the state is APPENDING, then aborts will not modify the state, meaning the first
  47931. // callback that happens should reset the state to READY so that loading can continue.
  47932. if (this.state === 'APPENDING' && !this.pendingSegment_) {
  47933. this.state = 'READY';
  47934. return true;
  47935. }
  47936. if (!this.pendingSegment_ || this.pendingSegment_.requestId !== requestId) {
  47937. return true;
  47938. }
  47939. return false;
  47940. }
  47941. /**
  47942. * set an error on the segment loader and null out any pending segements
  47943. *
  47944. * @param {Error} error the error to set on the SegmentLoader
  47945. * @return {Error} the error that was set or that is currently set
  47946. */
  47947. ;
  47948. _proto.error = function error(_error) {
  47949. if (typeof _error !== 'undefined') {
  47950. this.logger_('error occurred:', _error);
  47951. this.error_ = _error;
  47952. }
  47953. this.pendingSegment_ = null;
  47954. return this.error_;
  47955. };
  47956. _proto.endOfStream = function endOfStream() {
  47957. this.ended_ = true;
  47958. if (this.transmuxer_) {
  47959. // need to clear out any cached data to prepare for the new segment
  47960. segmentTransmuxer.reset(this.transmuxer_);
  47961. }
  47962. this.gopBuffer_.length = 0;
  47963. this.pause();
  47964. this.trigger('ended');
  47965. }
  47966. /**
  47967. * Indicates which time ranges are buffered
  47968. *
  47969. * @return {TimeRange}
  47970. * TimeRange object representing the current buffered ranges
  47971. */
  47972. ;
  47973. _proto.buffered_ = function buffered_() {
  47974. var trackInfo = this.getMediaInfo_();
  47975. if (!this.sourceUpdater_ || !trackInfo) {
  47976. return videojs.createTimeRanges();
  47977. }
  47978. if (this.loaderType_ === 'main') {
  47979. var hasAudio = trackInfo.hasAudio,
  47980. hasVideo = trackInfo.hasVideo,
  47981. isMuxed = trackInfo.isMuxed;
  47982. if (hasVideo && hasAudio && !this.audioDisabled_ && !isMuxed) {
  47983. return this.sourceUpdater_.buffered();
  47984. }
  47985. if (hasVideo) {
  47986. return this.sourceUpdater_.videoBuffered();
  47987. }
  47988. } // One case that can be ignored for now is audio only with alt audio,
  47989. // as we don't yet have proper support for that.
  47990. return this.sourceUpdater_.audioBuffered();
  47991. }
  47992. /**
  47993. * Gets and sets init segment for the provided map
  47994. *
  47995. * @param {Object} map
  47996. * The map object representing the init segment to get or set
  47997. * @param {boolean=} set
  47998. * If true, the init segment for the provided map should be saved
  47999. * @return {Object}
  48000. * map object for desired init segment
  48001. */
  48002. ;
  48003. _proto.initSegmentForMap = function initSegmentForMap(map, set) {
  48004. if (set === void 0) {
  48005. set = false;
  48006. }
  48007. if (!map) {
  48008. return null;
  48009. }
  48010. var id = initSegmentId(map);
  48011. var storedMap = this.initSegments_[id];
  48012. if (set && !storedMap && map.bytes) {
  48013. this.initSegments_[id] = storedMap = {
  48014. resolvedUri: map.resolvedUri,
  48015. byterange: map.byterange,
  48016. bytes: map.bytes,
  48017. tracks: map.tracks,
  48018. timescales: map.timescales
  48019. };
  48020. }
  48021. return storedMap || map;
  48022. }
  48023. /**
  48024. * Gets and sets key for the provided key
  48025. *
  48026. * @param {Object} key
  48027. * The key object representing the key to get or set
  48028. * @param {boolean=} set
  48029. * If true, the key for the provided key should be saved
  48030. * @return {Object}
  48031. * Key object for desired key
  48032. */
  48033. ;
  48034. _proto.segmentKey = function segmentKey(key, set) {
  48035. if (set === void 0) {
  48036. set = false;
  48037. }
  48038. if (!key) {
  48039. return null;
  48040. }
  48041. var id = segmentKeyId(key);
  48042. var storedKey = this.keyCache_[id]; // TODO: We should use the HTTP Expires header to invalidate our cache per
  48043. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.2.3
  48044. if (this.cacheEncryptionKeys_ && set && !storedKey && key.bytes) {
  48045. this.keyCache_[id] = storedKey = {
  48046. resolvedUri: key.resolvedUri,
  48047. bytes: key.bytes
  48048. };
  48049. }
  48050. var result = {
  48051. resolvedUri: (storedKey || key).resolvedUri
  48052. };
  48053. if (storedKey) {
  48054. result.bytes = storedKey.bytes;
  48055. }
  48056. return result;
  48057. }
  48058. /**
  48059. * Returns true if all configuration required for loading is present, otherwise false.
  48060. *
  48061. * @return {boolean} True if the all configuration is ready for loading
  48062. * @private
  48063. */
  48064. ;
  48065. _proto.couldBeginLoading_ = function couldBeginLoading_() {
  48066. return this.playlist_ && !this.paused();
  48067. }
  48068. /**
  48069. * load a playlist and start to fill the buffer
  48070. */
  48071. ;
  48072. _proto.load = function load() {
  48073. // un-pause
  48074. this.monitorBuffer_(); // if we don't have a playlist yet, keep waiting for one to be
  48075. // specified
  48076. if (!this.playlist_) {
  48077. return;
  48078. } // if all the configuration is ready, initialize and begin loading
  48079. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  48080. return this.init_();
  48081. } // if we're in the middle of processing a segment already, don't
  48082. // kick off an additional segment request
  48083. if (!this.couldBeginLoading_() || this.state !== 'READY' && this.state !== 'INIT') {
  48084. return;
  48085. }
  48086. this.state = 'READY';
  48087. }
  48088. /**
  48089. * Once all the starting parameters have been specified, begin
  48090. * operation. This method should only be invoked from the INIT
  48091. * state.
  48092. *
  48093. * @private
  48094. */
  48095. ;
  48096. _proto.init_ = function init_() {
  48097. this.state = 'READY'; // if this is the audio segment loader, and it hasn't been inited before, then any old
  48098. // audio data from the muxed content should be removed
  48099. this.resetEverything();
  48100. return this.monitorBuffer_();
  48101. }
  48102. /**
  48103. * set a playlist on the segment loader
  48104. *
  48105. * @param {PlaylistLoader} media the playlist to set on the segment loader
  48106. */
  48107. ;
  48108. _proto.playlist = function playlist(newPlaylist, options) {
  48109. if (options === void 0) {
  48110. options = {};
  48111. }
  48112. if (!newPlaylist) {
  48113. return;
  48114. }
  48115. var oldPlaylist = this.playlist_;
  48116. var segmentInfo = this.pendingSegment_;
  48117. this.playlist_ = newPlaylist;
  48118. this.xhrOptions_ = options; // when we haven't started playing yet, the start of a live playlist
  48119. // is always our zero-time so force a sync update each time the playlist
  48120. // is refreshed from the server
  48121. //
  48122. // Use the INIT state to determine if playback has started, as the playlist sync info
  48123. // should be fixed once requests begin (as sync points are generated based on sync
  48124. // info), but not before then.
  48125. if (this.state === 'INIT') {
  48126. newPlaylist.syncInfo = {
  48127. mediaSequence: newPlaylist.mediaSequence,
  48128. time: 0
  48129. }; // Setting the date time mapping means mapping the program date time (if available)
  48130. // to time 0 on the player's timeline. The playlist's syncInfo serves a similar
  48131. // purpose, mapping the initial mediaSequence to time zero. Since the syncInfo can
  48132. // be updated as the playlist is refreshed before the loader starts loading, the
  48133. // program date time mapping needs to be updated as well.
  48134. //
  48135. // This mapping is only done for the main loader because a program date time should
  48136. // map equivalently between playlists.
  48137. if (this.loaderType_ === 'main') {
  48138. this.syncController_.setDateTimeMappingForStart(newPlaylist);
  48139. }
  48140. }
  48141. var oldId = null;
  48142. if (oldPlaylist) {
  48143. if (oldPlaylist.id) {
  48144. oldId = oldPlaylist.id;
  48145. } else if (oldPlaylist.uri) {
  48146. oldId = oldPlaylist.uri;
  48147. }
  48148. }
  48149. this.logger_("playlist update [" + oldId + " => " + (newPlaylist.id || newPlaylist.uri) + "]"); // in VOD, this is always a rendition switch (or we updated our syncInfo above)
  48150. // in LIVE, we always want to update with new playlists (including refreshes)
  48151. this.trigger('syncinfoupdate'); // if we were unpaused but waiting for a playlist, start
  48152. // buffering now
  48153. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  48154. return this.init_();
  48155. }
  48156. if (!oldPlaylist || oldPlaylist.uri !== newPlaylist.uri) {
  48157. if (this.mediaIndex !== null) {
  48158. // we must reset/resync the segment loader when we switch renditions and
  48159. // the segment loader is already synced to the previous rendition
  48160. // on playlist changes we want it to be possible to fetch
  48161. // at the buffer for vod but not for live. So we use resetLoader
  48162. // for live and resyncLoader for vod. We want this because
  48163. // if a playlist uses independent and non-independent segments/parts the
  48164. // buffer may not accurately reflect the next segment that we should try
  48165. // downloading.
  48166. if (!newPlaylist.endList) {
  48167. this.resetLoader();
  48168. } else {
  48169. this.resyncLoader();
  48170. }
  48171. }
  48172. this.currentMediaInfo_ = void 0;
  48173. this.trigger('playlistupdate'); // the rest of this function depends on `oldPlaylist` being defined
  48174. return;
  48175. } // we reloaded the same playlist so we are in a live scenario
  48176. // and we will likely need to adjust the mediaIndex
  48177. var mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;
  48178. this.logger_("live window shift [" + mediaSequenceDiff + "]"); // update the mediaIndex on the SegmentLoader
  48179. // this is important because we can abort a request and this value must be
  48180. // equal to the last appended mediaIndex
  48181. if (this.mediaIndex !== null) {
  48182. this.mediaIndex -= mediaSequenceDiff; // this can happen if we are going to load the first segment, but get a playlist
  48183. // update during that. mediaIndex would go from 0 to -1 if mediaSequence in the
  48184. // new playlist was incremented by 1.
  48185. if (this.mediaIndex < 0) {
  48186. this.mediaIndex = null;
  48187. this.partIndex = null;
  48188. } else {
  48189. var segment = this.playlist_.segments[this.mediaIndex]; // partIndex should remain the same for the same segment
  48190. // unless parts fell off of the playlist for this segment.
  48191. // In that case we need to reset partIndex and resync
  48192. if (this.partIndex && (!segment.parts || !segment.parts.length || !segment.parts[this.partIndex])) {
  48193. var mediaIndex = this.mediaIndex;
  48194. this.logger_("currently processing part (index " + this.partIndex + ") no longer exists.");
  48195. this.resetLoader(); // We want to throw away the partIndex and the data associated with it,
  48196. // as the part was dropped from our current playlists segment.
  48197. // The mediaIndex will still be valid so keep that around.
  48198. this.mediaIndex = mediaIndex;
  48199. }
  48200. }
  48201. } // update the mediaIndex on the SegmentInfo object
  48202. // this is important because we will update this.mediaIndex with this value
  48203. // in `handleAppendsDone_` after the segment has been successfully appended
  48204. if (segmentInfo) {
  48205. segmentInfo.mediaIndex -= mediaSequenceDiff;
  48206. if (segmentInfo.mediaIndex < 0) {
  48207. segmentInfo.mediaIndex = null;
  48208. segmentInfo.partIndex = null;
  48209. } else {
  48210. // we need to update the referenced segment so that timing information is
  48211. // saved for the new playlist's segment, however, if the segment fell off the
  48212. // playlist, we can leave the old reference and just lose the timing info
  48213. if (segmentInfo.mediaIndex >= 0) {
  48214. segmentInfo.segment = newPlaylist.segments[segmentInfo.mediaIndex];
  48215. }
  48216. if (segmentInfo.partIndex >= 0 && segmentInfo.segment.parts) {
  48217. segmentInfo.part = segmentInfo.segment.parts[segmentInfo.partIndex];
  48218. }
  48219. }
  48220. }
  48221. this.syncController_.saveExpiredSegmentInfo(oldPlaylist, newPlaylist);
  48222. }
  48223. /**
  48224. * Prevent the loader from fetching additional segments. If there
  48225. * is a segment request outstanding, it will finish processing
  48226. * before the loader halts. A segment loader can be unpaused by
  48227. * calling load().
  48228. */
  48229. ;
  48230. _proto.pause = function pause() {
  48231. if (this.checkBufferTimeout_) {
  48232. window.clearTimeout(this.checkBufferTimeout_);
  48233. this.checkBufferTimeout_ = null;
  48234. }
  48235. }
  48236. /**
  48237. * Returns whether the segment loader is fetching additional
  48238. * segments when given the opportunity. This property can be
  48239. * modified through calls to pause() and load().
  48240. */
  48241. ;
  48242. _proto.paused = function paused() {
  48243. return this.checkBufferTimeout_ === null;
  48244. }
  48245. /**
  48246. * Delete all the buffered data and reset the SegmentLoader
  48247. *
  48248. * @param {Function} [done] an optional callback to be executed when the remove
  48249. * operation is complete
  48250. */
  48251. ;
  48252. _proto.resetEverything = function resetEverything(done) {
  48253. this.ended_ = false;
  48254. this.activeInitSegmentId_ = null;
  48255. this.appendInitSegment_ = {
  48256. audio: true,
  48257. video: true
  48258. };
  48259. this.resetLoader(); // remove from 0, the earliest point, to Infinity, to signify removal of everything.
  48260. // VTT Segment Loader doesn't need to do anything but in the regular SegmentLoader,
  48261. // we then clamp the value to duration if necessary.
  48262. this.remove(0, Infinity, done); // clears fmp4 captions
  48263. if (this.transmuxer_) {
  48264. this.transmuxer_.postMessage({
  48265. action: 'clearAllMp4Captions'
  48266. }); // reset the cache in the transmuxer
  48267. this.transmuxer_.postMessage({
  48268. action: 'reset'
  48269. });
  48270. }
  48271. }
  48272. /**
  48273. * Force the SegmentLoader to resync and start loading around the currentTime instead
  48274. * of starting at the end of the buffer
  48275. *
  48276. * Useful for fast quality changes
  48277. */
  48278. ;
  48279. _proto.resetLoader = function resetLoader() {
  48280. this.fetchAtBuffer_ = false;
  48281. this.resyncLoader();
  48282. }
  48283. /**
  48284. * Force the SegmentLoader to restart synchronization and make a conservative guess
  48285. * before returning to the simple walk-forward method
  48286. */
  48287. ;
  48288. _proto.resyncLoader = function resyncLoader() {
  48289. if (this.transmuxer_) {
  48290. // need to clear out any cached data to prepare for the new segment
  48291. segmentTransmuxer.reset(this.transmuxer_);
  48292. }
  48293. this.mediaIndex = null;
  48294. this.partIndex = null;
  48295. this.syncPoint_ = null;
  48296. this.isPendingTimestampOffset_ = false;
  48297. this.callQueue_ = [];
  48298. this.loadQueue_ = [];
  48299. this.metadataQueue_.id3 = [];
  48300. this.metadataQueue_.caption = [];
  48301. this.abort();
  48302. if (this.transmuxer_) {
  48303. this.transmuxer_.postMessage({
  48304. action: 'clearParsedMp4Captions'
  48305. });
  48306. }
  48307. }
  48308. /**
  48309. * Remove any data in the source buffer between start and end times
  48310. *
  48311. * @param {number} start - the start time of the region to remove from the buffer
  48312. * @param {number} end - the end time of the region to remove from the buffer
  48313. * @param {Function} [done] - an optional callback to be executed when the remove
  48314. * @param {boolean} force - force all remove operations to happen
  48315. * operation is complete
  48316. */
  48317. ;
  48318. _proto.remove = function remove(start, end, done, force) {
  48319. if (done === void 0) {
  48320. done = function done() {};
  48321. }
  48322. if (force === void 0) {
  48323. force = false;
  48324. } // clamp end to duration if we need to remove everything.
  48325. // This is due to a browser bug that causes issues if we remove to Infinity.
  48326. // videojs/videojs-contrib-hls#1225
  48327. if (end === Infinity) {
  48328. end = this.duration_();
  48329. } // skip removes that would throw an error
  48330. // commonly happens during a rendition switch at the start of a video
  48331. // from start 0 to end 0
  48332. if (end <= start) {
  48333. this.logger_('skipping remove because end ${end} is <= start ${start}');
  48334. return;
  48335. }
  48336. if (!this.sourceUpdater_ || !this.getMediaInfo_()) {
  48337. this.logger_('skipping remove because no source updater or starting media info'); // nothing to remove if we haven't processed any media
  48338. return;
  48339. } // set it to one to complete this function's removes
  48340. var removesRemaining = 1;
  48341. var removeFinished = function removeFinished() {
  48342. removesRemaining--;
  48343. if (removesRemaining === 0) {
  48344. done();
  48345. }
  48346. };
  48347. if (force || !this.audioDisabled_) {
  48348. removesRemaining++;
  48349. this.sourceUpdater_.removeAudio(start, end, removeFinished);
  48350. } // While it would be better to only remove video if the main loader has video, this
  48351. // should be safe with audio only as removeVideo will call back even if there's no
  48352. // video buffer.
  48353. //
  48354. // In theory we can check to see if there's video before calling the remove, but in
  48355. // the event that we're switching between renditions and from video to audio only
  48356. // (when we add support for that), we may need to clear the video contents despite
  48357. // what the new media will contain.
  48358. if (force || this.loaderType_ === 'main') {
  48359. this.gopBuffer_ = removeGopBuffer(this.gopBuffer_, start, end, this.timeMapping_);
  48360. removesRemaining++;
  48361. this.sourceUpdater_.removeVideo(start, end, removeFinished);
  48362. } // remove any captions and ID3 tags
  48363. for (var track in this.inbandTextTracks_) {
  48364. removeCuesFromTrack(start, end, this.inbandTextTracks_[track]);
  48365. }
  48366. removeCuesFromTrack(start, end, this.segmentMetadataTrack_); // finished this function's removes
  48367. removeFinished();
  48368. }
  48369. /**
  48370. * (re-)schedule monitorBufferTick_ to run as soon as possible
  48371. *
  48372. * @private
  48373. */
  48374. ;
  48375. _proto.monitorBuffer_ = function monitorBuffer_() {
  48376. if (this.checkBufferTimeout_) {
  48377. window.clearTimeout(this.checkBufferTimeout_);
  48378. }
  48379. this.checkBufferTimeout_ = window.setTimeout(this.monitorBufferTick_.bind(this), 1);
  48380. }
  48381. /**
  48382. * As long as the SegmentLoader is in the READY state, periodically
  48383. * invoke fillBuffer_().
  48384. *
  48385. * @private
  48386. */
  48387. ;
  48388. _proto.monitorBufferTick_ = function monitorBufferTick_() {
  48389. if (this.state === 'READY') {
  48390. this.fillBuffer_();
  48391. }
  48392. if (this.checkBufferTimeout_) {
  48393. window.clearTimeout(this.checkBufferTimeout_);
  48394. }
  48395. this.checkBufferTimeout_ = window.setTimeout(this.monitorBufferTick_.bind(this), CHECK_BUFFER_DELAY);
  48396. }
  48397. /**
  48398. * fill the buffer with segements unless the sourceBuffers are
  48399. * currently updating
  48400. *
  48401. * Note: this function should only ever be called by monitorBuffer_
  48402. * and never directly
  48403. *
  48404. * @private
  48405. */
  48406. ;
  48407. _proto.fillBuffer_ = function fillBuffer_() {
  48408. // TODO since the source buffer maintains a queue, and we shouldn't call this function
  48409. // except when we're ready for the next segment, this check can most likely be removed
  48410. if (this.sourceUpdater_.updating()) {
  48411. return;
  48412. } // see if we need to begin loading immediately
  48413. var segmentInfo = this.chooseNextRequest_();
  48414. if (!segmentInfo) {
  48415. return;
  48416. }
  48417. if (typeof segmentInfo.timestampOffset === 'number') {
  48418. this.isPendingTimestampOffset_ = false;
  48419. this.timelineChangeController_.pendingTimelineChange({
  48420. type: this.loaderType_,
  48421. from: this.currentTimeline_,
  48422. to: segmentInfo.timeline
  48423. });
  48424. }
  48425. this.loadSegment_(segmentInfo);
  48426. }
  48427. /**
  48428. * Determines if we should call endOfStream on the media source based
  48429. * on the state of the buffer or if appened segment was the final
  48430. * segment in the playlist.
  48431. *
  48432. * @param {number} [mediaIndex] the media index of segment we last appended
  48433. * @param {Object} [playlist] a media playlist object
  48434. * @return {boolean} do we need to call endOfStream on the MediaSource
  48435. */
  48436. ;
  48437. _proto.isEndOfStream_ = function isEndOfStream_(mediaIndex, playlist, partIndex) {
  48438. if (mediaIndex === void 0) {
  48439. mediaIndex = this.mediaIndex;
  48440. }
  48441. if (playlist === void 0) {
  48442. playlist = this.playlist_;
  48443. }
  48444. if (partIndex === void 0) {
  48445. partIndex = this.partIndex;
  48446. }
  48447. if (!playlist || !this.mediaSource_) {
  48448. return false;
  48449. }
  48450. var segment = typeof mediaIndex === 'number' && playlist.segments[mediaIndex]; // mediaIndex is zero based but length is 1 based
  48451. var appendedLastSegment = mediaIndex + 1 === playlist.segments.length; // true if there are no parts, or this is the last part.
  48452. var appendedLastPart = !segment || !segment.parts || partIndex + 1 === segment.parts.length; // if we've buffered to the end of the video, we need to call endOfStream
  48453. // so that MediaSources can trigger the `ended` event when it runs out of
  48454. // buffered data instead of waiting for me
  48455. return playlist.endList && this.mediaSource_.readyState === 'open' && appendedLastSegment && appendedLastPart;
  48456. }
  48457. /**
  48458. * Determines what request should be made given current segment loader state.
  48459. *
  48460. * @return {Object} a request object that describes the segment/part to load
  48461. */
  48462. ;
  48463. _proto.chooseNextRequest_ = function chooseNextRequest_() {
  48464. var buffered = this.buffered_();
  48465. var bufferedEnd = lastBufferedEnd(buffered) || 0;
  48466. var bufferedTime = timeAheadOf(buffered, this.currentTime_());
  48467. var preloaded = !this.hasPlayed_() && bufferedTime >= 1;
  48468. var haveEnoughBuffer = bufferedTime >= this.goalBufferLength_();
  48469. var segments = this.playlist_.segments; // return no segment if:
  48470. // 1. we don't have segments
  48471. // 2. The video has not yet played and we already downloaded a segment
  48472. // 3. we already have enough buffered time
  48473. if (!segments.length || preloaded || haveEnoughBuffer) {
  48474. return null;
  48475. }
  48476. this.syncPoint_ = this.syncPoint_ || this.syncController_.getSyncPoint(this.playlist_, this.duration_(), this.currentTimeline_, this.currentTime_());
  48477. var next = {
  48478. partIndex: null,
  48479. mediaIndex: null,
  48480. startOfSegment: null,
  48481. playlist: this.playlist_,
  48482. isSyncRequest: Boolean(!this.syncPoint_)
  48483. };
  48484. if (next.isSyncRequest) {
  48485. next.mediaIndex = getSyncSegmentCandidate(this.currentTimeline_, segments, bufferedEnd);
  48486. } else if (this.mediaIndex !== null) {
  48487. var segment = segments[this.mediaIndex];
  48488. var partIndex = typeof this.partIndex === 'number' ? this.partIndex : -1;
  48489. next.startOfSegment = segment.end ? segment.end : bufferedEnd;
  48490. if (segment.parts && segment.parts[partIndex + 1]) {
  48491. next.mediaIndex = this.mediaIndex;
  48492. next.partIndex = partIndex + 1;
  48493. } else {
  48494. next.mediaIndex = this.mediaIndex + 1;
  48495. }
  48496. } else {
  48497. // Find the segment containing the end of the buffer or current time.
  48498. var _Playlist$getMediaInf = Playlist.getMediaInfoForTime({
  48499. experimentalExactManifestTimings: this.experimentalExactManifestTimings,
  48500. playlist: this.playlist_,
  48501. currentTime: this.fetchAtBuffer_ ? bufferedEnd : this.currentTime_(),
  48502. startingPartIndex: this.syncPoint_.partIndex,
  48503. startingSegmentIndex: this.syncPoint_.segmentIndex,
  48504. startTime: this.syncPoint_.time
  48505. }),
  48506. segmentIndex = _Playlist$getMediaInf.segmentIndex,
  48507. startTime = _Playlist$getMediaInf.startTime,
  48508. _partIndex = _Playlist$getMediaInf.partIndex;
  48509. next.getMediaInfoForTime = this.fetchAtBuffer_ ? "bufferedEnd " + bufferedEnd : "currentTime " + this.currentTime_();
  48510. next.mediaIndex = segmentIndex;
  48511. next.startOfSegment = startTime;
  48512. next.partIndex = _partIndex;
  48513. }
  48514. var nextSegment = segments[next.mediaIndex];
  48515. var nextPart = nextSegment && typeof next.partIndex === 'number' && nextSegment.parts && nextSegment.parts[next.partIndex]; // if the next segment index is invalid or
  48516. // the next partIndex is invalid do not choose a next segment.
  48517. if (!nextSegment || typeof next.partIndex === 'number' && !nextPart) {
  48518. return null;
  48519. } // if the next segment has parts, and we don't have a partIndex.
  48520. // Set partIndex to 0
  48521. if (typeof next.partIndex !== 'number' && nextSegment.parts) {
  48522. next.partIndex = 0;
  48523. nextPart = nextSegment.parts[0];
  48524. } // if we have no buffered data then we need to make sure
  48525. // that the next part we append is "independent" if possible.
  48526. // So we check if the previous part is independent, and request
  48527. // it if it is.
  48528. if (!bufferedTime && nextPart && !nextPart.independent) {
  48529. if (next.partIndex === 0) {
  48530. var lastSegment = segments[next.mediaIndex - 1];
  48531. var lastSegmentLastPart = lastSegment.parts && lastSegment.parts.length && lastSegment.parts[lastSegment.parts.length - 1];
  48532. if (lastSegmentLastPart && lastSegmentLastPart.independent) {
  48533. next.mediaIndex -= 1;
  48534. next.partIndex = lastSegment.parts.length - 1;
  48535. next.independent = 'previous segment';
  48536. }
  48537. } else if (nextSegment.parts[next.partIndex - 1].independent) {
  48538. next.partIndex -= 1;
  48539. next.independent = 'previous part';
  48540. }
  48541. }
  48542. var ended = this.mediaSource_ && this.mediaSource_.readyState === 'ended'; // do not choose a next segment if all of the following:
  48543. // 1. this is the last segment in the playlist
  48544. // 2. end of stream has been called on the media source already
  48545. // 3. the player is not seeking
  48546. if (next.mediaIndex >= segments.length - 1 && ended && !this.seeking_()) {
  48547. return null;
  48548. }
  48549. return this.generateSegmentInfo_(next);
  48550. };
  48551. _proto.generateSegmentInfo_ = function generateSegmentInfo_(options) {
  48552. var independent = options.independent,
  48553. playlist = options.playlist,
  48554. mediaIndex = options.mediaIndex,
  48555. startOfSegment = options.startOfSegment,
  48556. isSyncRequest = options.isSyncRequest,
  48557. partIndex = options.partIndex,
  48558. forceTimestampOffset = options.forceTimestampOffset,
  48559. getMediaInfoForTime = options.getMediaInfoForTime;
  48560. var segment = playlist.segments[mediaIndex];
  48561. var part = typeof partIndex === 'number' && segment.parts[partIndex];
  48562. var segmentInfo = {
  48563. requestId: 'segment-loader-' + Math.random(),
  48564. // resolve the segment URL relative to the playlist
  48565. uri: part && part.resolvedUri || segment.resolvedUri,
  48566. // the segment's mediaIndex at the time it was requested
  48567. mediaIndex: mediaIndex,
  48568. partIndex: part ? partIndex : null,
  48569. // whether or not to update the SegmentLoader's state with this
  48570. // segment's mediaIndex
  48571. isSyncRequest: isSyncRequest,
  48572. startOfSegment: startOfSegment,
  48573. // the segment's playlist
  48574. playlist: playlist,
  48575. // unencrypted bytes of the segment
  48576. bytes: null,
  48577. // when a key is defined for this segment, the encrypted bytes
  48578. encryptedBytes: null,
  48579. // The target timestampOffset for this segment when we append it
  48580. // to the source buffer
  48581. timestampOffset: null,
  48582. // The timeline that the segment is in
  48583. timeline: segment.timeline,
  48584. // The expected duration of the segment in seconds
  48585. duration: part && part.duration || segment.duration,
  48586. // retain the segment in case the playlist updates while doing an async process
  48587. segment: segment,
  48588. part: part,
  48589. byteLength: 0,
  48590. transmuxer: this.transmuxer_,
  48591. // type of getMediaInfoForTime that was used to get this segment
  48592. getMediaInfoForTime: getMediaInfoForTime,
  48593. independent: independent
  48594. };
  48595. var overrideCheck = typeof forceTimestampOffset !== 'undefined' ? forceTimestampOffset : this.isPendingTimestampOffset_;
  48596. segmentInfo.timestampOffset = this.timestampOffsetForSegment_({
  48597. segmentTimeline: segment.timeline,
  48598. currentTimeline: this.currentTimeline_,
  48599. startOfSegment: startOfSegment,
  48600. buffered: this.buffered_(),
  48601. overrideCheck: overrideCheck
  48602. });
  48603. var audioBufferedEnd = lastBufferedEnd(this.sourceUpdater_.audioBuffered());
  48604. if (typeof audioBufferedEnd === 'number') {
  48605. // since the transmuxer is using the actual timing values, but the buffer is
  48606. // adjusted by the timestamp offset, we must adjust the value here
  48607. segmentInfo.audioAppendStart = audioBufferedEnd - this.sourceUpdater_.audioTimestampOffset();
  48608. }
  48609. if (this.sourceUpdater_.videoBuffered().length) {
  48610. segmentInfo.gopsToAlignWith = gopsSafeToAlignWith(this.gopBuffer_, // since the transmuxer is using the actual timing values, but the time is
  48611. // adjusted by the timestmap offset, we must adjust the value here
  48612. this.currentTime_() - this.sourceUpdater_.videoTimestampOffset(), this.timeMapping_);
  48613. }
  48614. return segmentInfo;
  48615. } // get the timestampoffset for a segment,
  48616. // added so that vtt segment loader can override and prevent
  48617. // adding timestamp offsets.
  48618. ;
  48619. _proto.timestampOffsetForSegment_ = function timestampOffsetForSegment_(options) {
  48620. return timestampOffsetForSegment(options);
  48621. }
  48622. /**
  48623. * Determines if the network has enough bandwidth to complete the current segment
  48624. * request in a timely manner. If not, the request will be aborted early and bandwidth
  48625. * updated to trigger a playlist switch.
  48626. *
  48627. * @param {Object} stats
  48628. * Object containing stats about the request timing and size
  48629. * @private
  48630. */
  48631. ;
  48632. _proto.earlyAbortWhenNeeded_ = function earlyAbortWhenNeeded_(stats) {
  48633. if (this.vhs_.tech_.paused() || // Don't abort if the current playlist is on the lowestEnabledRendition
  48634. // TODO: Replace using timeout with a boolean indicating whether this playlist is
  48635. // the lowestEnabledRendition.
  48636. !this.xhrOptions_.timeout || // Don't abort if we have no bandwidth information to estimate segment sizes
  48637. !this.playlist_.attributes.BANDWIDTH) {
  48638. return;
  48639. } // Wait at least 1 second since the first byte of data has been received before
  48640. // using the calculated bandwidth from the progress event to allow the bitrate
  48641. // to stabilize
  48642. if (Date.now() - (stats.firstBytesReceivedAt || Date.now()) < 1000) {
  48643. return;
  48644. }
  48645. var currentTime = this.currentTime_();
  48646. var measuredBandwidth = stats.bandwidth;
  48647. var segmentDuration = this.pendingSegment_.duration;
  48648. var requestTimeRemaining = Playlist.estimateSegmentRequestTime(segmentDuration, measuredBandwidth, this.playlist_, stats.bytesReceived); // Subtract 1 from the timeUntilRebuffer so we still consider an early abort
  48649. // if we are only left with less than 1 second when the request completes.
  48650. // A negative timeUntilRebuffering indicates we are already rebuffering
  48651. var timeUntilRebuffer$1 = timeUntilRebuffer(this.buffered_(), currentTime, this.vhs_.tech_.playbackRate()) - 1; // Only consider aborting early if the estimated time to finish the download
  48652. // is larger than the estimated time until the player runs out of forward buffer
  48653. if (requestTimeRemaining <= timeUntilRebuffer$1) {
  48654. return;
  48655. }
  48656. var switchCandidate = minRebufferMaxBandwidthSelector({
  48657. master: this.vhs_.playlists.master,
  48658. currentTime: currentTime,
  48659. bandwidth: measuredBandwidth,
  48660. duration: this.duration_(),
  48661. segmentDuration: segmentDuration,
  48662. timeUntilRebuffer: timeUntilRebuffer$1,
  48663. currentTimeline: this.currentTimeline_,
  48664. syncController: this.syncController_
  48665. });
  48666. if (!switchCandidate) {
  48667. return;
  48668. }
  48669. var rebufferingImpact = requestTimeRemaining - timeUntilRebuffer$1;
  48670. var timeSavedBySwitching = rebufferingImpact - switchCandidate.rebufferingImpact;
  48671. var minimumTimeSaving = 0.5; // If we are already rebuffering, increase the amount of variance we add to the
  48672. // potential round trip time of the new request so that we are not too aggressive
  48673. // with switching to a playlist that might save us a fraction of a second.
  48674. if (timeUntilRebuffer$1 <= TIME_FUDGE_FACTOR) {
  48675. minimumTimeSaving = 1;
  48676. }
  48677. if (!switchCandidate.playlist || switchCandidate.playlist.uri === this.playlist_.uri || timeSavedBySwitching < minimumTimeSaving) {
  48678. return;
  48679. } // set the bandwidth to that of the desired playlist being sure to scale by
  48680. // BANDWIDTH_VARIANCE and add one so the playlist selector does not exclude it
  48681. // don't trigger a bandwidthupdate as the bandwidth is artifial
  48682. this.bandwidth = switchCandidate.playlist.attributes.BANDWIDTH * Config.BANDWIDTH_VARIANCE + 1;
  48683. this.trigger('earlyabort');
  48684. };
  48685. _proto.handleAbort_ = function handleAbort_(segmentInfo) {
  48686. this.logger_("Aborting " + segmentInfoString(segmentInfo));
  48687. this.mediaRequestsAborted += 1;
  48688. }
  48689. /**
  48690. * XHR `progress` event handler
  48691. *
  48692. * @param {Event}
  48693. * The XHR `progress` event
  48694. * @param {Object} simpleSegment
  48695. * A simplified segment object copy
  48696. * @private
  48697. */
  48698. ;
  48699. _proto.handleProgress_ = function handleProgress_(event, simpleSegment) {
  48700. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  48701. if (this.checkForAbort_(simpleSegment.requestId)) {
  48702. return;
  48703. }
  48704. this.trigger('progress');
  48705. };
  48706. _proto.handleTrackInfo_ = function handleTrackInfo_(simpleSegment, trackInfo) {
  48707. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  48708. if (this.checkForAbort_(simpleSegment.requestId)) {
  48709. return;
  48710. }
  48711. if (this.checkForIllegalMediaSwitch(trackInfo)) {
  48712. return;
  48713. }
  48714. trackInfo = trackInfo || {}; // When we have track info, determine what media types this loader is dealing with.
  48715. // Guard against cases where we're not getting track info at all until we are
  48716. // certain that all streams will provide it.
  48717. if (!shallowEqual(this.currentMediaInfo_, trackInfo)) {
  48718. this.appendInitSegment_ = {
  48719. audio: true,
  48720. video: true
  48721. };
  48722. this.startingMediaInfo_ = trackInfo;
  48723. this.currentMediaInfo_ = trackInfo;
  48724. this.logger_('trackinfo update', trackInfo);
  48725. this.trigger('trackinfo');
  48726. } // trackinfo may cause an abort if the trackinfo
  48727. // causes a codec change to an unsupported codec.
  48728. if (this.checkForAbort_(simpleSegment.requestId)) {
  48729. return;
  48730. } // set trackinfo on the pending segment so that
  48731. // it can append.
  48732. this.pendingSegment_.trackInfo = trackInfo; // check if any calls were waiting on the track info
  48733. if (this.hasEnoughInfoToAppend_()) {
  48734. this.processCallQueue_();
  48735. }
  48736. };
  48737. _proto.handleTimingInfo_ = function handleTimingInfo_(simpleSegment, mediaType, timeType, time) {
  48738. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  48739. if (this.checkForAbort_(simpleSegment.requestId)) {
  48740. return;
  48741. }
  48742. var segmentInfo = this.pendingSegment_;
  48743. var timingInfoProperty = timingInfoPropertyForMedia(mediaType);
  48744. segmentInfo[timingInfoProperty] = segmentInfo[timingInfoProperty] || {};
  48745. segmentInfo[timingInfoProperty][timeType] = time;
  48746. this.logger_("timinginfo: " + mediaType + " - " + timeType + " - " + time); // check if any calls were waiting on the timing info
  48747. if (this.hasEnoughInfoToAppend_()) {
  48748. this.processCallQueue_();
  48749. }
  48750. };
  48751. _proto.handleCaptions_ = function handleCaptions_(simpleSegment, captionData) {
  48752. var _this2 = this;
  48753. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  48754. if (this.checkForAbort_(simpleSegment.requestId)) {
  48755. return;
  48756. } // This could only happen with fmp4 segments, but
  48757. // should still not happen in general
  48758. if (captionData.length === 0) {
  48759. this.logger_('SegmentLoader received no captions from a caption event');
  48760. return;
  48761. }
  48762. var segmentInfo = this.pendingSegment_; // Wait until we have some video data so that caption timing
  48763. // can be adjusted by the timestamp offset
  48764. if (!segmentInfo.hasAppendedData_) {
  48765. this.metadataQueue_.caption.push(this.handleCaptions_.bind(this, simpleSegment, captionData));
  48766. return;
  48767. }
  48768. var timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset();
  48769. var captionTracks = {}; // get total start/end and captions for each track/stream
  48770. captionData.forEach(function (caption) {
  48771. // caption.stream is actually a track name...
  48772. // set to the existing values in tracks or default values
  48773. captionTracks[caption.stream] = captionTracks[caption.stream] || {
  48774. // Infinity, as any other value will be less than this
  48775. startTime: Infinity,
  48776. captions: [],
  48777. // 0 as an other value will be more than this
  48778. endTime: 0
  48779. };
  48780. var captionTrack = captionTracks[caption.stream];
  48781. captionTrack.startTime = Math.min(captionTrack.startTime, caption.startTime + timestampOffset);
  48782. captionTrack.endTime = Math.max(captionTrack.endTime, caption.endTime + timestampOffset);
  48783. captionTrack.captions.push(caption);
  48784. });
  48785. Object.keys(captionTracks).forEach(function (trackName) {
  48786. var _captionTracks$trackN = captionTracks[trackName],
  48787. startTime = _captionTracks$trackN.startTime,
  48788. endTime = _captionTracks$trackN.endTime,
  48789. captions = _captionTracks$trackN.captions;
  48790. var inbandTextTracks = _this2.inbandTextTracks_;
  48791. _this2.logger_("adding cues from " + startTime + " -> " + endTime + " for " + trackName);
  48792. createCaptionsTrackIfNotExists(inbandTextTracks, _this2.vhs_.tech_, trackName); // clear out any cues that start and end at the same time period for the same track.
  48793. // We do this because a rendition change that also changes the timescale for captions
  48794. // will result in captions being re-parsed for certain segments. If we add them again
  48795. // without clearing we will have two of the same captions visible.
  48796. removeCuesFromTrack(startTime, endTime, inbandTextTracks[trackName]);
  48797. addCaptionData({
  48798. captionArray: captions,
  48799. inbandTextTracks: inbandTextTracks,
  48800. timestampOffset: timestampOffset
  48801. });
  48802. }); // Reset stored captions since we added parsed
  48803. // captions to a text track at this point
  48804. if (this.transmuxer_) {
  48805. this.transmuxer_.postMessage({
  48806. action: 'clearParsedMp4Captions'
  48807. });
  48808. }
  48809. };
  48810. _proto.handleId3_ = function handleId3_(simpleSegment, id3Frames, dispatchType) {
  48811. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  48812. if (this.checkForAbort_(simpleSegment.requestId)) {
  48813. return;
  48814. }
  48815. var segmentInfo = this.pendingSegment_; // we need to have appended data in order for the timestamp offset to be set
  48816. if (!segmentInfo.hasAppendedData_) {
  48817. this.metadataQueue_.id3.push(this.handleId3_.bind(this, simpleSegment, id3Frames, dispatchType));
  48818. return;
  48819. }
  48820. var timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset(); // There's potentially an issue where we could double add metadata if there's a muxed
  48821. // audio/video source with a metadata track, and an alt audio with a metadata track.
  48822. // However, this probably won't happen, and if it does it can be handled then.
  48823. createMetadataTrackIfNotExists(this.inbandTextTracks_, dispatchType, this.vhs_.tech_);
  48824. addMetadata({
  48825. inbandTextTracks: this.inbandTextTracks_,
  48826. metadataArray: id3Frames,
  48827. timestampOffset: timestampOffset,
  48828. videoDuration: this.duration_()
  48829. });
  48830. };
  48831. _proto.processMetadataQueue_ = function processMetadataQueue_() {
  48832. this.metadataQueue_.id3.forEach(function (fn) {
  48833. return fn();
  48834. });
  48835. this.metadataQueue_.caption.forEach(function (fn) {
  48836. return fn();
  48837. });
  48838. this.metadataQueue_.id3 = [];
  48839. this.metadataQueue_.caption = [];
  48840. };
  48841. _proto.processCallQueue_ = function processCallQueue_() {
  48842. var callQueue = this.callQueue_; // Clear out the queue before the queued functions are run, since some of the
  48843. // functions may check the length of the load queue and default to pushing themselves
  48844. // back onto the queue.
  48845. this.callQueue_ = [];
  48846. callQueue.forEach(function (fun) {
  48847. return fun();
  48848. });
  48849. };
  48850. _proto.processLoadQueue_ = function processLoadQueue_() {
  48851. var loadQueue = this.loadQueue_; // Clear out the queue before the queued functions are run, since some of the
  48852. // functions may check the length of the load queue and default to pushing themselves
  48853. // back onto the queue.
  48854. this.loadQueue_ = [];
  48855. loadQueue.forEach(function (fun) {
  48856. return fun();
  48857. });
  48858. }
  48859. /**
  48860. * Determines whether the loader has enough info to load the next segment.
  48861. *
  48862. * @return {boolean}
  48863. * Whether or not the loader has enough info to load the next segment
  48864. */
  48865. ;
  48866. _proto.hasEnoughInfoToLoad_ = function hasEnoughInfoToLoad_() {
  48867. // Since primary timing goes by video, only the audio loader potentially needs to wait
  48868. // to load.
  48869. if (this.loaderType_ !== 'audio') {
  48870. return true;
  48871. }
  48872. var segmentInfo = this.pendingSegment_; // A fill buffer must have already run to establish a pending segment before there's
  48873. // enough info to load.
  48874. if (!segmentInfo) {
  48875. return false;
  48876. } // The first segment can and should be loaded immediately so that source buffers are
  48877. // created together (before appending). Source buffer creation uses the presence of
  48878. // audio and video data to determine whether to create audio/video source buffers, and
  48879. // uses processed (transmuxed or parsed) media to determine the types required.
  48880. if (!this.getCurrentMediaInfo_()) {
  48881. return true;
  48882. }
  48883. if ( // Technically, instead of waiting to load a segment on timeline changes, a segment
  48884. // can be requested and downloaded and only wait before it is transmuxed or parsed.
  48885. // But in practice, there are a few reasons why it is better to wait until a loader
  48886. // is ready to append that segment before requesting and downloading:
  48887. //
  48888. // 1. Because audio and main loaders cross discontinuities together, if this loader
  48889. // is waiting for the other to catch up, then instead of requesting another
  48890. // segment and using up more bandwidth, by not yet loading, more bandwidth is
  48891. // allotted to the loader currently behind.
  48892. // 2. media-segment-request doesn't have to have logic to consider whether a segment
  48893. // is ready to be processed or not, isolating the queueing behavior to the loader.
  48894. // 3. The audio loader bases some of its segment properties on timing information
  48895. // provided by the main loader, meaning that, if the logic for waiting on
  48896. // processing was in media-segment-request, then it would also need to know how
  48897. // to re-generate the segment information after the main loader caught up.
  48898. shouldWaitForTimelineChange({
  48899. timelineChangeController: this.timelineChangeController_,
  48900. currentTimeline: this.currentTimeline_,
  48901. segmentTimeline: segmentInfo.timeline,
  48902. loaderType: this.loaderType_,
  48903. audioDisabled: this.audioDisabled_
  48904. })) {
  48905. return false;
  48906. }
  48907. return true;
  48908. };
  48909. _proto.getCurrentMediaInfo_ = function getCurrentMediaInfo_(segmentInfo) {
  48910. if (segmentInfo === void 0) {
  48911. segmentInfo = this.pendingSegment_;
  48912. }
  48913. return segmentInfo && segmentInfo.trackInfo || this.currentMediaInfo_;
  48914. };
  48915. _proto.getMediaInfo_ = function getMediaInfo_(segmentInfo) {
  48916. if (segmentInfo === void 0) {
  48917. segmentInfo = this.pendingSegment_;
  48918. }
  48919. return this.getCurrentMediaInfo_(segmentInfo) || this.startingMediaInfo_;
  48920. };
  48921. _proto.getPendingSegmentPlaylist = function getPendingSegmentPlaylist() {
  48922. return this.pendingSegment_ ? this.pendingSegment_.playlist : null;
  48923. };
  48924. _proto.hasEnoughInfoToAppend_ = function hasEnoughInfoToAppend_() {
  48925. if (!this.sourceUpdater_.ready()) {
  48926. return false;
  48927. } // If content needs to be removed or the loader is waiting on an append reattempt,
  48928. // then no additional content should be appended until the prior append is resolved.
  48929. if (this.waitingOnRemove_ || this.quotaExceededErrorRetryTimeout_) {
  48930. return false;
  48931. }
  48932. var segmentInfo = this.pendingSegment_;
  48933. var trackInfo = this.getCurrentMediaInfo_(); // no segment to append any data for or
  48934. // we do not have information on this specific
  48935. // segment yet
  48936. if (!segmentInfo || !trackInfo) {
  48937. return false;
  48938. }
  48939. var hasAudio = trackInfo.hasAudio,
  48940. hasVideo = trackInfo.hasVideo,
  48941. isMuxed = trackInfo.isMuxed;
  48942. if (hasVideo && !segmentInfo.videoTimingInfo) {
  48943. return false;
  48944. } // muxed content only relies on video timing information for now.
  48945. if (hasAudio && !this.audioDisabled_ && !isMuxed && !segmentInfo.audioTimingInfo) {
  48946. return false;
  48947. }
  48948. if (shouldWaitForTimelineChange({
  48949. timelineChangeController: this.timelineChangeController_,
  48950. currentTimeline: this.currentTimeline_,
  48951. segmentTimeline: segmentInfo.timeline,
  48952. loaderType: this.loaderType_,
  48953. audioDisabled: this.audioDisabled_
  48954. })) {
  48955. return false;
  48956. }
  48957. return true;
  48958. };
  48959. _proto.handleData_ = function handleData_(simpleSegment, result) {
  48960. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  48961. if (this.checkForAbort_(simpleSegment.requestId)) {
  48962. return;
  48963. } // If there's anything in the call queue, then this data came later and should be
  48964. // executed after the calls currently queued.
  48965. if (this.callQueue_.length || !this.hasEnoughInfoToAppend_()) {
  48966. this.callQueue_.push(this.handleData_.bind(this, simpleSegment, result));
  48967. return;
  48968. }
  48969. var segmentInfo = this.pendingSegment_; // update the time mapping so we can translate from display time to media time
  48970. this.setTimeMapping_(segmentInfo.timeline); // for tracking overall stats
  48971. this.updateMediaSecondsLoaded_(segmentInfo.part || segmentInfo.segment); // Note that the state isn't changed from loading to appending. This is because abort
  48972. // logic may change behavior depending on the state, and changing state too early may
  48973. // inflate our estimates of bandwidth. In the future this should be re-examined to
  48974. // note more granular states.
  48975. // don't process and append data if the mediaSource is closed
  48976. if (this.mediaSource_.readyState === 'closed') {
  48977. return;
  48978. } // if this request included an initialization segment, save that data
  48979. // to the initSegment cache
  48980. if (simpleSegment.map) {
  48981. simpleSegment.map = this.initSegmentForMap(simpleSegment.map, true); // move over init segment properties to media request
  48982. segmentInfo.segment.map = simpleSegment.map;
  48983. } // if this request included a segment key, save that data in the cache
  48984. if (simpleSegment.key) {
  48985. this.segmentKey(simpleSegment.key, true);
  48986. }
  48987. segmentInfo.isFmp4 = simpleSegment.isFmp4;
  48988. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  48989. if (segmentInfo.isFmp4) {
  48990. this.trigger('fmp4');
  48991. segmentInfo.timingInfo.start = segmentInfo[timingInfoPropertyForMedia(result.type)].start;
  48992. } else {
  48993. var trackInfo = this.getCurrentMediaInfo_();
  48994. var useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  48995. var firstVideoFrameTimeForData;
  48996. if (useVideoTimingInfo) {
  48997. firstVideoFrameTimeForData = segmentInfo.videoTimingInfo.start;
  48998. } // Segment loader knows more about segment timing than the transmuxer (in certain
  48999. // aspects), so make any changes required for a more accurate start time.
  49000. // Don't set the end time yet, as the segment may not be finished processing.
  49001. segmentInfo.timingInfo.start = this.trueSegmentStart_({
  49002. currentStart: segmentInfo.timingInfo.start,
  49003. playlist: segmentInfo.playlist,
  49004. mediaIndex: segmentInfo.mediaIndex,
  49005. currentVideoTimestampOffset: this.sourceUpdater_.videoTimestampOffset(),
  49006. useVideoTimingInfo: useVideoTimingInfo,
  49007. firstVideoFrameTimeForData: firstVideoFrameTimeForData,
  49008. videoTimingInfo: segmentInfo.videoTimingInfo,
  49009. audioTimingInfo: segmentInfo.audioTimingInfo
  49010. });
  49011. } // Init segments for audio and video only need to be appended in certain cases. Now
  49012. // that data is about to be appended, we can check the final cases to determine
  49013. // whether we should append an init segment.
  49014. this.updateAppendInitSegmentStatus(segmentInfo, result.type); // Timestamp offset should be updated once we get new data and have its timing info,
  49015. // as we use the start of the segment to offset the best guess (playlist provided)
  49016. // timestamp offset.
  49017. this.updateSourceBufferTimestampOffset_(segmentInfo); // if this is a sync request we need to determine whether it should
  49018. // be appended or not.
  49019. if (segmentInfo.isSyncRequest) {
  49020. // first save/update our timing info for this segment.
  49021. // this is what allows us to choose an accurate segment
  49022. // and the main reason we make a sync request.
  49023. this.updateTimingInfoEnd_(segmentInfo);
  49024. this.syncController_.saveSegmentTimingInfo({
  49025. segmentInfo: segmentInfo,
  49026. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  49027. });
  49028. var next = this.chooseNextRequest_(); // If the sync request isn't the segment that would be requested next
  49029. // after taking into account its timing info, do not append it.
  49030. if (next.mediaIndex !== segmentInfo.mediaIndex || next.partIndex !== segmentInfo.partIndex) {
  49031. this.logger_('sync segment was incorrect, not appending');
  49032. return;
  49033. } // otherwise append it like any other segment as our guess was correct.
  49034. this.logger_('sync segment was correct, appending');
  49035. } // Save some state so that in the future anything waiting on first append (and/or
  49036. // timestamp offset(s)) can process immediately. While the extra state isn't optimal,
  49037. // we need some notion of whether the timestamp offset or other relevant information
  49038. // has had a chance to be set.
  49039. segmentInfo.hasAppendedData_ = true; // Now that the timestamp offset should be set, we can append any waiting ID3 tags.
  49040. this.processMetadataQueue_();
  49041. this.appendData_(segmentInfo, result);
  49042. };
  49043. _proto.updateAppendInitSegmentStatus = function updateAppendInitSegmentStatus(segmentInfo, type) {
  49044. // alt audio doesn't manage timestamp offset
  49045. if (this.loaderType_ === 'main' && typeof segmentInfo.timestampOffset === 'number' && // in the case that we're handling partial data, we don't want to append an init
  49046. // segment for each chunk
  49047. !segmentInfo.changedTimestampOffset) {
  49048. // if the timestamp offset changed, the timeline may have changed, so we have to re-
  49049. // append init segments
  49050. this.appendInitSegment_ = {
  49051. audio: true,
  49052. video: true
  49053. };
  49054. }
  49055. if (this.playlistOfLastInitSegment_[type] !== segmentInfo.playlist) {
  49056. // make sure we append init segment on playlist changes, in case the media config
  49057. // changed
  49058. this.appendInitSegment_[type] = true;
  49059. }
  49060. };
  49061. _proto.getInitSegmentAndUpdateState_ = function getInitSegmentAndUpdateState_(_ref4) {
  49062. var type = _ref4.type,
  49063. initSegment = _ref4.initSegment,
  49064. map = _ref4.map,
  49065. playlist = _ref4.playlist; // "The EXT-X-MAP tag specifies how to obtain the Media Initialization Section
  49066. // (Section 3) required to parse the applicable Media Segments. It applies to every
  49067. // Media Segment that appears after it in the Playlist until the next EXT-X-MAP tag
  49068. // or until the end of the playlist."
  49069. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.5
  49070. if (map) {
  49071. var id = initSegmentId(map);
  49072. if (this.activeInitSegmentId_ === id) {
  49073. // don't need to re-append the init segment if the ID matches
  49074. return null;
  49075. } // a map-specified init segment takes priority over any transmuxed (or otherwise
  49076. // obtained) init segment
  49077. //
  49078. // this also caches the init segment for later use
  49079. initSegment = this.initSegmentForMap(map, true).bytes;
  49080. this.activeInitSegmentId_ = id;
  49081. } // We used to always prepend init segments for video, however, that shouldn't be
  49082. // necessary. Instead, we should only append on changes, similar to what we've always
  49083. // done for audio. This is more important (though may not be that important) for
  49084. // frame-by-frame appending for LHLS, simply because of the increased quantity of
  49085. // appends.
  49086. if (initSegment && this.appendInitSegment_[type]) {
  49087. // Make sure we track the playlist that we last used for the init segment, so that
  49088. // we can re-append the init segment in the event that we get data from a new
  49089. // playlist. Discontinuities and track changes are handled in other sections.
  49090. this.playlistOfLastInitSegment_[type] = playlist; // Disable future init segment appends for this type. Until a change is necessary.
  49091. this.appendInitSegment_[type] = false; // we need to clear out the fmp4 active init segment id, since
  49092. // we are appending the muxer init segment
  49093. this.activeInitSegmentId_ = null;
  49094. return initSegment;
  49095. }
  49096. return null;
  49097. };
  49098. _proto.handleQuotaExceededError_ = function handleQuotaExceededError_(_ref5, error) {
  49099. var _this3 = this;
  49100. var segmentInfo = _ref5.segmentInfo,
  49101. type = _ref5.type,
  49102. bytes = _ref5.bytes;
  49103. var audioBuffered = this.sourceUpdater_.audioBuffered();
  49104. var videoBuffered = this.sourceUpdater_.videoBuffered(); // For now we're ignoring any notion of gaps in the buffer, but they, in theory,
  49105. // should be cleared out during the buffer removals. However, log in case it helps
  49106. // debug.
  49107. if (audioBuffered.length > 1) {
  49108. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: ' + timeRangesToArray(audioBuffered).join(', '));
  49109. }
  49110. if (videoBuffered.length > 1) {
  49111. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: ' + timeRangesToArray(videoBuffered).join(', '));
  49112. }
  49113. var audioBufferStart = audioBuffered.length ? audioBuffered.start(0) : 0;
  49114. var audioBufferEnd = audioBuffered.length ? audioBuffered.end(audioBuffered.length - 1) : 0;
  49115. var videoBufferStart = videoBuffered.length ? videoBuffered.start(0) : 0;
  49116. var videoBufferEnd = videoBuffered.length ? videoBuffered.end(videoBuffered.length - 1) : 0;
  49117. if (audioBufferEnd - audioBufferStart <= MIN_BACK_BUFFER && videoBufferEnd - videoBufferStart <= MIN_BACK_BUFFER) {
  49118. // Can't remove enough buffer to make room for new segment (or the browser doesn't
  49119. // allow for appends of segments this size). In the future, it may be possible to
  49120. // split up the segment and append in pieces, but for now, error out this playlist
  49121. // in an attempt to switch to a more manageable rendition.
  49122. this.logger_('On QUOTA_EXCEEDED_ERR, single segment too large to append to ' + 'buffer, triggering an error. ' + ("Appended byte length: " + bytes.byteLength + ", ") + ("audio buffer: " + timeRangesToArray(audioBuffered).join(', ') + ", ") + ("video buffer: " + timeRangesToArray(videoBuffered).join(', ') + ", "));
  49123. this.error({
  49124. message: 'Quota exceeded error with append of a single segment of content',
  49125. excludeUntil: Infinity
  49126. });
  49127. this.trigger('error');
  49128. return;
  49129. } // To try to resolve the quota exceeded error, clear back buffer and retry. This means
  49130. // that the segment-loader should block on future events until this one is handled, so
  49131. // that it doesn't keep moving onto further segments. Adding the call to the call
  49132. // queue will prevent further appends until waitingOnRemove_ and
  49133. // quotaExceededErrorRetryTimeout_ are cleared.
  49134. //
  49135. // Note that this will only block the current loader. In the case of demuxed content,
  49136. // the other load may keep filling as fast as possible. In practice, this should be
  49137. // OK, as it is a rare case when either audio has a high enough bitrate to fill up a
  49138. // source buffer, or video fills without enough room for audio to append (and without
  49139. // the availability of clearing out seconds of back buffer to make room for audio).
  49140. // But it might still be good to handle this case in the future as a TODO.
  49141. this.waitingOnRemove_ = true;
  49142. this.callQueue_.push(this.appendToSourceBuffer_.bind(this, {
  49143. segmentInfo: segmentInfo,
  49144. type: type,
  49145. bytes: bytes
  49146. }));
  49147. var currentTime = this.currentTime_(); // Try to remove as much audio and video as possible to make room for new content
  49148. // before retrying.
  49149. var timeToRemoveUntil = currentTime - MIN_BACK_BUFFER;
  49150. this.logger_("On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to " + timeToRemoveUntil);
  49151. this.remove(0, timeToRemoveUntil, function () {
  49152. _this3.logger_("On QUOTA_EXCEEDED_ERR, retrying append in " + MIN_BACK_BUFFER + "s");
  49153. _this3.waitingOnRemove_ = false; // wait the length of time alotted in the back buffer to prevent wasted
  49154. // attempts (since we can't clear less than the minimum)
  49155. _this3.quotaExceededErrorRetryTimeout_ = window.setTimeout(function () {
  49156. _this3.logger_('On QUOTA_EXCEEDED_ERR, re-processing call queue');
  49157. _this3.quotaExceededErrorRetryTimeout_ = null;
  49158. _this3.processCallQueue_();
  49159. }, MIN_BACK_BUFFER * 1000);
  49160. }, true);
  49161. };
  49162. _proto.handleAppendError_ = function handleAppendError_(_ref6, error) {
  49163. var segmentInfo = _ref6.segmentInfo,
  49164. type = _ref6.type,
  49165. bytes = _ref6.bytes; // if there's no error, nothing to do
  49166. if (!error) {
  49167. return;
  49168. }
  49169. if (error.code === QUOTA_EXCEEDED_ERR) {
  49170. this.handleQuotaExceededError_({
  49171. segmentInfo: segmentInfo,
  49172. type: type,
  49173. bytes: bytes
  49174. }); // A quota exceeded error should be recoverable with a future re-append, so no need
  49175. // to trigger an append error.
  49176. return;
  49177. }
  49178. this.logger_('Received non QUOTA_EXCEEDED_ERR on append', error);
  49179. this.error(type + " append of " + bytes.length + "b failed for segment " + ("#" + segmentInfo.mediaIndex + " in playlist " + segmentInfo.playlist.id)); // If an append errors, we often can't recover.
  49180. // (see https://w3c.github.io/media-source/#sourcebuffer-append-error).
  49181. //
  49182. // Trigger a special error so that it can be handled separately from normal,
  49183. // recoverable errors.
  49184. this.trigger('appenderror');
  49185. };
  49186. _proto.appendToSourceBuffer_ = function appendToSourceBuffer_(_ref7) {
  49187. var segmentInfo = _ref7.segmentInfo,
  49188. type = _ref7.type,
  49189. initSegment = _ref7.initSegment,
  49190. data = _ref7.data,
  49191. bytes = _ref7.bytes; // If this is a re-append, bytes were already created and don't need to be recreated
  49192. if (!bytes) {
  49193. var segments = [data];
  49194. var byteLength = data.byteLength;
  49195. if (initSegment) {
  49196. // if the media initialization segment is changing, append it before the content
  49197. // segment
  49198. segments.unshift(initSegment);
  49199. byteLength += initSegment.byteLength;
  49200. } // Technically we should be OK appending the init segment separately, however, we
  49201. // haven't yet tested that, and prepending is how we have always done things.
  49202. bytes = concatSegments({
  49203. bytes: byteLength,
  49204. segments: segments
  49205. });
  49206. }
  49207. this.sourceUpdater_.appendBuffer({
  49208. segmentInfo: segmentInfo,
  49209. type: type,
  49210. bytes: bytes
  49211. }, this.handleAppendError_.bind(this, {
  49212. segmentInfo: segmentInfo,
  49213. type: type,
  49214. bytes: bytes
  49215. }));
  49216. };
  49217. _proto.handleSegmentTimingInfo_ = function handleSegmentTimingInfo_(type, requestId, segmentTimingInfo) {
  49218. if (!this.pendingSegment_ || requestId !== this.pendingSegment_.requestId) {
  49219. return;
  49220. }
  49221. var segment = this.pendingSegment_.segment;
  49222. var timingInfoProperty = type + "TimingInfo";
  49223. if (!segment[timingInfoProperty]) {
  49224. segment[timingInfoProperty] = {};
  49225. }
  49226. segment[timingInfoProperty].transmuxerPrependedSeconds = segmentTimingInfo.prependedContentDuration || 0;
  49227. segment[timingInfoProperty].transmuxedPresentationStart = segmentTimingInfo.start.presentation;
  49228. segment[timingInfoProperty].transmuxedDecodeStart = segmentTimingInfo.start.decode;
  49229. segment[timingInfoProperty].transmuxedPresentationEnd = segmentTimingInfo.end.presentation;
  49230. segment[timingInfoProperty].transmuxedDecodeEnd = segmentTimingInfo.end.decode; // mainly used as a reference for debugging
  49231. segment[timingInfoProperty].baseMediaDecodeTime = segmentTimingInfo.baseMediaDecodeTime;
  49232. };
  49233. _proto.appendData_ = function appendData_(segmentInfo, result) {
  49234. var type = result.type,
  49235. data = result.data;
  49236. if (!data || !data.byteLength) {
  49237. return;
  49238. }
  49239. if (type === 'audio' && this.audioDisabled_) {
  49240. return;
  49241. }
  49242. var initSegment = this.getInitSegmentAndUpdateState_({
  49243. type: type,
  49244. initSegment: result.initSegment,
  49245. playlist: segmentInfo.playlist,
  49246. map: segmentInfo.isFmp4 ? segmentInfo.segment.map : null
  49247. });
  49248. this.appendToSourceBuffer_({
  49249. segmentInfo: segmentInfo,
  49250. type: type,
  49251. initSegment: initSegment,
  49252. data: data
  49253. });
  49254. }
  49255. /**
  49256. * load a specific segment from a request into the buffer
  49257. *
  49258. * @private
  49259. */
  49260. ;
  49261. _proto.loadSegment_ = function loadSegment_(segmentInfo) {
  49262. var _this4 = this;
  49263. this.state = 'WAITING';
  49264. this.pendingSegment_ = segmentInfo;
  49265. this.trimBackBuffer_(segmentInfo);
  49266. if (typeof segmentInfo.timestampOffset === 'number') {
  49267. if (this.transmuxer_) {
  49268. this.transmuxer_.postMessage({
  49269. action: 'clearAllMp4Captions'
  49270. });
  49271. }
  49272. }
  49273. if (!this.hasEnoughInfoToLoad_()) {
  49274. this.loadQueue_.push(function () {
  49275. // regenerate the audioAppendStart, timestampOffset, etc as they
  49276. // may have changed since this function was added to the queue.
  49277. var options = _extends_1({}, segmentInfo, {
  49278. forceTimestampOffset: true
  49279. });
  49280. _extends_1(segmentInfo, _this4.generateSegmentInfo_(options));
  49281. _this4.isPendingTimestampOffset_ = false;
  49282. _this4.updateTransmuxerAndRequestSegment_(segmentInfo);
  49283. });
  49284. return;
  49285. }
  49286. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  49287. };
  49288. _proto.updateTransmuxerAndRequestSegment_ = function updateTransmuxerAndRequestSegment_(segmentInfo) {
  49289. var _this5 = this; // We'll update the source buffer's timestamp offset once we have transmuxed data, but
  49290. // the transmuxer still needs to be updated before then.
  49291. //
  49292. // Even though keepOriginalTimestamps is set to true for the transmuxer, timestamp
  49293. // offset must be passed to the transmuxer for stream correcting adjustments.
  49294. if (this.shouldUpdateTransmuxerTimestampOffset_(segmentInfo.timestampOffset)) {
  49295. this.gopBuffer_.length = 0; // gopsToAlignWith was set before the GOP buffer was cleared
  49296. segmentInfo.gopsToAlignWith = [];
  49297. this.timeMapping_ = 0; // reset values in the transmuxer since a discontinuity should start fresh
  49298. this.transmuxer_.postMessage({
  49299. action: 'reset'
  49300. });
  49301. this.transmuxer_.postMessage({
  49302. action: 'setTimestampOffset',
  49303. timestampOffset: segmentInfo.timestampOffset
  49304. });
  49305. }
  49306. var simpleSegment = this.createSimplifiedSegmentObj_(segmentInfo);
  49307. var isEndOfStream = this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex);
  49308. var isWalkingForward = this.mediaIndex !== null;
  49309. var isDiscontinuity = segmentInfo.timeline !== this.currentTimeline_ && // currentTimeline starts at -1, so we shouldn't end the timeline switching to 0,
  49310. // the first timeline
  49311. segmentInfo.timeline > 0;
  49312. var isEndOfTimeline = isEndOfStream || isWalkingForward && isDiscontinuity;
  49313. this.logger_("Requesting " + segmentInfoString(segmentInfo)); // If there's an init segment associated with this segment, but it is not cached (identified by a lack of bytes),
  49314. // then this init segment has never been seen before and should be appended.
  49315. //
  49316. // At this point the content type (audio/video or both) is not yet known, but it should be safe to set
  49317. // both to true and leave the decision of whether to append the init segment to append time.
  49318. if (simpleSegment.map && !simpleSegment.map.bytes) {
  49319. this.logger_('going to request init segment.');
  49320. this.appendInitSegment_ = {
  49321. video: true,
  49322. audio: true
  49323. };
  49324. }
  49325. segmentInfo.abortRequests = mediaSegmentRequest({
  49326. xhr: this.vhs_.xhr,
  49327. xhrOptions: this.xhrOptions_,
  49328. decryptionWorker: this.decrypter_,
  49329. segment: simpleSegment,
  49330. abortFn: this.handleAbort_.bind(this, segmentInfo),
  49331. progressFn: this.handleProgress_.bind(this),
  49332. trackInfoFn: this.handleTrackInfo_.bind(this),
  49333. timingInfoFn: this.handleTimingInfo_.bind(this),
  49334. videoSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'video', segmentInfo.requestId),
  49335. audioSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'audio', segmentInfo.requestId),
  49336. captionsFn: this.handleCaptions_.bind(this),
  49337. isEndOfTimeline: isEndOfTimeline,
  49338. endedTimelineFn: function endedTimelineFn() {
  49339. _this5.logger_('received endedtimeline callback');
  49340. },
  49341. id3Fn: this.handleId3_.bind(this),
  49342. dataFn: this.handleData_.bind(this),
  49343. doneFn: this.segmentRequestFinished_.bind(this),
  49344. onTransmuxerLog: function onTransmuxerLog(_ref8) {
  49345. var message = _ref8.message,
  49346. level = _ref8.level,
  49347. stream = _ref8.stream;
  49348. _this5.logger_(segmentInfoString(segmentInfo) + " logged from transmuxer stream " + stream + " as a " + level + ": " + message);
  49349. }
  49350. });
  49351. }
  49352. /**
  49353. * trim the back buffer so that we don't have too much data
  49354. * in the source buffer
  49355. *
  49356. * @private
  49357. *
  49358. * @param {Object} segmentInfo - the current segment
  49359. */
  49360. ;
  49361. _proto.trimBackBuffer_ = function trimBackBuffer_(segmentInfo) {
  49362. var removeToTime = safeBackBufferTrimTime(this.seekable_(), this.currentTime_(), this.playlist_.targetDuration || 10); // Chrome has a hard limit of 150MB of
  49363. // buffer and a very conservative "garbage collector"
  49364. // We manually clear out the old buffer to ensure
  49365. // we don't trigger the QuotaExceeded error
  49366. // on the source buffer during subsequent appends
  49367. if (removeToTime > 0) {
  49368. this.remove(0, removeToTime);
  49369. }
  49370. }
  49371. /**
  49372. * created a simplified copy of the segment object with just the
  49373. * information necessary to perform the XHR and decryption
  49374. *
  49375. * @private
  49376. *
  49377. * @param {Object} segmentInfo - the current segment
  49378. * @return {Object} a simplified segment object copy
  49379. */
  49380. ;
  49381. _proto.createSimplifiedSegmentObj_ = function createSimplifiedSegmentObj_(segmentInfo) {
  49382. var segment = segmentInfo.segment;
  49383. var part = segmentInfo.part;
  49384. var simpleSegment = {
  49385. resolvedUri: part ? part.resolvedUri : segment.resolvedUri,
  49386. byterange: part ? part.byterange : segment.byterange,
  49387. requestId: segmentInfo.requestId,
  49388. transmuxer: segmentInfo.transmuxer,
  49389. audioAppendStart: segmentInfo.audioAppendStart,
  49390. gopsToAlignWith: segmentInfo.gopsToAlignWith,
  49391. part: segmentInfo.part
  49392. };
  49393. var previousSegment = segmentInfo.playlist.segments[segmentInfo.mediaIndex - 1];
  49394. if (previousSegment && previousSegment.timeline === segment.timeline) {
  49395. // The baseStartTime of a segment is used to handle rollover when probing the TS
  49396. // segment to retrieve timing information. Since the probe only looks at the media's
  49397. // times (e.g., PTS and DTS values of the segment), and doesn't consider the
  49398. // player's time (e.g., player.currentTime()), baseStartTime should reflect the
  49399. // media time as well. transmuxedDecodeEnd represents the end time of a segment, in
  49400. // seconds of media time, so should be used here. The previous segment is used since
  49401. // the end of the previous segment should represent the beginning of the current
  49402. // segment, so long as they are on the same timeline.
  49403. if (previousSegment.videoTimingInfo) {
  49404. simpleSegment.baseStartTime = previousSegment.videoTimingInfo.transmuxedDecodeEnd;
  49405. } else if (previousSegment.audioTimingInfo) {
  49406. simpleSegment.baseStartTime = previousSegment.audioTimingInfo.transmuxedDecodeEnd;
  49407. }
  49408. }
  49409. if (segment.key) {
  49410. // if the media sequence is greater than 2^32, the IV will be incorrect
  49411. // assuming 10s segments, that would be about 1300 years
  49412. var iv = segment.key.iv || new Uint32Array([0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence]);
  49413. simpleSegment.key = this.segmentKey(segment.key);
  49414. simpleSegment.key.iv = iv;
  49415. }
  49416. if (segment.map) {
  49417. simpleSegment.map = this.initSegmentForMap(segment.map);
  49418. }
  49419. return simpleSegment;
  49420. };
  49421. _proto.saveTransferStats_ = function saveTransferStats_(stats) {
  49422. // every request counts as a media request even if it has been aborted
  49423. // or canceled due to a timeout
  49424. this.mediaRequests += 1;
  49425. if (stats) {
  49426. this.mediaBytesTransferred += stats.bytesReceived;
  49427. this.mediaTransferDuration += stats.roundTripTime;
  49428. }
  49429. };
  49430. _proto.saveBandwidthRelatedStats_ = function saveBandwidthRelatedStats_(duration, stats) {
  49431. // byteLength will be used for throughput, and should be based on bytes receieved,
  49432. // which we only know at the end of the request and should reflect total bytes
  49433. // downloaded rather than just bytes processed from components of the segment
  49434. this.pendingSegment_.byteLength = stats.bytesReceived;
  49435. if (duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  49436. this.logger_("Ignoring segment's bandwidth because its duration of " + duration + (" is less than the min to record " + MIN_SEGMENT_DURATION_TO_SAVE_STATS));
  49437. return;
  49438. }
  49439. this.bandwidth = stats.bandwidth;
  49440. this.roundTrip = stats.roundTripTime;
  49441. };
  49442. _proto.handleTimeout_ = function handleTimeout_() {
  49443. // although the VTT segment loader bandwidth isn't really used, it's good to
  49444. // maintain functinality between segment loaders
  49445. this.mediaRequestsTimedout += 1;
  49446. this.bandwidth = 1;
  49447. this.roundTrip = NaN;
  49448. this.trigger('bandwidthupdate');
  49449. this.trigger('timeout');
  49450. }
  49451. /**
  49452. * Handle the callback from the segmentRequest function and set the
  49453. * associated SegmentLoader state and errors if necessary
  49454. *
  49455. * @private
  49456. */
  49457. ;
  49458. _proto.segmentRequestFinished_ = function segmentRequestFinished_(error, simpleSegment, result) {
  49459. // TODO handle special cases, e.g., muxed audio/video but only audio in the segment
  49460. // check the call queue directly since this function doesn't need to deal with any
  49461. // data, and can continue even if the source buffers are not set up and we didn't get
  49462. // any data from the segment
  49463. if (this.callQueue_.length) {
  49464. this.callQueue_.push(this.segmentRequestFinished_.bind(this, error, simpleSegment, result));
  49465. return;
  49466. }
  49467. this.saveTransferStats_(simpleSegment.stats); // The request was aborted and the SegmentLoader has already been reset
  49468. if (!this.pendingSegment_) {
  49469. return;
  49470. } // the request was aborted and the SegmentLoader has already started
  49471. // another request. this can happen when the timeout for an aborted
  49472. // request triggers due to a limitation in the XHR library
  49473. // do not count this as any sort of request or we risk double-counting
  49474. if (simpleSegment.requestId !== this.pendingSegment_.requestId) {
  49475. return;
  49476. } // an error occurred from the active pendingSegment_ so reset everything
  49477. if (error) {
  49478. this.pendingSegment_ = null;
  49479. this.state = 'READY'; // aborts are not a true error condition and nothing corrective needs to be done
  49480. if (error.code === REQUEST_ERRORS.ABORTED) {
  49481. return;
  49482. }
  49483. this.pause(); // the error is really just that at least one of the requests timed-out
  49484. // set the bandwidth to a very low value and trigger an ABR switch to
  49485. // take emergency action
  49486. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  49487. this.handleTimeout_();
  49488. return;
  49489. } // if control-flow has arrived here, then the error is real
  49490. // emit an error event to blacklist the current playlist
  49491. this.mediaRequestsErrored += 1;
  49492. this.error(error);
  49493. this.trigger('error');
  49494. return;
  49495. }
  49496. var segmentInfo = this.pendingSegment_; // the response was a success so set any bandwidth stats the request
  49497. // generated for ABR purposes
  49498. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
  49499. segmentInfo.endOfAllRequests = simpleSegment.endOfAllRequests;
  49500. if (result.gopInfo) {
  49501. this.gopBuffer_ = updateGopBuffer(this.gopBuffer_, result.gopInfo, this.safeAppend_);
  49502. } // Although we may have already started appending on progress, we shouldn't switch the
  49503. // state away from loading until we are officially done loading the segment data.
  49504. this.state = 'APPENDING'; // used for testing
  49505. this.trigger('appending');
  49506. this.waitForAppendsToComplete_(segmentInfo);
  49507. };
  49508. _proto.setTimeMapping_ = function setTimeMapping_(timeline) {
  49509. var timelineMapping = this.syncController_.mappingForTimeline(timeline);
  49510. if (timelineMapping !== null) {
  49511. this.timeMapping_ = timelineMapping;
  49512. }
  49513. };
  49514. _proto.updateMediaSecondsLoaded_ = function updateMediaSecondsLoaded_(segment) {
  49515. if (typeof segment.start === 'number' && typeof segment.end === 'number') {
  49516. this.mediaSecondsLoaded += segment.end - segment.start;
  49517. } else {
  49518. this.mediaSecondsLoaded += segment.duration;
  49519. }
  49520. };
  49521. _proto.shouldUpdateTransmuxerTimestampOffset_ = function shouldUpdateTransmuxerTimestampOffset_(timestampOffset) {
  49522. if (timestampOffset === null) {
  49523. return false;
  49524. } // note that we're potentially using the same timestamp offset for both video and
  49525. // audio
  49526. if (this.loaderType_ === 'main' && timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  49527. return true;
  49528. }
  49529. if (!this.audioDisabled_ && timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  49530. return true;
  49531. }
  49532. return false;
  49533. };
  49534. _proto.trueSegmentStart_ = function trueSegmentStart_(_ref9) {
  49535. var currentStart = _ref9.currentStart,
  49536. playlist = _ref9.playlist,
  49537. mediaIndex = _ref9.mediaIndex,
  49538. firstVideoFrameTimeForData = _ref9.firstVideoFrameTimeForData,
  49539. currentVideoTimestampOffset = _ref9.currentVideoTimestampOffset,
  49540. useVideoTimingInfo = _ref9.useVideoTimingInfo,
  49541. videoTimingInfo = _ref9.videoTimingInfo,
  49542. audioTimingInfo = _ref9.audioTimingInfo;
  49543. if (typeof currentStart !== 'undefined') {
  49544. // if start was set once, keep using it
  49545. return currentStart;
  49546. }
  49547. if (!useVideoTimingInfo) {
  49548. return audioTimingInfo.start;
  49549. }
  49550. var previousSegment = playlist.segments[mediaIndex - 1]; // The start of a segment should be the start of the first full frame contained
  49551. // within that segment. Since the transmuxer maintains a cache of incomplete data
  49552. // from and/or the last frame seen, the start time may reflect a frame that starts
  49553. // in the previous segment. Check for that case and ensure the start time is
  49554. // accurate for the segment.
  49555. if (mediaIndex === 0 || !previousSegment || typeof previousSegment.start === 'undefined' || previousSegment.end !== firstVideoFrameTimeForData + currentVideoTimestampOffset) {
  49556. return firstVideoFrameTimeForData;
  49557. }
  49558. return videoTimingInfo.start;
  49559. };
  49560. _proto.waitForAppendsToComplete_ = function waitForAppendsToComplete_(segmentInfo) {
  49561. var trackInfo = this.getCurrentMediaInfo_(segmentInfo);
  49562. if (!trackInfo) {
  49563. this.error({
  49564. message: 'No starting media returned, likely due to an unsupported media format.',
  49565. blacklistDuration: Infinity
  49566. });
  49567. this.trigger('error');
  49568. return;
  49569. } // Although transmuxing is done, appends may not yet be finished. Throw a marker
  49570. // on each queue this loader is responsible for to ensure that the appends are
  49571. // complete.
  49572. var hasAudio = trackInfo.hasAudio,
  49573. hasVideo = trackInfo.hasVideo,
  49574. isMuxed = trackInfo.isMuxed;
  49575. var waitForVideo = this.loaderType_ === 'main' && hasVideo;
  49576. var waitForAudio = !this.audioDisabled_ && hasAudio && !isMuxed;
  49577. segmentInfo.waitingOnAppends = 0; // segments with no data
  49578. if (!segmentInfo.hasAppendedData_) {
  49579. if (!segmentInfo.timingInfo && typeof segmentInfo.timestampOffset === 'number') {
  49580. // When there's no audio or video data in the segment, there's no audio or video
  49581. // timing information.
  49582. //
  49583. // If there's no audio or video timing information, then the timestamp offset
  49584. // can't be adjusted to the appropriate value for the transmuxer and source
  49585. // buffers.
  49586. //
  49587. // Therefore, the next segment should be used to set the timestamp offset.
  49588. this.isPendingTimestampOffset_ = true;
  49589. } // override settings for metadata only segments
  49590. segmentInfo.timingInfo = {
  49591. start: 0
  49592. };
  49593. segmentInfo.waitingOnAppends++;
  49594. if (!this.isPendingTimestampOffset_) {
  49595. // update the timestampoffset
  49596. this.updateSourceBufferTimestampOffset_(segmentInfo); // make sure the metadata queue is processed even though we have
  49597. // no video/audio data.
  49598. this.processMetadataQueue_();
  49599. } // append is "done" instantly with no data.
  49600. this.checkAppendsDone_(segmentInfo);
  49601. return;
  49602. } // Since source updater could call back synchronously, do the increments first.
  49603. if (waitForVideo) {
  49604. segmentInfo.waitingOnAppends++;
  49605. }
  49606. if (waitForAudio) {
  49607. segmentInfo.waitingOnAppends++;
  49608. }
  49609. if (waitForVideo) {
  49610. this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  49611. }
  49612. if (waitForAudio) {
  49613. this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  49614. }
  49615. };
  49616. _proto.checkAppendsDone_ = function checkAppendsDone_(segmentInfo) {
  49617. if (this.checkForAbort_(segmentInfo.requestId)) {
  49618. return;
  49619. }
  49620. segmentInfo.waitingOnAppends--;
  49621. if (segmentInfo.waitingOnAppends === 0) {
  49622. this.handleAppendsDone_();
  49623. }
  49624. };
  49625. _proto.checkForIllegalMediaSwitch = function checkForIllegalMediaSwitch(trackInfo) {
  49626. var illegalMediaSwitchError = illegalMediaSwitch(this.loaderType_, this.getCurrentMediaInfo_(), trackInfo);
  49627. if (illegalMediaSwitchError) {
  49628. this.error({
  49629. message: illegalMediaSwitchError,
  49630. blacklistDuration: Infinity
  49631. });
  49632. this.trigger('error');
  49633. return true;
  49634. }
  49635. return false;
  49636. };
  49637. _proto.updateSourceBufferTimestampOffset_ = function updateSourceBufferTimestampOffset_(segmentInfo) {
  49638. if (segmentInfo.timestampOffset === null || // we don't yet have the start for whatever media type (video or audio) has
  49639. // priority, timing-wise, so we must wait
  49640. typeof segmentInfo.timingInfo.start !== 'number' || // already updated the timestamp offset for this segment
  49641. segmentInfo.changedTimestampOffset || // the alt audio loader should not be responsible for setting the timestamp offset
  49642. this.loaderType_ !== 'main') {
  49643. return;
  49644. }
  49645. var didChange = false; // Primary timing goes by video, and audio is trimmed in the transmuxer, meaning that
  49646. // the timing info here comes from video. In the event that the audio is longer than
  49647. // the video, this will trim the start of the audio.
  49648. // This also trims any offset from 0 at the beginning of the media
  49649. segmentInfo.timestampOffset -= this.getSegmentStartTimeForTimestampOffsetCalculation_({
  49650. videoTimingInfo: segmentInfo.segment.videoTimingInfo,
  49651. audioTimingInfo: segmentInfo.segment.audioTimingInfo,
  49652. timingInfo: segmentInfo.timingInfo
  49653. }); // In the event that there are part segment downloads, each will try to update the
  49654. // timestamp offset. Retaining this bit of state prevents us from updating in the
  49655. // future (within the same segment), however, there may be a better way to handle it.
  49656. segmentInfo.changedTimestampOffset = true;
  49657. if (segmentInfo.timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  49658. this.sourceUpdater_.videoTimestampOffset(segmentInfo.timestampOffset);
  49659. didChange = true;
  49660. }
  49661. if (segmentInfo.timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  49662. this.sourceUpdater_.audioTimestampOffset(segmentInfo.timestampOffset);
  49663. didChange = true;
  49664. }
  49665. if (didChange) {
  49666. this.trigger('timestampoffset');
  49667. }
  49668. };
  49669. _proto.getSegmentStartTimeForTimestampOffsetCalculation_ = function getSegmentStartTimeForTimestampOffsetCalculation_(_ref10) {
  49670. var videoTimingInfo = _ref10.videoTimingInfo,
  49671. audioTimingInfo = _ref10.audioTimingInfo,
  49672. timingInfo = _ref10.timingInfo;
  49673. if (!this.useDtsForTimestampOffset_) {
  49674. return timingInfo.start;
  49675. }
  49676. if (videoTimingInfo && typeof videoTimingInfo.transmuxedDecodeStart === 'number') {
  49677. return videoTimingInfo.transmuxedDecodeStart;
  49678. } // handle audio only
  49679. if (audioTimingInfo && typeof audioTimingInfo.transmuxedDecodeStart === 'number') {
  49680. return audioTimingInfo.transmuxedDecodeStart;
  49681. } // handle content not transmuxed (e.g., MP4)
  49682. return timingInfo.start;
  49683. };
  49684. _proto.updateTimingInfoEnd_ = function updateTimingInfoEnd_(segmentInfo) {
  49685. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  49686. var trackInfo = this.getMediaInfo_();
  49687. var useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  49688. var prioritizedTimingInfo = useVideoTimingInfo && segmentInfo.videoTimingInfo ? segmentInfo.videoTimingInfo : segmentInfo.audioTimingInfo;
  49689. if (!prioritizedTimingInfo) {
  49690. return;
  49691. }
  49692. segmentInfo.timingInfo.end = typeof prioritizedTimingInfo.end === 'number' ? // End time may not exist in a case where we aren't parsing the full segment (one
  49693. // current example is the case of fmp4), so use the rough duration to calculate an
  49694. // end time.
  49695. prioritizedTimingInfo.end : prioritizedTimingInfo.start + segmentInfo.duration;
  49696. }
  49697. /**
  49698. * callback to run when appendBuffer is finished. detects if we are
  49699. * in a good state to do things with the data we got, or if we need
  49700. * to wait for more
  49701. *
  49702. * @private
  49703. */
  49704. ;
  49705. _proto.handleAppendsDone_ = function handleAppendsDone_() {
  49706. // appendsdone can cause an abort
  49707. if (this.pendingSegment_) {
  49708. this.trigger('appendsdone');
  49709. }
  49710. if (!this.pendingSegment_) {
  49711. this.state = 'READY'; // TODO should this move into this.checkForAbort to speed up requests post abort in
  49712. // all appending cases?
  49713. if (!this.paused()) {
  49714. this.monitorBuffer_();
  49715. }
  49716. return;
  49717. }
  49718. var segmentInfo = this.pendingSegment_; // Now that the end of the segment has been reached, we can set the end time. It's
  49719. // best to wait until all appends are done so we're sure that the primary media is
  49720. // finished (and we have its end time).
  49721. this.updateTimingInfoEnd_(segmentInfo);
  49722. if (this.shouldSaveSegmentTimingInfo_) {
  49723. // Timeline mappings should only be saved for the main loader. This is for multiple
  49724. // reasons:
  49725. //
  49726. // 1) Only one mapping is saved per timeline, meaning that if both the audio loader
  49727. // and the main loader try to save the timeline mapping, whichever comes later
  49728. // will overwrite the first. In theory this is OK, as the mappings should be the
  49729. // same, however, it breaks for (2)
  49730. // 2) In the event of a live stream, the initial live point will make for a somewhat
  49731. // arbitrary mapping. If audio and video streams are not perfectly in-sync, then
  49732. // the mapping will be off for one of the streams, dependent on which one was
  49733. // first saved (see (1)).
  49734. // 3) Primary timing goes by video in VHS, so the mapping should be video.
  49735. //
  49736. // Since the audio loader will wait for the main loader to load the first segment,
  49737. // the main loader will save the first timeline mapping, and ensure that there won't
  49738. // be a case where audio loads two segments without saving a mapping (thus leading
  49739. // to missing segment timing info).
  49740. this.syncController_.saveSegmentTimingInfo({
  49741. segmentInfo: segmentInfo,
  49742. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  49743. });
  49744. }
  49745. var segmentDurationMessage = getTroublesomeSegmentDurationMessage(segmentInfo, this.sourceType_);
  49746. if (segmentDurationMessage) {
  49747. if (segmentDurationMessage.severity === 'warn') {
  49748. videojs.log.warn(segmentDurationMessage.message);
  49749. } else {
  49750. this.logger_(segmentDurationMessage.message);
  49751. }
  49752. }
  49753. this.recordThroughput_(segmentInfo);
  49754. this.pendingSegment_ = null;
  49755. this.state = 'READY';
  49756. if (segmentInfo.isSyncRequest) {
  49757. this.trigger('syncinfoupdate'); // if the sync request was not appended
  49758. // then it was not the correct segment.
  49759. // throw it away and use the data it gave us
  49760. // to get the correct one.
  49761. if (!segmentInfo.hasAppendedData_) {
  49762. this.logger_("Throwing away un-appended sync request " + segmentInfoString(segmentInfo));
  49763. return;
  49764. }
  49765. }
  49766. this.logger_("Appended " + segmentInfoString(segmentInfo));
  49767. this.addSegmentMetadataCue_(segmentInfo);
  49768. this.fetchAtBuffer_ = true;
  49769. if (this.currentTimeline_ !== segmentInfo.timeline) {
  49770. this.timelineChangeController_.lastTimelineChange({
  49771. type: this.loaderType_,
  49772. from: this.currentTimeline_,
  49773. to: segmentInfo.timeline
  49774. }); // If audio is not disabled, the main segment loader is responsible for updating
  49775. // the audio timeline as well. If the content is video only, this won't have any
  49776. // impact.
  49777. if (this.loaderType_ === 'main' && !this.audioDisabled_) {
  49778. this.timelineChangeController_.lastTimelineChange({
  49779. type: 'audio',
  49780. from: this.currentTimeline_,
  49781. to: segmentInfo.timeline
  49782. });
  49783. }
  49784. }
  49785. this.currentTimeline_ = segmentInfo.timeline; // We must update the syncinfo to recalculate the seekable range before
  49786. // the following conditional otherwise it may consider this a bad "guess"
  49787. // and attempt to resync when the post-update seekable window and live
  49788. // point would mean that this was the perfect segment to fetch
  49789. this.trigger('syncinfoupdate');
  49790. var segment = segmentInfo.segment;
  49791. var part = segmentInfo.part;
  49792. var badSegmentGuess = segment.end && this.currentTime_() - segment.end > segmentInfo.playlist.targetDuration * 3;
  49793. var badPartGuess = part && part.end && this.currentTime_() - part.end > segmentInfo.playlist.partTargetDuration * 3; // If we previously appended a segment/part that ends more than 3 part/targetDurations before
  49794. // the currentTime_ that means that our conservative guess was too conservative.
  49795. // In that case, reset the loader state so that we try to use any information gained
  49796. // from the previous request to create a new, more accurate, sync-point.
  49797. if (badSegmentGuess || badPartGuess) {
  49798. this.logger_("bad " + (badSegmentGuess ? 'segment' : 'part') + " " + segmentInfoString(segmentInfo));
  49799. this.resetEverything();
  49800. return;
  49801. }
  49802. var isWalkingForward = this.mediaIndex !== null; // Don't do a rendition switch unless we have enough time to get a sync segment
  49803. // and conservatively guess
  49804. if (isWalkingForward) {
  49805. this.trigger('bandwidthupdate');
  49806. }
  49807. this.trigger('progress');
  49808. this.mediaIndex = segmentInfo.mediaIndex;
  49809. this.partIndex = segmentInfo.partIndex; // any time an update finishes and the last segment is in the
  49810. // buffer, end the stream. this ensures the "ended" event will
  49811. // fire if playback reaches that point.
  49812. if (this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex)) {
  49813. this.endOfStream();
  49814. } // used for testing
  49815. this.trigger('appended');
  49816. if (segmentInfo.hasAppendedData_) {
  49817. this.mediaAppends++;
  49818. }
  49819. if (!this.paused()) {
  49820. this.monitorBuffer_();
  49821. }
  49822. }
  49823. /**
  49824. * Records the current throughput of the decrypt, transmux, and append
  49825. * portion of the semgment pipeline. `throughput.rate` is a the cumulative
  49826. * moving average of the throughput. `throughput.count` is the number of
  49827. * data points in the average.
  49828. *
  49829. * @private
  49830. * @param {Object} segmentInfo the object returned by loadSegment
  49831. */
  49832. ;
  49833. _proto.recordThroughput_ = function recordThroughput_(segmentInfo) {
  49834. if (segmentInfo.duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  49835. this.logger_("Ignoring segment's throughput because its duration of " + segmentInfo.duration + (" is less than the min to record " + MIN_SEGMENT_DURATION_TO_SAVE_STATS));
  49836. return;
  49837. }
  49838. var rate = this.throughput.rate; // Add one to the time to ensure that we don't accidentally attempt to divide
  49839. // by zero in the case where the throughput is ridiculously high
  49840. var segmentProcessingTime = Date.now() - segmentInfo.endOfAllRequests + 1; // Multiply by 8000 to convert from bytes/millisecond to bits/second
  49841. var segmentProcessingThroughput = Math.floor(segmentInfo.byteLength / segmentProcessingTime * 8 * 1000); // This is just a cumulative moving average calculation:
  49842. // newAvg = oldAvg + (sample - oldAvg) / (sampleCount + 1)
  49843. this.throughput.rate += (segmentProcessingThroughput - rate) / ++this.throughput.count;
  49844. }
  49845. /**
  49846. * Adds a cue to the segment-metadata track with some metadata information about the
  49847. * segment
  49848. *
  49849. * @private
  49850. * @param {Object} segmentInfo
  49851. * the object returned by loadSegment
  49852. * @method addSegmentMetadataCue_
  49853. */
  49854. ;
  49855. _proto.addSegmentMetadataCue_ = function addSegmentMetadataCue_(segmentInfo) {
  49856. if (!this.segmentMetadataTrack_) {
  49857. return;
  49858. }
  49859. var segment = segmentInfo.segment;
  49860. var start = segment.start;
  49861. var end = segment.end; // Do not try adding the cue if the start and end times are invalid.
  49862. if (!finite(start) || !finite(end)) {
  49863. return;
  49864. }
  49865. removeCuesFromTrack(start, end, this.segmentMetadataTrack_);
  49866. var Cue = window.WebKitDataCue || window.VTTCue;
  49867. var value = {
  49868. custom: segment.custom,
  49869. dateTimeObject: segment.dateTimeObject,
  49870. dateTimeString: segment.dateTimeString,
  49871. bandwidth: segmentInfo.playlist.attributes.BANDWIDTH,
  49872. resolution: segmentInfo.playlist.attributes.RESOLUTION,
  49873. codecs: segmentInfo.playlist.attributes.CODECS,
  49874. byteLength: segmentInfo.byteLength,
  49875. uri: segmentInfo.uri,
  49876. timeline: segmentInfo.timeline,
  49877. playlist: segmentInfo.playlist.id,
  49878. start: start,
  49879. end: end
  49880. };
  49881. var data = JSON.stringify(value);
  49882. var cue = new Cue(start, end, data); // Attach the metadata to the value property of the cue to keep consistency between
  49883. // the differences of WebKitDataCue in safari and VTTCue in other browsers
  49884. cue.value = value;
  49885. this.segmentMetadataTrack_.addCue(cue);
  49886. };
  49887. return SegmentLoader;
  49888. }(videojs.EventTarget);
  49889. function noop() {}
  49890. var toTitleCase = function toTitleCase(string) {
  49891. if (typeof string !== 'string') {
  49892. return string;
  49893. }
  49894. return string.replace(/./, function (w) {
  49895. return w.toUpperCase();
  49896. });
  49897. };
  49898. var bufferTypes = ['video', 'audio'];
  49899. var _updating = function updating(type, sourceUpdater) {
  49900. var sourceBuffer = sourceUpdater[type + "Buffer"];
  49901. return sourceBuffer && sourceBuffer.updating || sourceUpdater.queuePending[type];
  49902. };
  49903. var nextQueueIndexOfType = function nextQueueIndexOfType(type, queue) {
  49904. for (var i = 0; i < queue.length; i++) {
  49905. var queueEntry = queue[i];
  49906. if (queueEntry.type === 'mediaSource') {
  49907. // If the next entry is a media source entry (uses multiple source buffers), block
  49908. // processing to allow it to go through first.
  49909. return null;
  49910. }
  49911. if (queueEntry.type === type) {
  49912. return i;
  49913. }
  49914. }
  49915. return null;
  49916. };
  49917. var shiftQueue = function shiftQueue(type, sourceUpdater) {
  49918. if (sourceUpdater.queue.length === 0) {
  49919. return;
  49920. }
  49921. var queueIndex = 0;
  49922. var queueEntry = sourceUpdater.queue[queueIndex];
  49923. if (queueEntry.type === 'mediaSource') {
  49924. if (!sourceUpdater.updating() && sourceUpdater.mediaSource.readyState !== 'closed') {
  49925. sourceUpdater.queue.shift();
  49926. queueEntry.action(sourceUpdater);
  49927. if (queueEntry.doneFn) {
  49928. queueEntry.doneFn();
  49929. } // Only specific source buffer actions must wait for async updateend events. Media
  49930. // Source actions process synchronously. Therefore, both audio and video source
  49931. // buffers are now clear to process the next queue entries.
  49932. shiftQueue('audio', sourceUpdater);
  49933. shiftQueue('video', sourceUpdater);
  49934. } // Media Source actions require both source buffers, so if the media source action
  49935. // couldn't process yet (because one or both source buffers are busy), block other
  49936. // queue actions until both are available and the media source action can process.
  49937. return;
  49938. }
  49939. if (type === 'mediaSource') {
  49940. // If the queue was shifted by a media source action (this happens when pushing a
  49941. // media source action onto the queue), then it wasn't from an updateend event from an
  49942. // audio or video source buffer, so there's no change from previous state, and no
  49943. // processing should be done.
  49944. return;
  49945. } // Media source queue entries don't need to consider whether the source updater is
  49946. // started (i.e., source buffers are created) as they don't need the source buffers, but
  49947. // source buffer queue entries do.
  49948. if (!sourceUpdater.ready() || sourceUpdater.mediaSource.readyState === 'closed' || _updating(type, sourceUpdater)) {
  49949. return;
  49950. }
  49951. if (queueEntry.type !== type) {
  49952. queueIndex = nextQueueIndexOfType(type, sourceUpdater.queue);
  49953. if (queueIndex === null) {
  49954. // Either there's no queue entry that uses this source buffer type in the queue, or
  49955. // there's a media source queue entry before the next entry of this type, in which
  49956. // case wait for that action to process first.
  49957. return;
  49958. }
  49959. queueEntry = sourceUpdater.queue[queueIndex];
  49960. }
  49961. sourceUpdater.queue.splice(queueIndex, 1); // Keep a record that this source buffer type is in use.
  49962. //
  49963. // The queue pending operation must be set before the action is performed in the event
  49964. // that the action results in a synchronous event that is acted upon. For instance, if
  49965. // an exception is thrown that can be handled, it's possible that new actions will be
  49966. // appended to an empty queue and immediately executed, but would not have the correct
  49967. // pending information if this property was set after the action was performed.
  49968. sourceUpdater.queuePending[type] = queueEntry;
  49969. queueEntry.action(type, sourceUpdater);
  49970. if (!queueEntry.doneFn) {
  49971. // synchronous operation, process next entry
  49972. sourceUpdater.queuePending[type] = null;
  49973. shiftQueue(type, sourceUpdater);
  49974. return;
  49975. }
  49976. };
  49977. var cleanupBuffer = function cleanupBuffer(type, sourceUpdater) {
  49978. var buffer = sourceUpdater[type + "Buffer"];
  49979. var titleType = toTitleCase(type);
  49980. if (!buffer) {
  49981. return;
  49982. }
  49983. buffer.removeEventListener('updateend', sourceUpdater["on" + titleType + "UpdateEnd_"]);
  49984. buffer.removeEventListener('error', sourceUpdater["on" + titleType + "Error_"]);
  49985. sourceUpdater.codecs[type] = null;
  49986. sourceUpdater[type + "Buffer"] = null;
  49987. };
  49988. var inSourceBuffers = function inSourceBuffers(mediaSource, sourceBuffer) {
  49989. return mediaSource && sourceBuffer && Array.prototype.indexOf.call(mediaSource.sourceBuffers, sourceBuffer) !== -1;
  49990. };
  49991. var actions = {
  49992. appendBuffer: function appendBuffer(bytes, segmentInfo, onError) {
  49993. return function (type, sourceUpdater) {
  49994. var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
  49995. // or the media source does not contain this source buffer.
  49996. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  49997. return;
  49998. }
  49999. sourceUpdater.logger_("Appending segment " + segmentInfo.mediaIndex + "'s " + bytes.length + " bytes to " + type + "Buffer");
  50000. try {
  50001. sourceBuffer.appendBuffer(bytes);
  50002. } catch (e) {
  50003. sourceUpdater.logger_("Error with code " + e.code + " " + (e.code === QUOTA_EXCEEDED_ERR ? '(QUOTA_EXCEEDED_ERR) ' : '') + ("when appending segment " + segmentInfo.mediaIndex + " to " + type + "Buffer"));
  50004. sourceUpdater.queuePending[type] = null;
  50005. onError(e);
  50006. }
  50007. };
  50008. },
  50009. remove: function remove(start, end) {
  50010. return function (type, sourceUpdater) {
  50011. var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
  50012. // or the media source does not contain this source buffer.
  50013. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  50014. return;
  50015. }
  50016. sourceUpdater.logger_("Removing " + start + " to " + end + " from " + type + "Buffer");
  50017. try {
  50018. sourceBuffer.remove(start, end);
  50019. } catch (e) {
  50020. sourceUpdater.logger_("Remove " + start + " to " + end + " from " + type + "Buffer failed");
  50021. }
  50022. };
  50023. },
  50024. timestampOffset: function timestampOffset(offset) {
  50025. return function (type, sourceUpdater) {
  50026. var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
  50027. // or the media source does not contain this source buffer.
  50028. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  50029. return;
  50030. }
  50031. sourceUpdater.logger_("Setting " + type + "timestampOffset to " + offset);
  50032. sourceBuffer.timestampOffset = offset;
  50033. };
  50034. },
  50035. callback: function callback(_callback) {
  50036. return function (type, sourceUpdater) {
  50037. _callback();
  50038. };
  50039. },
  50040. endOfStream: function endOfStream(error) {
  50041. return function (sourceUpdater) {
  50042. if (sourceUpdater.mediaSource.readyState !== 'open') {
  50043. return;
  50044. }
  50045. sourceUpdater.logger_("Calling mediaSource endOfStream(" + (error || '') + ")");
  50046. try {
  50047. sourceUpdater.mediaSource.endOfStream(error);
  50048. } catch (e) {
  50049. videojs.log.warn('Failed to call media source endOfStream', e);
  50050. }
  50051. };
  50052. },
  50053. duration: function duration(_duration) {
  50054. return function (sourceUpdater) {
  50055. sourceUpdater.logger_("Setting mediaSource duration to " + _duration);
  50056. try {
  50057. sourceUpdater.mediaSource.duration = _duration;
  50058. } catch (e) {
  50059. videojs.log.warn('Failed to set media source duration', e);
  50060. }
  50061. };
  50062. },
  50063. abort: function abort() {
  50064. return function (type, sourceUpdater) {
  50065. if (sourceUpdater.mediaSource.readyState !== 'open') {
  50066. return;
  50067. }
  50068. var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
  50069. // or the media source does not contain this source buffer.
  50070. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  50071. return;
  50072. }
  50073. sourceUpdater.logger_("calling abort on " + type + "Buffer");
  50074. try {
  50075. sourceBuffer.abort();
  50076. } catch (e) {
  50077. videojs.log.warn("Failed to abort on " + type + "Buffer", e);
  50078. }
  50079. };
  50080. },
  50081. addSourceBuffer: function addSourceBuffer(type, codec) {
  50082. return function (sourceUpdater) {
  50083. var titleType = toTitleCase(type);
  50084. var mime = getMimeForCodec(codec);
  50085. sourceUpdater.logger_("Adding " + type + "Buffer with codec " + codec + " to mediaSource");
  50086. var sourceBuffer = sourceUpdater.mediaSource.addSourceBuffer(mime);
  50087. sourceBuffer.addEventListener('updateend', sourceUpdater["on" + titleType + "UpdateEnd_"]);
  50088. sourceBuffer.addEventListener('error', sourceUpdater["on" + titleType + "Error_"]);
  50089. sourceUpdater.codecs[type] = codec;
  50090. sourceUpdater[type + "Buffer"] = sourceBuffer;
  50091. };
  50092. },
  50093. removeSourceBuffer: function removeSourceBuffer(type) {
  50094. return function (sourceUpdater) {
  50095. var sourceBuffer = sourceUpdater[type + "Buffer"];
  50096. cleanupBuffer(type, sourceUpdater); // can't do anything if the media source / source buffer is null
  50097. // or the media source does not contain this source buffer.
  50098. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  50099. return;
  50100. }
  50101. sourceUpdater.logger_("Removing " + type + "Buffer with codec " + sourceUpdater.codecs[type] + " from mediaSource");
  50102. try {
  50103. sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer);
  50104. } catch (e) {
  50105. videojs.log.warn("Failed to removeSourceBuffer " + type + "Buffer", e);
  50106. }
  50107. };
  50108. },
  50109. changeType: function changeType(codec) {
  50110. return function (type, sourceUpdater) {
  50111. var sourceBuffer = sourceUpdater[type + "Buffer"];
  50112. var mime = getMimeForCodec(codec); // can't do anything if the media source / source buffer is null
  50113. // or the media source does not contain this source buffer.
  50114. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  50115. return;
  50116. } // do not update codec if we don't need to.
  50117. if (sourceUpdater.codecs[type] === codec) {
  50118. return;
  50119. }
  50120. sourceUpdater.logger_("changing " + type + "Buffer codec from " + sourceUpdater.codecs[type] + " to " + codec);
  50121. sourceBuffer.changeType(mime);
  50122. sourceUpdater.codecs[type] = codec;
  50123. };
  50124. }
  50125. };
  50126. var pushQueue = function pushQueue(_ref) {
  50127. var type = _ref.type,
  50128. sourceUpdater = _ref.sourceUpdater,
  50129. action = _ref.action,
  50130. doneFn = _ref.doneFn,
  50131. name = _ref.name;
  50132. sourceUpdater.queue.push({
  50133. type: type,
  50134. action: action,
  50135. doneFn: doneFn,
  50136. name: name
  50137. });
  50138. shiftQueue(type, sourceUpdater);
  50139. };
  50140. var onUpdateend = function onUpdateend(type, sourceUpdater) {
  50141. return function (e) {
  50142. // Although there should, in theory, be a pending action for any updateend receieved,
  50143. // there are some actions that may trigger updateend events without set definitions in
  50144. // the w3c spec. For instance, setting the duration on the media source may trigger
  50145. // updateend events on source buffers. This does not appear to be in the spec. As such,
  50146. // if we encounter an updateend without a corresponding pending action from our queue
  50147. // for that source buffer type, process the next action.
  50148. if (sourceUpdater.queuePending[type]) {
  50149. var doneFn = sourceUpdater.queuePending[type].doneFn;
  50150. sourceUpdater.queuePending[type] = null;
  50151. if (doneFn) {
  50152. // if there's an error, report it
  50153. doneFn(sourceUpdater[type + "Error_"]);
  50154. }
  50155. }
  50156. shiftQueue(type, sourceUpdater);
  50157. };
  50158. };
  50159. /**
  50160. * A queue of callbacks to be serialized and applied when a
  50161. * MediaSource and its associated SourceBuffers are not in the
  50162. * updating state. It is used by the segment loader to update the
  50163. * underlying SourceBuffers when new data is loaded, for instance.
  50164. *
  50165. * @class SourceUpdater
  50166. * @param {MediaSource} mediaSource the MediaSource to create the SourceBuffer from
  50167. * @param {string} mimeType the desired MIME type of the underlying SourceBuffer
  50168. */
  50169. var SourceUpdater = /*#__PURE__*/function (_videojs$EventTarget) {
  50170. inheritsLoose(SourceUpdater, _videojs$EventTarget);
  50171. function SourceUpdater(mediaSource) {
  50172. var _this;
  50173. _this = _videojs$EventTarget.call(this) || this;
  50174. _this.mediaSource = mediaSource;
  50175. _this.sourceopenListener_ = function () {
  50176. return shiftQueue('mediaSource', assertThisInitialized(_this));
  50177. };
  50178. _this.mediaSource.addEventListener('sourceopen', _this.sourceopenListener_);
  50179. _this.logger_ = logger('SourceUpdater'); // initial timestamp offset is 0
  50180. _this.audioTimestampOffset_ = 0;
  50181. _this.videoTimestampOffset_ = 0;
  50182. _this.queue = [];
  50183. _this.queuePending = {
  50184. audio: null,
  50185. video: null
  50186. };
  50187. _this.delayedAudioAppendQueue_ = [];
  50188. _this.videoAppendQueued_ = false;
  50189. _this.codecs = {};
  50190. _this.onVideoUpdateEnd_ = onUpdateend('video', assertThisInitialized(_this));
  50191. _this.onAudioUpdateEnd_ = onUpdateend('audio', assertThisInitialized(_this));
  50192. _this.onVideoError_ = function (e) {
  50193. // used for debugging
  50194. _this.videoError_ = e;
  50195. };
  50196. _this.onAudioError_ = function (e) {
  50197. // used for debugging
  50198. _this.audioError_ = e;
  50199. };
  50200. _this.createdSourceBuffers_ = false;
  50201. _this.initializedEme_ = false;
  50202. _this.triggeredReady_ = false;
  50203. return _this;
  50204. }
  50205. var _proto = SourceUpdater.prototype;
  50206. _proto.initializedEme = function initializedEme() {
  50207. this.initializedEme_ = true;
  50208. this.triggerReady();
  50209. };
  50210. _proto.hasCreatedSourceBuffers = function hasCreatedSourceBuffers() {
  50211. // if false, likely waiting on one of the segment loaders to get enough data to create
  50212. // source buffers
  50213. return this.createdSourceBuffers_;
  50214. };
  50215. _proto.hasInitializedAnyEme = function hasInitializedAnyEme() {
  50216. return this.initializedEme_;
  50217. };
  50218. _proto.ready = function ready() {
  50219. return this.hasCreatedSourceBuffers() && this.hasInitializedAnyEme();
  50220. };
  50221. _proto.createSourceBuffers = function createSourceBuffers(codecs) {
  50222. if (this.hasCreatedSourceBuffers()) {
  50223. // already created them before
  50224. return;
  50225. } // the intial addOrChangeSourceBuffers will always be
  50226. // two add buffers.
  50227. this.addOrChangeSourceBuffers(codecs);
  50228. this.createdSourceBuffers_ = true;
  50229. this.trigger('createdsourcebuffers');
  50230. this.triggerReady();
  50231. };
  50232. _proto.triggerReady = function triggerReady() {
  50233. // only allow ready to be triggered once, this prevents the case
  50234. // where:
  50235. // 1. we trigger createdsourcebuffers
  50236. // 2. ie 11 synchronously initializates eme
  50237. // 3. the synchronous initialization causes us to trigger ready
  50238. // 4. We go back to the ready check in createSourceBuffers and ready is triggered again.
  50239. if (this.ready() && !this.triggeredReady_) {
  50240. this.triggeredReady_ = true;
  50241. this.trigger('ready');
  50242. }
  50243. }
  50244. /**
  50245. * Add a type of source buffer to the media source.
  50246. *
  50247. * @param {string} type
  50248. * The type of source buffer to add.
  50249. *
  50250. * @param {string} codec
  50251. * The codec to add the source buffer with.
  50252. */
  50253. ;
  50254. _proto.addSourceBuffer = function addSourceBuffer(type, codec) {
  50255. pushQueue({
  50256. type: 'mediaSource',
  50257. sourceUpdater: this,
  50258. action: actions.addSourceBuffer(type, codec),
  50259. name: 'addSourceBuffer'
  50260. });
  50261. }
  50262. /**
  50263. * call abort on a source buffer.
  50264. *
  50265. * @param {string} type
  50266. * The type of source buffer to call abort on.
  50267. */
  50268. ;
  50269. _proto.abort = function abort(type) {
  50270. pushQueue({
  50271. type: type,
  50272. sourceUpdater: this,
  50273. action: actions.abort(type),
  50274. name: 'abort'
  50275. });
  50276. }
  50277. /**
  50278. * Call removeSourceBuffer and remove a specific type
  50279. * of source buffer on the mediaSource.
  50280. *
  50281. * @param {string} type
  50282. * The type of source buffer to remove.
  50283. */
  50284. ;
  50285. _proto.removeSourceBuffer = function removeSourceBuffer(type) {
  50286. if (!this.canRemoveSourceBuffer()) {
  50287. videojs.log.error('removeSourceBuffer is not supported!');
  50288. return;
  50289. }
  50290. pushQueue({
  50291. type: 'mediaSource',
  50292. sourceUpdater: this,
  50293. action: actions.removeSourceBuffer(type),
  50294. name: 'removeSourceBuffer'
  50295. });
  50296. }
  50297. /**
  50298. * Whether or not the removeSourceBuffer function is supported
  50299. * on the mediaSource.
  50300. *
  50301. * @return {boolean}
  50302. * if removeSourceBuffer can be called.
  50303. */
  50304. ;
  50305. _proto.canRemoveSourceBuffer = function canRemoveSourceBuffer() {
  50306. // IE reports that it supports removeSourceBuffer, but often throws
  50307. // errors when attempting to use the function. So we report that it
  50308. // does not support removeSourceBuffer. As of Firefox 83 removeSourceBuffer
  50309. // throws errors, so we report that it does not support this as well.
  50310. return !videojs.browser.IE_VERSION && !videojs.browser.IS_FIREFOX && window.MediaSource && window.MediaSource.prototype && typeof window.MediaSource.prototype.removeSourceBuffer === 'function';
  50311. }
  50312. /**
  50313. * Whether or not the changeType function is supported
  50314. * on our SourceBuffers.
  50315. *
  50316. * @return {boolean}
  50317. * if changeType can be called.
  50318. */
  50319. ;
  50320. SourceUpdater.canChangeType = function canChangeType() {
  50321. return window.SourceBuffer && window.SourceBuffer.prototype && typeof window.SourceBuffer.prototype.changeType === 'function';
  50322. }
  50323. /**
  50324. * Whether or not the changeType function is supported
  50325. * on our SourceBuffers.
  50326. *
  50327. * @return {boolean}
  50328. * if changeType can be called.
  50329. */
  50330. ;
  50331. _proto.canChangeType = function canChangeType() {
  50332. return this.constructor.canChangeType();
  50333. }
  50334. /**
  50335. * Call the changeType function on a source buffer, given the code and type.
  50336. *
  50337. * @param {string} type
  50338. * The type of source buffer to call changeType on.
  50339. *
  50340. * @param {string} codec
  50341. * The codec string to change type with on the source buffer.
  50342. */
  50343. ;
  50344. _proto.changeType = function changeType(type, codec) {
  50345. if (!this.canChangeType()) {
  50346. videojs.log.error('changeType is not supported!');
  50347. return;
  50348. }
  50349. pushQueue({
  50350. type: type,
  50351. sourceUpdater: this,
  50352. action: actions.changeType(codec),
  50353. name: 'changeType'
  50354. });
  50355. }
  50356. /**
  50357. * Add source buffers with a codec or, if they are already created,
  50358. * call changeType on source buffers using changeType.
  50359. *
  50360. * @param {Object} codecs
  50361. * Codecs to switch to
  50362. */
  50363. ;
  50364. _proto.addOrChangeSourceBuffers = function addOrChangeSourceBuffers(codecs) {
  50365. var _this2 = this;
  50366. if (!codecs || typeof codecs !== 'object' || Object.keys(codecs).length === 0) {
  50367. throw new Error('Cannot addOrChangeSourceBuffers to undefined codecs');
  50368. }
  50369. Object.keys(codecs).forEach(function (type) {
  50370. var codec = codecs[type];
  50371. if (!_this2.hasCreatedSourceBuffers()) {
  50372. return _this2.addSourceBuffer(type, codec);
  50373. }
  50374. if (_this2.canChangeType()) {
  50375. _this2.changeType(type, codec);
  50376. }
  50377. });
  50378. }
  50379. /**
  50380. * Queue an update to append an ArrayBuffer.
  50381. *
  50382. * @param {MediaObject} object containing audioBytes and/or videoBytes
  50383. * @param {Function} done the function to call when done
  50384. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data
  50385. */
  50386. ;
  50387. _proto.appendBuffer = function appendBuffer(options, doneFn) {
  50388. var _this3 = this;
  50389. var segmentInfo = options.segmentInfo,
  50390. type = options.type,
  50391. bytes = options.bytes;
  50392. this.processedAppend_ = true;
  50393. if (type === 'audio' && this.videoBuffer && !this.videoAppendQueued_) {
  50394. this.delayedAudioAppendQueue_.push([options, doneFn]);
  50395. this.logger_("delayed audio append of " + bytes.length + " until video append");
  50396. return;
  50397. } // In the case of certain errors, for instance, QUOTA_EXCEEDED_ERR, updateend will
  50398. // not be fired. This means that the queue will be blocked until the next action
  50399. // taken by the segment-loader. Provide a mechanism for segment-loader to handle
  50400. // these errors by calling the doneFn with the specific error.
  50401. var onError = doneFn;
  50402. pushQueue({
  50403. type: type,
  50404. sourceUpdater: this,
  50405. action: actions.appendBuffer(bytes, segmentInfo || {
  50406. mediaIndex: -1
  50407. }, onError),
  50408. doneFn: doneFn,
  50409. name: 'appendBuffer'
  50410. });
  50411. if (type === 'video') {
  50412. this.videoAppendQueued_ = true;
  50413. if (!this.delayedAudioAppendQueue_.length) {
  50414. return;
  50415. }
  50416. var queue = this.delayedAudioAppendQueue_.slice();
  50417. this.logger_("queuing delayed audio " + queue.length + " appendBuffers");
  50418. this.delayedAudioAppendQueue_.length = 0;
  50419. queue.forEach(function (que) {
  50420. _this3.appendBuffer.apply(_this3, que);
  50421. });
  50422. }
  50423. }
  50424. /**
  50425. * Get the audio buffer's buffered timerange.
  50426. *
  50427. * @return {TimeRange}
  50428. * The audio buffer's buffered time range
  50429. */
  50430. ;
  50431. _proto.audioBuffered = function audioBuffered() {
  50432. // no media source/source buffer or it isn't in the media sources
  50433. // source buffer list
  50434. if (!inSourceBuffers(this.mediaSource, this.audioBuffer)) {
  50435. return videojs.createTimeRange();
  50436. }
  50437. return this.audioBuffer.buffered ? this.audioBuffer.buffered : videojs.createTimeRange();
  50438. }
  50439. /**
  50440. * Get the video buffer's buffered timerange.
  50441. *
  50442. * @return {TimeRange}
  50443. * The video buffer's buffered time range
  50444. */
  50445. ;
  50446. _proto.videoBuffered = function videoBuffered() {
  50447. // no media source/source buffer or it isn't in the media sources
  50448. // source buffer list
  50449. if (!inSourceBuffers(this.mediaSource, this.videoBuffer)) {
  50450. return videojs.createTimeRange();
  50451. }
  50452. return this.videoBuffer.buffered ? this.videoBuffer.buffered : videojs.createTimeRange();
  50453. }
  50454. /**
  50455. * Get a combined video/audio buffer's buffered timerange.
  50456. *
  50457. * @return {TimeRange}
  50458. * the combined time range
  50459. */
  50460. ;
  50461. _proto.buffered = function buffered() {
  50462. var video = inSourceBuffers(this.mediaSource, this.videoBuffer) ? this.videoBuffer : null;
  50463. var audio = inSourceBuffers(this.mediaSource, this.audioBuffer) ? this.audioBuffer : null;
  50464. if (audio && !video) {
  50465. return this.audioBuffered();
  50466. }
  50467. if (video && !audio) {
  50468. return this.videoBuffered();
  50469. }
  50470. return bufferIntersection(this.audioBuffered(), this.videoBuffered());
  50471. }
  50472. /**
  50473. * Add a callback to the queue that will set duration on the mediaSource.
  50474. *
  50475. * @param {number} duration
  50476. * The duration to set
  50477. *
  50478. * @param {Function} [doneFn]
  50479. * function to run after duration has been set.
  50480. */
  50481. ;
  50482. _proto.setDuration = function setDuration(duration, doneFn) {
  50483. if (doneFn === void 0) {
  50484. doneFn = noop;
  50485. } // In order to set the duration on the media source, it's necessary to wait for all
  50486. // source buffers to no longer be updating. "If the updating attribute equals true on
  50487. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  50488. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  50489. pushQueue({
  50490. type: 'mediaSource',
  50491. sourceUpdater: this,
  50492. action: actions.duration(duration),
  50493. name: 'duration',
  50494. doneFn: doneFn
  50495. });
  50496. }
  50497. /**
  50498. * Add a mediaSource endOfStream call to the queue
  50499. *
  50500. * @param {Error} [error]
  50501. * Call endOfStream with an error
  50502. *
  50503. * @param {Function} [doneFn]
  50504. * A function that should be called when the
  50505. * endOfStream call has finished.
  50506. */
  50507. ;
  50508. _proto.endOfStream = function endOfStream(error, doneFn) {
  50509. if (error === void 0) {
  50510. error = null;
  50511. }
  50512. if (doneFn === void 0) {
  50513. doneFn = noop;
  50514. }
  50515. if (typeof error !== 'string') {
  50516. error = undefined;
  50517. } // In order to set the duration on the media source, it's necessary to wait for all
  50518. // source buffers to no longer be updating. "If the updating attribute equals true on
  50519. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  50520. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  50521. pushQueue({
  50522. type: 'mediaSource',
  50523. sourceUpdater: this,
  50524. action: actions.endOfStream(error),
  50525. name: 'endOfStream',
  50526. doneFn: doneFn
  50527. });
  50528. }
  50529. /**
  50530. * Queue an update to remove a time range from the buffer.
  50531. *
  50532. * @param {number} start where to start the removal
  50533. * @param {number} end where to end the removal
  50534. * @param {Function} [done=noop] optional callback to be executed when the remove
  50535. * operation is complete
  50536. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  50537. */
  50538. ;
  50539. _proto.removeAudio = function removeAudio(start, end, done) {
  50540. if (done === void 0) {
  50541. done = noop;
  50542. }
  50543. if (!this.audioBuffered().length || this.audioBuffered().end(0) === 0) {
  50544. done();
  50545. return;
  50546. }
  50547. pushQueue({
  50548. type: 'audio',
  50549. sourceUpdater: this,
  50550. action: actions.remove(start, end),
  50551. doneFn: done,
  50552. name: 'remove'
  50553. });
  50554. }
  50555. /**
  50556. * Queue an update to remove a time range from the buffer.
  50557. *
  50558. * @param {number} start where to start the removal
  50559. * @param {number} end where to end the removal
  50560. * @param {Function} [done=noop] optional callback to be executed when the remove
  50561. * operation is complete
  50562. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  50563. */
  50564. ;
  50565. _proto.removeVideo = function removeVideo(start, end, done) {
  50566. if (done === void 0) {
  50567. done = noop;
  50568. }
  50569. if (!this.videoBuffered().length || this.videoBuffered().end(0) === 0) {
  50570. done();
  50571. return;
  50572. }
  50573. pushQueue({
  50574. type: 'video',
  50575. sourceUpdater: this,
  50576. action: actions.remove(start, end),
  50577. doneFn: done,
  50578. name: 'remove'
  50579. });
  50580. }
  50581. /**
  50582. * Whether the underlying sourceBuffer is updating or not
  50583. *
  50584. * @return {boolean} the updating status of the SourceBuffer
  50585. */
  50586. ;
  50587. _proto.updating = function updating() {
  50588. // the audio/video source buffer is updating
  50589. if (_updating('audio', this) || _updating('video', this)) {
  50590. return true;
  50591. }
  50592. return false;
  50593. }
  50594. /**
  50595. * Set/get the timestampoffset on the audio SourceBuffer
  50596. *
  50597. * @return {number} the timestamp offset
  50598. */
  50599. ;
  50600. _proto.audioTimestampOffset = function audioTimestampOffset(offset) {
  50601. if (typeof offset !== 'undefined' && this.audioBuffer && // no point in updating if it's the same
  50602. this.audioTimestampOffset_ !== offset) {
  50603. pushQueue({
  50604. type: 'audio',
  50605. sourceUpdater: this,
  50606. action: actions.timestampOffset(offset),
  50607. name: 'timestampOffset'
  50608. });
  50609. this.audioTimestampOffset_ = offset;
  50610. }
  50611. return this.audioTimestampOffset_;
  50612. }
  50613. /**
  50614. * Set/get the timestampoffset on the video SourceBuffer
  50615. *
  50616. * @return {number} the timestamp offset
  50617. */
  50618. ;
  50619. _proto.videoTimestampOffset = function videoTimestampOffset(offset) {
  50620. if (typeof offset !== 'undefined' && this.videoBuffer && // no point in updating if it's the same
  50621. this.videoTimestampOffset !== offset) {
  50622. pushQueue({
  50623. type: 'video',
  50624. sourceUpdater: this,
  50625. action: actions.timestampOffset(offset),
  50626. name: 'timestampOffset'
  50627. });
  50628. this.videoTimestampOffset_ = offset;
  50629. }
  50630. return this.videoTimestampOffset_;
  50631. }
  50632. /**
  50633. * Add a function to the queue that will be called
  50634. * when it is its turn to run in the audio queue.
  50635. *
  50636. * @param {Function} callback
  50637. * The callback to queue.
  50638. */
  50639. ;
  50640. _proto.audioQueueCallback = function audioQueueCallback(callback) {
  50641. if (!this.audioBuffer) {
  50642. return;
  50643. }
  50644. pushQueue({
  50645. type: 'audio',
  50646. sourceUpdater: this,
  50647. action: actions.callback(callback),
  50648. name: 'callback'
  50649. });
  50650. }
  50651. /**
  50652. * Add a function to the queue that will be called
  50653. * when it is its turn to run in the video queue.
  50654. *
  50655. * @param {Function} callback
  50656. * The callback to queue.
  50657. */
  50658. ;
  50659. _proto.videoQueueCallback = function videoQueueCallback(callback) {
  50660. if (!this.videoBuffer) {
  50661. return;
  50662. }
  50663. pushQueue({
  50664. type: 'video',
  50665. sourceUpdater: this,
  50666. action: actions.callback(callback),
  50667. name: 'callback'
  50668. });
  50669. }
  50670. /**
  50671. * dispose of the source updater and the underlying sourceBuffer
  50672. */
  50673. ;
  50674. _proto.dispose = function dispose() {
  50675. var _this4 = this;
  50676. this.trigger('dispose');
  50677. bufferTypes.forEach(function (type) {
  50678. _this4.abort(type);
  50679. if (_this4.canRemoveSourceBuffer()) {
  50680. _this4.removeSourceBuffer(type);
  50681. } else {
  50682. _this4[type + "QueueCallback"](function () {
  50683. return cleanupBuffer(type, _this4);
  50684. });
  50685. }
  50686. });
  50687. this.videoAppendQueued_ = false;
  50688. this.delayedAudioAppendQueue_.length = 0;
  50689. if (this.sourceopenListener_) {
  50690. this.mediaSource.removeEventListener('sourceopen', this.sourceopenListener_);
  50691. }
  50692. this.off();
  50693. };
  50694. return SourceUpdater;
  50695. }(videojs.EventTarget);
  50696. var uint8ToUtf8 = function uint8ToUtf8(uintArray) {
  50697. return decodeURIComponent(escape(String.fromCharCode.apply(null, uintArray)));
  50698. };
  50699. var VTT_LINE_TERMINATORS = new Uint8Array('\n\n'.split('').map(function (_char3) {
  50700. return _char3.charCodeAt(0);
  50701. }));
  50702. var NoVttJsError = /*#__PURE__*/function (_Error) {
  50703. inheritsLoose(NoVttJsError, _Error);
  50704. function NoVttJsError() {
  50705. return _Error.call(this, 'Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.') || this;
  50706. }
  50707. return NoVttJsError;
  50708. }( /*#__PURE__*/wrapNativeSuper(Error));
  50709. /**
  50710. * An object that manages segment loading and appending.
  50711. *
  50712. * @class VTTSegmentLoader
  50713. * @param {Object} options required and optional options
  50714. * @extends videojs.EventTarget
  50715. */
  50716. var VTTSegmentLoader = /*#__PURE__*/function (_SegmentLoader) {
  50717. inheritsLoose(VTTSegmentLoader, _SegmentLoader);
  50718. function VTTSegmentLoader(settings, options) {
  50719. var _this;
  50720. if (options === void 0) {
  50721. options = {};
  50722. }
  50723. _this = _SegmentLoader.call(this, settings, options) || this; // SegmentLoader requires a MediaSource be specified or it will throw an error;
  50724. // however, VTTSegmentLoader has no need of a media source, so delete the reference
  50725. _this.mediaSource_ = null;
  50726. _this.subtitlesTrack_ = null;
  50727. _this.loaderType_ = 'subtitle';
  50728. _this.featuresNativeTextTracks_ = settings.featuresNativeTextTracks;
  50729. _this.loadVttJs = settings.loadVttJs; // The VTT segment will have its own time mappings. Saving VTT segment timing info in
  50730. // the sync controller leads to improper behavior.
  50731. _this.shouldSaveSegmentTimingInfo_ = false;
  50732. return _this;
  50733. }
  50734. var _proto = VTTSegmentLoader.prototype;
  50735. _proto.createTransmuxer_ = function createTransmuxer_() {
  50736. // don't need to transmux any subtitles
  50737. return null;
  50738. }
  50739. /**
  50740. * Indicates which time ranges are buffered
  50741. *
  50742. * @return {TimeRange}
  50743. * TimeRange object representing the current buffered ranges
  50744. */
  50745. ;
  50746. _proto.buffered_ = function buffered_() {
  50747. if (!this.subtitlesTrack_ || !this.subtitlesTrack_.cues || !this.subtitlesTrack_.cues.length) {
  50748. return videojs.createTimeRanges();
  50749. }
  50750. var cues = this.subtitlesTrack_.cues;
  50751. var start = cues[0].startTime;
  50752. var end = cues[cues.length - 1].startTime;
  50753. return videojs.createTimeRanges([[start, end]]);
  50754. }
  50755. /**
  50756. * Gets and sets init segment for the provided map
  50757. *
  50758. * @param {Object} map
  50759. * The map object representing the init segment to get or set
  50760. * @param {boolean=} set
  50761. * If true, the init segment for the provided map should be saved
  50762. * @return {Object}
  50763. * map object for desired init segment
  50764. */
  50765. ;
  50766. _proto.initSegmentForMap = function initSegmentForMap(map, set) {
  50767. if (set === void 0) {
  50768. set = false;
  50769. }
  50770. if (!map) {
  50771. return null;
  50772. }
  50773. var id = initSegmentId(map);
  50774. var storedMap = this.initSegments_[id];
  50775. if (set && !storedMap && map.bytes) {
  50776. // append WebVTT line terminators to the media initialization segment if it exists
  50777. // to follow the WebVTT spec (https://w3c.github.io/webvtt/#file-structure) that
  50778. // requires two or more WebVTT line terminators between the WebVTT header and the
  50779. // rest of the file
  50780. var combinedByteLength = VTT_LINE_TERMINATORS.byteLength + map.bytes.byteLength;
  50781. var combinedSegment = new Uint8Array(combinedByteLength);
  50782. combinedSegment.set(map.bytes);
  50783. combinedSegment.set(VTT_LINE_TERMINATORS, map.bytes.byteLength);
  50784. this.initSegments_[id] = storedMap = {
  50785. resolvedUri: map.resolvedUri,
  50786. byterange: map.byterange,
  50787. bytes: combinedSegment
  50788. };
  50789. }
  50790. return storedMap || map;
  50791. }
  50792. /**
  50793. * Returns true if all configuration required for loading is present, otherwise false.
  50794. *
  50795. * @return {boolean} True if the all configuration is ready for loading
  50796. * @private
  50797. */
  50798. ;
  50799. _proto.couldBeginLoading_ = function couldBeginLoading_() {
  50800. return this.playlist_ && this.subtitlesTrack_ && !this.paused();
  50801. }
  50802. /**
  50803. * Once all the starting parameters have been specified, begin
  50804. * operation. This method should only be invoked from the INIT
  50805. * state.
  50806. *
  50807. * @private
  50808. */
  50809. ;
  50810. _proto.init_ = function init_() {
  50811. this.state = 'READY';
  50812. this.resetEverything();
  50813. return this.monitorBuffer_();
  50814. }
  50815. /**
  50816. * Set a subtitle track on the segment loader to add subtitles to
  50817. *
  50818. * @param {TextTrack=} track
  50819. * The text track to add loaded subtitles to
  50820. * @return {TextTrack}
  50821. * Returns the subtitles track
  50822. */
  50823. ;
  50824. _proto.track = function track(_track) {
  50825. if (typeof _track === 'undefined') {
  50826. return this.subtitlesTrack_;
  50827. }
  50828. this.subtitlesTrack_ = _track; // if we were unpaused but waiting for a sourceUpdater, start
  50829. // buffering now
  50830. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  50831. this.init_();
  50832. }
  50833. return this.subtitlesTrack_;
  50834. }
  50835. /**
  50836. * Remove any data in the source buffer between start and end times
  50837. *
  50838. * @param {number} start - the start time of the region to remove from the buffer
  50839. * @param {number} end - the end time of the region to remove from the buffer
  50840. */
  50841. ;
  50842. _proto.remove = function remove(start, end) {
  50843. removeCuesFromTrack(start, end, this.subtitlesTrack_);
  50844. }
  50845. /**
  50846. * fill the buffer with segements unless the sourceBuffers are
  50847. * currently updating
  50848. *
  50849. * Note: this function should only ever be called by monitorBuffer_
  50850. * and never directly
  50851. *
  50852. * @private
  50853. */
  50854. ;
  50855. _proto.fillBuffer_ = function fillBuffer_() {
  50856. var _this2 = this; // see if we need to begin loading immediately
  50857. var segmentInfo = this.chooseNextRequest_();
  50858. if (!segmentInfo) {
  50859. return;
  50860. }
  50861. if (this.syncController_.timestampOffsetForTimeline(segmentInfo.timeline) === null) {
  50862. // We don't have the timestamp offset that we need to sync subtitles.
  50863. // Rerun on a timestamp offset or user interaction.
  50864. var checkTimestampOffset = function checkTimestampOffset() {
  50865. _this2.state = 'READY';
  50866. if (!_this2.paused()) {
  50867. // if not paused, queue a buffer check as soon as possible
  50868. _this2.monitorBuffer_();
  50869. }
  50870. };
  50871. this.syncController_.one('timestampoffset', checkTimestampOffset);
  50872. this.state = 'WAITING_ON_TIMELINE';
  50873. return;
  50874. }
  50875. this.loadSegment_(segmentInfo);
  50876. } // never set a timestamp offset for vtt segments.
  50877. ;
  50878. _proto.timestampOffsetForSegment_ = function timestampOffsetForSegment_() {
  50879. return null;
  50880. };
  50881. _proto.chooseNextRequest_ = function chooseNextRequest_() {
  50882. return this.skipEmptySegments_(_SegmentLoader.prototype.chooseNextRequest_.call(this));
  50883. }
  50884. /**
  50885. * Prevents the segment loader from requesting segments we know contain no subtitles
  50886. * by walking forward until we find the next segment that we don't know whether it is
  50887. * empty or not.
  50888. *
  50889. * @param {Object} segmentInfo
  50890. * a segment info object that describes the current segment
  50891. * @return {Object}
  50892. * a segment info object that describes the current segment
  50893. */
  50894. ;
  50895. _proto.skipEmptySegments_ = function skipEmptySegments_(segmentInfo) {
  50896. while (segmentInfo && segmentInfo.segment.empty) {
  50897. // stop at the last possible segmentInfo
  50898. if (segmentInfo.mediaIndex + 1 >= segmentInfo.playlist.segments.length) {
  50899. segmentInfo = null;
  50900. break;
  50901. }
  50902. segmentInfo = this.generateSegmentInfo_({
  50903. playlist: segmentInfo.playlist,
  50904. mediaIndex: segmentInfo.mediaIndex + 1,
  50905. startOfSegment: segmentInfo.startOfSegment + segmentInfo.duration,
  50906. isSyncRequest: segmentInfo.isSyncRequest
  50907. });
  50908. }
  50909. return segmentInfo;
  50910. };
  50911. _proto.stopForError = function stopForError(error) {
  50912. this.error(error);
  50913. this.state = 'READY';
  50914. this.pause();
  50915. this.trigger('error');
  50916. }
  50917. /**
  50918. * append a decrypted segement to the SourceBuffer through a SourceUpdater
  50919. *
  50920. * @private
  50921. */
  50922. ;
  50923. _proto.segmentRequestFinished_ = function segmentRequestFinished_(error, simpleSegment, result) {
  50924. var _this3 = this;
  50925. if (!this.subtitlesTrack_) {
  50926. this.state = 'READY';
  50927. return;
  50928. }
  50929. this.saveTransferStats_(simpleSegment.stats); // the request was aborted
  50930. if (!this.pendingSegment_) {
  50931. this.state = 'READY';
  50932. this.mediaRequestsAborted += 1;
  50933. return;
  50934. }
  50935. if (error) {
  50936. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  50937. this.handleTimeout_();
  50938. }
  50939. if (error.code === REQUEST_ERRORS.ABORTED) {
  50940. this.mediaRequestsAborted += 1;
  50941. } else {
  50942. this.mediaRequestsErrored += 1;
  50943. }
  50944. this.stopForError(error);
  50945. return;
  50946. }
  50947. var segmentInfo = this.pendingSegment_; // although the VTT segment loader bandwidth isn't really used, it's good to
  50948. // maintain functionality between segment loaders
  50949. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats); // if this request included a segment key, save that data in the cache
  50950. if (simpleSegment.key) {
  50951. this.segmentKey(simpleSegment.key, true);
  50952. }
  50953. this.state = 'APPENDING'; // used for tests
  50954. this.trigger('appending');
  50955. var segment = segmentInfo.segment;
  50956. if (segment.map) {
  50957. segment.map.bytes = simpleSegment.map.bytes;
  50958. }
  50959. segmentInfo.bytes = simpleSegment.bytes; // Make sure that vttjs has loaded, otherwise, load it and wait till it finished loading
  50960. if (typeof window.WebVTT !== 'function' && typeof this.loadVttJs === 'function') {
  50961. this.state = 'WAITING_ON_VTTJS'; // should be fine to call multiple times
  50962. // script will be loaded once but multiple listeners will be added to the queue, which is expected.
  50963. this.loadVttJs().then(function () {
  50964. return _this3.segmentRequestFinished_(error, simpleSegment, result);
  50965. }, function () {
  50966. return _this3.stopForError({
  50967. message: 'Error loading vtt.js'
  50968. });
  50969. });
  50970. return;
  50971. }
  50972. segment.requested = true;
  50973. try {
  50974. this.parseVTTCues_(segmentInfo);
  50975. } catch (e) {
  50976. this.stopForError({
  50977. message: e.message
  50978. });
  50979. return;
  50980. }
  50981. this.updateTimeMapping_(segmentInfo, this.syncController_.timelines[segmentInfo.timeline], this.playlist_);
  50982. if (segmentInfo.cues.length) {
  50983. segmentInfo.timingInfo = {
  50984. start: segmentInfo.cues[0].startTime,
  50985. end: segmentInfo.cues[segmentInfo.cues.length - 1].endTime
  50986. };
  50987. } else {
  50988. segmentInfo.timingInfo = {
  50989. start: segmentInfo.startOfSegment,
  50990. end: segmentInfo.startOfSegment + segmentInfo.duration
  50991. };
  50992. }
  50993. if (segmentInfo.isSyncRequest) {
  50994. this.trigger('syncinfoupdate');
  50995. this.pendingSegment_ = null;
  50996. this.state = 'READY';
  50997. return;
  50998. }
  50999. segmentInfo.byteLength = segmentInfo.bytes.byteLength;
  51000. this.mediaSecondsLoaded += segment.duration; // Create VTTCue instances for each cue in the new segment and add them to
  51001. // the subtitle track
  51002. segmentInfo.cues.forEach(function (cue) {
  51003. _this3.subtitlesTrack_.addCue(_this3.featuresNativeTextTracks_ ? new window.VTTCue(cue.startTime, cue.endTime, cue.text) : cue);
  51004. }); // Remove any duplicate cues from the subtitle track. The WebVTT spec allows
  51005. // cues to have identical time-intervals, but if the text is also identical
  51006. // we can safely assume it is a duplicate that can be removed (ex. when a cue
  51007. // "overlaps" VTT segments)
  51008. removeDuplicateCuesFromTrack(this.subtitlesTrack_);
  51009. this.handleAppendsDone_();
  51010. };
  51011. _proto.handleData_ = function handleData_() {// noop as we shouldn't be getting video/audio data captions
  51012. // that we do not support here.
  51013. };
  51014. _proto.updateTimingInfoEnd_ = function updateTimingInfoEnd_() {// noop
  51015. }
  51016. /**
  51017. * Uses the WebVTT parser to parse the segment response
  51018. *
  51019. * @throws NoVttJsError
  51020. *
  51021. * @param {Object} segmentInfo
  51022. * a segment info object that describes the current segment
  51023. * @private
  51024. */
  51025. ;
  51026. _proto.parseVTTCues_ = function parseVTTCues_(segmentInfo) {
  51027. var decoder;
  51028. var decodeBytesToString = false;
  51029. if (typeof window.WebVTT !== 'function') {
  51030. // caller is responsible for exception handling.
  51031. throw new NoVttJsError();
  51032. }
  51033. if (typeof window.TextDecoder === 'function') {
  51034. decoder = new window.TextDecoder('utf8');
  51035. } else {
  51036. decoder = window.WebVTT.StringDecoder();
  51037. decodeBytesToString = true;
  51038. }
  51039. var parser = new window.WebVTT.Parser(window, window.vttjs, decoder);
  51040. segmentInfo.cues = [];
  51041. segmentInfo.timestampmap = {
  51042. MPEGTS: 0,
  51043. LOCAL: 0
  51044. };
  51045. parser.oncue = segmentInfo.cues.push.bind(segmentInfo.cues);
  51046. parser.ontimestampmap = function (map) {
  51047. segmentInfo.timestampmap = map;
  51048. };
  51049. parser.onparsingerror = function (error) {
  51050. videojs.log.warn('Error encountered when parsing cues: ' + error.message);
  51051. };
  51052. if (segmentInfo.segment.map) {
  51053. var mapData = segmentInfo.segment.map.bytes;
  51054. if (decodeBytesToString) {
  51055. mapData = uint8ToUtf8(mapData);
  51056. }
  51057. parser.parse(mapData);
  51058. }
  51059. var segmentData = segmentInfo.bytes;
  51060. if (decodeBytesToString) {
  51061. segmentData = uint8ToUtf8(segmentData);
  51062. }
  51063. parser.parse(segmentData);
  51064. parser.flush();
  51065. }
  51066. /**
  51067. * Updates the start and end times of any cues parsed by the WebVTT parser using
  51068. * the information parsed from the X-TIMESTAMP-MAP header and a TS to media time mapping
  51069. * from the SyncController
  51070. *
  51071. * @param {Object} segmentInfo
  51072. * a segment info object that describes the current segment
  51073. * @param {Object} mappingObj
  51074. * object containing a mapping from TS to media time
  51075. * @param {Object} playlist
  51076. * the playlist object containing the segment
  51077. * @private
  51078. */
  51079. ;
  51080. _proto.updateTimeMapping_ = function updateTimeMapping_(segmentInfo, mappingObj, playlist) {
  51081. var segment = segmentInfo.segment;
  51082. if (!mappingObj) {
  51083. // If the sync controller does not have a mapping of TS to Media Time for the
  51084. // timeline, then we don't have enough information to update the cue
  51085. // start/end times
  51086. return;
  51087. }
  51088. if (!segmentInfo.cues.length) {
  51089. // If there are no cues, we also do not have enough information to figure out
  51090. // segment timing. Mark that the segment contains no cues so we don't re-request
  51091. // an empty segment.
  51092. segment.empty = true;
  51093. return;
  51094. }
  51095. var timestampmap = segmentInfo.timestampmap;
  51096. var diff = timestampmap.MPEGTS / clock_1 - timestampmap.LOCAL + mappingObj.mapping;
  51097. segmentInfo.cues.forEach(function (cue) {
  51098. // First convert cue time to TS time using the timestamp-map provided within the vtt
  51099. cue.startTime += diff;
  51100. cue.endTime += diff;
  51101. });
  51102. if (!playlist.syncInfo) {
  51103. var firstStart = segmentInfo.cues[0].startTime;
  51104. var lastStart = segmentInfo.cues[segmentInfo.cues.length - 1].startTime;
  51105. playlist.syncInfo = {
  51106. mediaSequence: playlist.mediaSequence + segmentInfo.mediaIndex,
  51107. time: Math.min(firstStart, lastStart - segment.duration)
  51108. };
  51109. }
  51110. };
  51111. return VTTSegmentLoader;
  51112. }(SegmentLoader);
  51113. /**
  51114. * @file ad-cue-tags.js
  51115. */
  51116. /**
  51117. * Searches for an ad cue that overlaps with the given mediaTime
  51118. *
  51119. * @param {Object} track
  51120. * the track to find the cue for
  51121. *
  51122. * @param {number} mediaTime
  51123. * the time to find the cue at
  51124. *
  51125. * @return {Object|null}
  51126. * the found cue or null
  51127. */
  51128. var findAdCue = function findAdCue(track, mediaTime) {
  51129. var cues = track.cues;
  51130. for (var i = 0; i < cues.length; i++) {
  51131. var cue = cues[i];
  51132. if (mediaTime >= cue.adStartTime && mediaTime <= cue.adEndTime) {
  51133. return cue;
  51134. }
  51135. }
  51136. return null;
  51137. };
  51138. var updateAdCues = function updateAdCues(media, track, offset) {
  51139. if (offset === void 0) {
  51140. offset = 0;
  51141. }
  51142. if (!media.segments) {
  51143. return;
  51144. }
  51145. var mediaTime = offset;
  51146. var cue;
  51147. for (var i = 0; i < media.segments.length; i++) {
  51148. var segment = media.segments[i];
  51149. if (!cue) {
  51150. // Since the cues will span for at least the segment duration, adding a fudge
  51151. // factor of half segment duration will prevent duplicate cues from being
  51152. // created when timing info is not exact (e.g. cue start time initialized
  51153. // at 10.006677, but next call mediaTime is 10.003332 )
  51154. cue = findAdCue(track, mediaTime + segment.duration / 2);
  51155. }
  51156. if (cue) {
  51157. if ('cueIn' in segment) {
  51158. // Found a CUE-IN so end the cue
  51159. cue.endTime = mediaTime;
  51160. cue.adEndTime = mediaTime;
  51161. mediaTime += segment.duration;
  51162. cue = null;
  51163. continue;
  51164. }
  51165. if (mediaTime < cue.endTime) {
  51166. // Already processed this mediaTime for this cue
  51167. mediaTime += segment.duration;
  51168. continue;
  51169. } // otherwise extend cue until a CUE-IN is found
  51170. cue.endTime += segment.duration;
  51171. } else {
  51172. if ('cueOut' in segment) {
  51173. cue = new window.VTTCue(mediaTime, mediaTime + segment.duration, segment.cueOut);
  51174. cue.adStartTime = mediaTime; // Assumes tag format to be
  51175. // #EXT-X-CUE-OUT:30
  51176. cue.adEndTime = mediaTime + parseFloat(segment.cueOut);
  51177. track.addCue(cue);
  51178. }
  51179. if ('cueOutCont' in segment) {
  51180. // Entered into the middle of an ad cue
  51181. // Assumes tag formate to be
  51182. // #EXT-X-CUE-OUT-CONT:10/30
  51183. var _segment$cueOutCont$s = segment.cueOutCont.split('/').map(parseFloat),
  51184. adOffset = _segment$cueOutCont$s[0],
  51185. adTotal = _segment$cueOutCont$s[1];
  51186. cue = new window.VTTCue(mediaTime, mediaTime + segment.duration, '');
  51187. cue.adStartTime = mediaTime - adOffset;
  51188. cue.adEndTime = cue.adStartTime + adTotal;
  51189. track.addCue(cue);
  51190. }
  51191. }
  51192. mediaTime += segment.duration;
  51193. }
  51194. }; // synchronize expired playlist segments.
  51195. // the max media sequence diff is 48 hours of live stream
  51196. // content with two second segments. Anything larger than that
  51197. // will likely be invalid.
  51198. var MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC = 86400;
  51199. var syncPointStrategies = [// Stategy "VOD": Handle the VOD-case where the sync-point is *always*
  51200. // the equivalence display-time 0 === segment-index 0
  51201. {
  51202. name: 'VOD',
  51203. run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
  51204. if (duration !== Infinity) {
  51205. var syncPoint = {
  51206. time: 0,
  51207. segmentIndex: 0,
  51208. partIndex: null
  51209. };
  51210. return syncPoint;
  51211. }
  51212. return null;
  51213. }
  51214. }, // Stategy "ProgramDateTime": We have a program-date-time tag in this playlist
  51215. {
  51216. name: 'ProgramDateTime',
  51217. run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
  51218. if (!Object.keys(syncController.timelineToDatetimeMappings).length) {
  51219. return null;
  51220. }
  51221. var syncPoint = null;
  51222. var lastDistance = null;
  51223. var partsAndSegments = getPartsAndSegments(playlist);
  51224. currentTime = currentTime || 0;
  51225. for (var i = 0; i < partsAndSegments.length; i++) {
  51226. // start from the end and loop backwards for live
  51227. // or start from the front and loop forwards for non-live
  51228. var index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  51229. var partAndSegment = partsAndSegments[index];
  51230. var segment = partAndSegment.segment;
  51231. var datetimeMapping = syncController.timelineToDatetimeMappings[segment.timeline];
  51232. if (!datetimeMapping || !segment.dateTimeObject) {
  51233. continue;
  51234. }
  51235. var segmentTime = segment.dateTimeObject.getTime() / 1000;
  51236. var start = segmentTime + datetimeMapping; // take part duration into account.
  51237. if (segment.parts && typeof partAndSegment.partIndex === 'number') {
  51238. for (var z = 0; z < partAndSegment.partIndex; z++) {
  51239. start += segment.parts[z].duration;
  51240. }
  51241. }
  51242. var distance = Math.abs(currentTime - start); // Once the distance begins to increase, or if distance is 0, we have passed
  51243. // currentTime and can stop looking for better candidates
  51244. if (lastDistance !== null && (distance === 0 || lastDistance < distance)) {
  51245. break;
  51246. }
  51247. lastDistance = distance;
  51248. syncPoint = {
  51249. time: start,
  51250. segmentIndex: partAndSegment.segmentIndex,
  51251. partIndex: partAndSegment.partIndex
  51252. };
  51253. }
  51254. return syncPoint;
  51255. }
  51256. }, // Stategy "Segment": We have a known time mapping for a timeline and a
  51257. // segment in the current timeline with timing data
  51258. {
  51259. name: 'Segment',
  51260. run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
  51261. var syncPoint = null;
  51262. var lastDistance = null;
  51263. currentTime = currentTime || 0;
  51264. var partsAndSegments = getPartsAndSegments(playlist);
  51265. for (var i = 0; i < partsAndSegments.length; i++) {
  51266. // start from the end and loop backwards for live
  51267. // or start from the front and loop forwards for non-live
  51268. var index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  51269. var partAndSegment = partsAndSegments[index];
  51270. var segment = partAndSegment.segment;
  51271. var start = partAndSegment.part && partAndSegment.part.start || segment && segment.start;
  51272. if (segment.timeline === currentTimeline && typeof start !== 'undefined') {
  51273. var distance = Math.abs(currentTime - start); // Once the distance begins to increase, we have passed
  51274. // currentTime and can stop looking for better candidates
  51275. if (lastDistance !== null && lastDistance < distance) {
  51276. break;
  51277. }
  51278. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  51279. lastDistance = distance;
  51280. syncPoint = {
  51281. time: start,
  51282. segmentIndex: partAndSegment.segmentIndex,
  51283. partIndex: partAndSegment.partIndex
  51284. };
  51285. }
  51286. }
  51287. }
  51288. return syncPoint;
  51289. }
  51290. }, // Stategy "Discontinuity": We have a discontinuity with a known
  51291. // display-time
  51292. {
  51293. name: 'Discontinuity',
  51294. run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
  51295. var syncPoint = null;
  51296. currentTime = currentTime || 0;
  51297. if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  51298. var lastDistance = null;
  51299. for (var i = 0; i < playlist.discontinuityStarts.length; i++) {
  51300. var segmentIndex = playlist.discontinuityStarts[i];
  51301. var discontinuity = playlist.discontinuitySequence + i + 1;
  51302. var discontinuitySync = syncController.discontinuities[discontinuity];
  51303. if (discontinuitySync) {
  51304. var distance = Math.abs(currentTime - discontinuitySync.time); // Once the distance begins to increase, we have passed
  51305. // currentTime and can stop looking for better candidates
  51306. if (lastDistance !== null && lastDistance < distance) {
  51307. break;
  51308. }
  51309. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  51310. lastDistance = distance;
  51311. syncPoint = {
  51312. time: discontinuitySync.time,
  51313. segmentIndex: segmentIndex,
  51314. partIndex: null
  51315. };
  51316. }
  51317. }
  51318. }
  51319. }
  51320. return syncPoint;
  51321. }
  51322. }, // Stategy "Playlist": We have a playlist with a known mapping of
  51323. // segment index to display time
  51324. {
  51325. name: 'Playlist',
  51326. run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
  51327. if (playlist.syncInfo) {
  51328. var syncPoint = {
  51329. time: playlist.syncInfo.time,
  51330. segmentIndex: playlist.syncInfo.mediaSequence - playlist.mediaSequence,
  51331. partIndex: null
  51332. };
  51333. return syncPoint;
  51334. }
  51335. return null;
  51336. }
  51337. }];
  51338. var SyncController = /*#__PURE__*/function (_videojs$EventTarget) {
  51339. inheritsLoose(SyncController, _videojs$EventTarget);
  51340. function SyncController(options) {
  51341. var _this;
  51342. _this = _videojs$EventTarget.call(this) || this; // ...for synching across variants
  51343. _this.timelines = [];
  51344. _this.discontinuities = [];
  51345. _this.timelineToDatetimeMappings = {};
  51346. _this.logger_ = logger('SyncController');
  51347. return _this;
  51348. }
  51349. /**
  51350. * Find a sync-point for the playlist specified
  51351. *
  51352. * A sync-point is defined as a known mapping from display-time to
  51353. * a segment-index in the current playlist.
  51354. *
  51355. * @param {Playlist} playlist
  51356. * The playlist that needs a sync-point
  51357. * @param {number} duration
  51358. * Duration of the MediaSource (Infinite if playing a live source)
  51359. * @param {number} currentTimeline
  51360. * The last timeline from which a segment was loaded
  51361. * @return {Object}
  51362. * A sync-point object
  51363. */
  51364. var _proto = SyncController.prototype;
  51365. _proto.getSyncPoint = function getSyncPoint(playlist, duration, currentTimeline, currentTime) {
  51366. var syncPoints = this.runStrategies_(playlist, duration, currentTimeline, currentTime);
  51367. if (!syncPoints.length) {
  51368. // Signal that we need to attempt to get a sync-point manually
  51369. // by fetching a segment in the playlist and constructing
  51370. // a sync-point from that information
  51371. return null;
  51372. } // Now find the sync-point that is closest to the currentTime because
  51373. // that should result in the most accurate guess about which segment
  51374. // to fetch
  51375. return this.selectSyncPoint_(syncPoints, {
  51376. key: 'time',
  51377. value: currentTime
  51378. });
  51379. }
  51380. /**
  51381. * Calculate the amount of time that has expired off the playlist during playback
  51382. *
  51383. * @param {Playlist} playlist
  51384. * Playlist object to calculate expired from
  51385. * @param {number} duration
  51386. * Duration of the MediaSource (Infinity if playling a live source)
  51387. * @return {number|null}
  51388. * The amount of time that has expired off the playlist during playback. Null
  51389. * if no sync-points for the playlist can be found.
  51390. */
  51391. ;
  51392. _proto.getExpiredTime = function getExpiredTime(playlist, duration) {
  51393. if (!playlist || !playlist.segments) {
  51394. return null;
  51395. }
  51396. var syncPoints = this.runStrategies_(playlist, duration, playlist.discontinuitySequence, 0); // Without sync-points, there is not enough information to determine the expired time
  51397. if (!syncPoints.length) {
  51398. return null;
  51399. }
  51400. var syncPoint = this.selectSyncPoint_(syncPoints, {
  51401. key: 'segmentIndex',
  51402. value: 0
  51403. }); // If the sync-point is beyond the start of the playlist, we want to subtract the
  51404. // duration from index 0 to syncPoint.segmentIndex instead of adding.
  51405. if (syncPoint.segmentIndex > 0) {
  51406. syncPoint.time *= -1;
  51407. }
  51408. return Math.abs(syncPoint.time + sumDurations({
  51409. defaultDuration: playlist.targetDuration,
  51410. durationList: playlist.segments,
  51411. startIndex: syncPoint.segmentIndex,
  51412. endIndex: 0
  51413. }));
  51414. }
  51415. /**
  51416. * Runs each sync-point strategy and returns a list of sync-points returned by the
  51417. * strategies
  51418. *
  51419. * @private
  51420. * @param {Playlist} playlist
  51421. * The playlist that needs a sync-point
  51422. * @param {number} duration
  51423. * Duration of the MediaSource (Infinity if playing a live source)
  51424. * @param {number} currentTimeline
  51425. * The last timeline from which a segment was loaded
  51426. * @return {Array}
  51427. * A list of sync-point objects
  51428. */
  51429. ;
  51430. _proto.runStrategies_ = function runStrategies_(playlist, duration, currentTimeline, currentTime) {
  51431. var syncPoints = []; // Try to find a sync-point in by utilizing various strategies...
  51432. for (var i = 0; i < syncPointStrategies.length; i++) {
  51433. var strategy = syncPointStrategies[i];
  51434. var syncPoint = strategy.run(this, playlist, duration, currentTimeline, currentTime);
  51435. if (syncPoint) {
  51436. syncPoint.strategy = strategy.name;
  51437. syncPoints.push({
  51438. strategy: strategy.name,
  51439. syncPoint: syncPoint
  51440. });
  51441. }
  51442. }
  51443. return syncPoints;
  51444. }
  51445. /**
  51446. * Selects the sync-point nearest the specified target
  51447. *
  51448. * @private
  51449. * @param {Array} syncPoints
  51450. * List of sync-points to select from
  51451. * @param {Object} target
  51452. * Object specifying the property and value we are targeting
  51453. * @param {string} target.key
  51454. * Specifies the property to target. Must be either 'time' or 'segmentIndex'
  51455. * @param {number} target.value
  51456. * The value to target for the specified key.
  51457. * @return {Object}
  51458. * The sync-point nearest the target
  51459. */
  51460. ;
  51461. _proto.selectSyncPoint_ = function selectSyncPoint_(syncPoints, target) {
  51462. var bestSyncPoint = syncPoints[0].syncPoint;
  51463. var bestDistance = Math.abs(syncPoints[0].syncPoint[target.key] - target.value);
  51464. var bestStrategy = syncPoints[0].strategy;
  51465. for (var i = 1; i < syncPoints.length; i++) {
  51466. var newDistance = Math.abs(syncPoints[i].syncPoint[target.key] - target.value);
  51467. if (newDistance < bestDistance) {
  51468. bestDistance = newDistance;
  51469. bestSyncPoint = syncPoints[i].syncPoint;
  51470. bestStrategy = syncPoints[i].strategy;
  51471. }
  51472. }
  51473. this.logger_("syncPoint for [" + target.key + ": " + target.value + "] chosen with strategy" + (" [" + bestStrategy + "]: [time:" + bestSyncPoint.time + ",") + (" segmentIndex:" + bestSyncPoint.segmentIndex) + (typeof bestSyncPoint.partIndex === 'number' ? ",partIndex:" + bestSyncPoint.partIndex : '') + ']');
  51474. return bestSyncPoint;
  51475. }
  51476. /**
  51477. * Save any meta-data present on the segments when segments leave
  51478. * the live window to the playlist to allow for synchronization at the
  51479. * playlist level later.
  51480. *
  51481. * @param {Playlist} oldPlaylist - The previous active playlist
  51482. * @param {Playlist} newPlaylist - The updated and most current playlist
  51483. */
  51484. ;
  51485. _proto.saveExpiredSegmentInfo = function saveExpiredSegmentInfo(oldPlaylist, newPlaylist) {
  51486. var mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence; // Ignore large media sequence gaps
  51487. if (mediaSequenceDiff > MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC) {
  51488. videojs.log.warn("Not saving expired segment info. Media sequence gap " + mediaSequenceDiff + " is too large.");
  51489. return;
  51490. } // When a segment expires from the playlist and it has a start time
  51491. // save that information as a possible sync-point reference in future
  51492. for (var i = mediaSequenceDiff - 1; i >= 0; i--) {
  51493. var lastRemovedSegment = oldPlaylist.segments[i];
  51494. if (lastRemovedSegment && typeof lastRemovedSegment.start !== 'undefined') {
  51495. newPlaylist.syncInfo = {
  51496. mediaSequence: oldPlaylist.mediaSequence + i,
  51497. time: lastRemovedSegment.start
  51498. };
  51499. this.logger_("playlist refresh sync: [time:" + newPlaylist.syncInfo.time + "," + (" mediaSequence: " + newPlaylist.syncInfo.mediaSequence + "]"));
  51500. this.trigger('syncinfoupdate');
  51501. break;
  51502. }
  51503. }
  51504. }
  51505. /**
  51506. * Save the mapping from playlist's ProgramDateTime to display. This should only happen
  51507. * before segments start to load.
  51508. *
  51509. * @param {Playlist} playlist - The currently active playlist
  51510. */
  51511. ;
  51512. _proto.setDateTimeMappingForStart = function setDateTimeMappingForStart(playlist) {
  51513. // It's possible for the playlist to be updated before playback starts, meaning time
  51514. // zero is not yet set. If, during these playlist refreshes, a discontinuity is
  51515. // crossed, then the old time zero mapping (for the prior timeline) would be retained
  51516. // unless the mappings are cleared.
  51517. this.timelineToDatetimeMappings = {};
  51518. if (playlist.segments && playlist.segments.length && playlist.segments[0].dateTimeObject) {
  51519. var firstSegment = playlist.segments[0];
  51520. var playlistTimestamp = firstSegment.dateTimeObject.getTime() / 1000;
  51521. this.timelineToDatetimeMappings[firstSegment.timeline] = -playlistTimestamp;
  51522. }
  51523. }
  51524. /**
  51525. * Calculates and saves timeline mappings, playlist sync info, and segment timing values
  51526. * based on the latest timing information.
  51527. *
  51528. * @param {Object} options
  51529. * Options object
  51530. * @param {SegmentInfo} options.segmentInfo
  51531. * The current active request information
  51532. * @param {boolean} options.shouldSaveTimelineMapping
  51533. * If there's a timeline change, determines if the timeline mapping should be
  51534. * saved for timeline mapping and program date time mappings.
  51535. */
  51536. ;
  51537. _proto.saveSegmentTimingInfo = function saveSegmentTimingInfo(_ref) {
  51538. var segmentInfo = _ref.segmentInfo,
  51539. shouldSaveTimelineMapping = _ref.shouldSaveTimelineMapping;
  51540. var didCalculateSegmentTimeMapping = this.calculateSegmentTimeMapping_(segmentInfo, segmentInfo.timingInfo, shouldSaveTimelineMapping);
  51541. var segment = segmentInfo.segment;
  51542. if (didCalculateSegmentTimeMapping) {
  51543. this.saveDiscontinuitySyncInfo_(segmentInfo); // If the playlist does not have sync information yet, record that information
  51544. // now with segment timing information
  51545. if (!segmentInfo.playlist.syncInfo) {
  51546. segmentInfo.playlist.syncInfo = {
  51547. mediaSequence: segmentInfo.playlist.mediaSequence + segmentInfo.mediaIndex,
  51548. time: segment.start
  51549. };
  51550. }
  51551. }
  51552. var dateTime = segment.dateTimeObject;
  51553. if (segment.discontinuity && shouldSaveTimelineMapping && dateTime) {
  51554. this.timelineToDatetimeMappings[segment.timeline] = -(dateTime.getTime() / 1000);
  51555. }
  51556. };
  51557. _proto.timestampOffsetForTimeline = function timestampOffsetForTimeline(timeline) {
  51558. if (typeof this.timelines[timeline] === 'undefined') {
  51559. return null;
  51560. }
  51561. return this.timelines[timeline].time;
  51562. };
  51563. _proto.mappingForTimeline = function mappingForTimeline(timeline) {
  51564. if (typeof this.timelines[timeline] === 'undefined') {
  51565. return null;
  51566. }
  51567. return this.timelines[timeline].mapping;
  51568. }
  51569. /**
  51570. * Use the "media time" for a segment to generate a mapping to "display time" and
  51571. * save that display time to the segment.
  51572. *
  51573. * @private
  51574. * @param {SegmentInfo} segmentInfo
  51575. * The current active request information
  51576. * @param {Object} timingInfo
  51577. * The start and end time of the current segment in "media time"
  51578. * @param {boolean} shouldSaveTimelineMapping
  51579. * If there's a timeline change, determines if the timeline mapping should be
  51580. * saved in timelines.
  51581. * @return {boolean}
  51582. * Returns false if segment time mapping could not be calculated
  51583. */
  51584. ;
  51585. _proto.calculateSegmentTimeMapping_ = function calculateSegmentTimeMapping_(segmentInfo, timingInfo, shouldSaveTimelineMapping) {
  51586. // TODO: remove side effects
  51587. var segment = segmentInfo.segment;
  51588. var part = segmentInfo.part;
  51589. var mappingObj = this.timelines[segmentInfo.timeline];
  51590. var start;
  51591. var end;
  51592. if (typeof segmentInfo.timestampOffset === 'number') {
  51593. mappingObj = {
  51594. time: segmentInfo.startOfSegment,
  51595. mapping: segmentInfo.startOfSegment - timingInfo.start
  51596. };
  51597. if (shouldSaveTimelineMapping) {
  51598. this.timelines[segmentInfo.timeline] = mappingObj;
  51599. this.trigger('timestampoffset');
  51600. this.logger_("time mapping for timeline " + segmentInfo.timeline + ": " + ("[time: " + mappingObj.time + "] [mapping: " + mappingObj.mapping + "]"));
  51601. }
  51602. start = segmentInfo.startOfSegment;
  51603. end = timingInfo.end + mappingObj.mapping;
  51604. } else if (mappingObj) {
  51605. start = timingInfo.start + mappingObj.mapping;
  51606. end = timingInfo.end + mappingObj.mapping;
  51607. } else {
  51608. return false;
  51609. }
  51610. if (part) {
  51611. part.start = start;
  51612. part.end = end;
  51613. } // If we don't have a segment start yet or the start value we got
  51614. // is less than our current segment.start value, save a new start value.
  51615. // We have to do this because parts will have segment timing info saved
  51616. // multiple times and we want segment start to be the earliest part start
  51617. // value for that segment.
  51618. if (!segment.start || start < segment.start) {
  51619. segment.start = start;
  51620. }
  51621. segment.end = end;
  51622. return true;
  51623. }
  51624. /**
  51625. * Each time we have discontinuity in the playlist, attempt to calculate the location
  51626. * in display of the start of the discontinuity and save that. We also save an accuracy
  51627. * value so that we save values with the most accuracy (closest to 0.)
  51628. *
  51629. * @private
  51630. * @param {SegmentInfo} segmentInfo - The current active request information
  51631. */
  51632. ;
  51633. _proto.saveDiscontinuitySyncInfo_ = function saveDiscontinuitySyncInfo_(segmentInfo) {
  51634. var playlist = segmentInfo.playlist;
  51635. var segment = segmentInfo.segment; // If the current segment is a discontinuity then we know exactly where
  51636. // the start of the range and it's accuracy is 0 (greater accuracy values
  51637. // mean more approximation)
  51638. if (segment.discontinuity) {
  51639. this.discontinuities[segment.timeline] = {
  51640. time: segment.start,
  51641. accuracy: 0
  51642. };
  51643. } else if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  51644. // Search for future discontinuities that we can provide better timing
  51645. // information for and save that information for sync purposes
  51646. for (var i = 0; i < playlist.discontinuityStarts.length; i++) {
  51647. var segmentIndex = playlist.discontinuityStarts[i];
  51648. var discontinuity = playlist.discontinuitySequence + i + 1;
  51649. var mediaIndexDiff = segmentIndex - segmentInfo.mediaIndex;
  51650. var accuracy = Math.abs(mediaIndexDiff);
  51651. if (!this.discontinuities[discontinuity] || this.discontinuities[discontinuity].accuracy > accuracy) {
  51652. var time = void 0;
  51653. if (mediaIndexDiff < 0) {
  51654. time = segment.start - sumDurations({
  51655. defaultDuration: playlist.targetDuration,
  51656. durationList: playlist.segments,
  51657. startIndex: segmentInfo.mediaIndex,
  51658. endIndex: segmentIndex
  51659. });
  51660. } else {
  51661. time = segment.end + sumDurations({
  51662. defaultDuration: playlist.targetDuration,
  51663. durationList: playlist.segments,
  51664. startIndex: segmentInfo.mediaIndex + 1,
  51665. endIndex: segmentIndex
  51666. });
  51667. }
  51668. this.discontinuities[discontinuity] = {
  51669. time: time,
  51670. accuracy: accuracy
  51671. };
  51672. }
  51673. }
  51674. }
  51675. };
  51676. _proto.dispose = function dispose() {
  51677. this.trigger('dispose');
  51678. this.off();
  51679. };
  51680. return SyncController;
  51681. }(videojs.EventTarget);
  51682. /**
  51683. * The TimelineChangeController acts as a source for segment loaders to listen for and
  51684. * keep track of latest and pending timeline changes. This is useful to ensure proper
  51685. * sync, as each loader may need to make a consideration for what timeline the other
  51686. * loader is on before making changes which could impact the other loader's media.
  51687. *
  51688. * @class TimelineChangeController
  51689. * @extends videojs.EventTarget
  51690. */
  51691. var TimelineChangeController = /*#__PURE__*/function (_videojs$EventTarget) {
  51692. inheritsLoose(TimelineChangeController, _videojs$EventTarget);
  51693. function TimelineChangeController() {
  51694. var _this;
  51695. _this = _videojs$EventTarget.call(this) || this;
  51696. _this.pendingTimelineChanges_ = {};
  51697. _this.lastTimelineChanges_ = {};
  51698. return _this;
  51699. }
  51700. var _proto = TimelineChangeController.prototype;
  51701. _proto.clearPendingTimelineChange = function clearPendingTimelineChange(type) {
  51702. this.pendingTimelineChanges_[type] = null;
  51703. this.trigger('pendingtimelinechange');
  51704. };
  51705. _proto.pendingTimelineChange = function pendingTimelineChange(_ref) {
  51706. var type = _ref.type,
  51707. from = _ref.from,
  51708. to = _ref.to;
  51709. if (typeof from === 'number' && typeof to === 'number') {
  51710. this.pendingTimelineChanges_[type] = {
  51711. type: type,
  51712. from: from,
  51713. to: to
  51714. };
  51715. this.trigger('pendingtimelinechange');
  51716. }
  51717. return this.pendingTimelineChanges_[type];
  51718. };
  51719. _proto.lastTimelineChange = function lastTimelineChange(_ref2) {
  51720. var type = _ref2.type,
  51721. from = _ref2.from,
  51722. to = _ref2.to;
  51723. if (typeof from === 'number' && typeof to === 'number') {
  51724. this.lastTimelineChanges_[type] = {
  51725. type: type,
  51726. from: from,
  51727. to: to
  51728. };
  51729. delete this.pendingTimelineChanges_[type];
  51730. this.trigger('timelinechange');
  51731. }
  51732. return this.lastTimelineChanges_[type];
  51733. };
  51734. _proto.dispose = function dispose() {
  51735. this.trigger('dispose');
  51736. this.pendingTimelineChanges_ = {};
  51737. this.lastTimelineChanges_ = {};
  51738. this.off();
  51739. };
  51740. return TimelineChangeController;
  51741. }(videojs.EventTarget);
  51742. /* rollup-plugin-worker-factory start for worker!/Users/ddashkevich/projects/http-streaming/src/decrypter-worker.js */
  51743. var workerCode = transform(getWorkerString(function () {
  51744. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  51745. function createCommonjsModule(fn, basedir, module) {
  51746. return module = {
  51747. path: basedir,
  51748. exports: {},
  51749. require: function require(path, base) {
  51750. return commonjsRequire(path, base === undefined || base === null ? module.path : base);
  51751. }
  51752. }, fn(module, module.exports), module.exports;
  51753. }
  51754. function commonjsRequire() {
  51755. throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
  51756. }
  51757. var createClass = createCommonjsModule(function (module) {
  51758. function _defineProperties(target, props) {
  51759. for (var i = 0; i < props.length; i++) {
  51760. var descriptor = props[i];
  51761. descriptor.enumerable = descriptor.enumerable || false;
  51762. descriptor.configurable = true;
  51763. if ("value" in descriptor) descriptor.writable = true;
  51764. Object.defineProperty(target, descriptor.key, descriptor);
  51765. }
  51766. }
  51767. function _createClass(Constructor, protoProps, staticProps) {
  51768. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  51769. if (staticProps) _defineProperties(Constructor, staticProps);
  51770. return Constructor;
  51771. }
  51772. module.exports = _createClass;
  51773. module.exports["default"] = module.exports, module.exports.__esModule = true;
  51774. });
  51775. var setPrototypeOf = createCommonjsModule(function (module) {
  51776. function _setPrototypeOf(o, p) {
  51777. module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  51778. o.__proto__ = p;
  51779. return o;
  51780. };
  51781. module.exports["default"] = module.exports, module.exports.__esModule = true;
  51782. return _setPrototypeOf(o, p);
  51783. }
  51784. module.exports = _setPrototypeOf;
  51785. module.exports["default"] = module.exports, module.exports.__esModule = true;
  51786. });
  51787. var inheritsLoose = createCommonjsModule(function (module) {
  51788. function _inheritsLoose(subClass, superClass) {
  51789. subClass.prototype = Object.create(superClass.prototype);
  51790. subClass.prototype.constructor = subClass;
  51791. setPrototypeOf(subClass, superClass);
  51792. }
  51793. module.exports = _inheritsLoose;
  51794. module.exports["default"] = module.exports, module.exports.__esModule = true;
  51795. });
  51796. /**
  51797. * @file stream.js
  51798. */
  51799. /**
  51800. * A lightweight readable stream implemention that handles event dispatching.
  51801. *
  51802. * @class Stream
  51803. */
  51804. var Stream = /*#__PURE__*/function () {
  51805. function Stream() {
  51806. this.listeners = {};
  51807. }
  51808. /**
  51809. * Add a listener for a specified event type.
  51810. *
  51811. * @param {string} type the event name
  51812. * @param {Function} listener the callback to be invoked when an event of
  51813. * the specified type occurs
  51814. */
  51815. var _proto = Stream.prototype;
  51816. _proto.on = function on(type, listener) {
  51817. if (!this.listeners[type]) {
  51818. this.listeners[type] = [];
  51819. }
  51820. this.listeners[type].push(listener);
  51821. }
  51822. /**
  51823. * Remove a listener for a specified event type.
  51824. *
  51825. * @param {string} type the event name
  51826. * @param {Function} listener a function previously registered for this
  51827. * type of event through `on`
  51828. * @return {boolean} if we could turn it off or not
  51829. */
  51830. ;
  51831. _proto.off = function off(type, listener) {
  51832. if (!this.listeners[type]) {
  51833. return false;
  51834. }
  51835. var index = this.listeners[type].indexOf(listener); // TODO: which is better?
  51836. // In Video.js we slice listener functions
  51837. // on trigger so that it does not mess up the order
  51838. // while we loop through.
  51839. //
  51840. // Here we slice on off so that the loop in trigger
  51841. // can continue using it's old reference to loop without
  51842. // messing up the order.
  51843. this.listeners[type] = this.listeners[type].slice(0);
  51844. this.listeners[type].splice(index, 1);
  51845. return index > -1;
  51846. }
  51847. /**
  51848. * Trigger an event of the specified type on this stream. Any additional
  51849. * arguments to this function are passed as parameters to event listeners.
  51850. *
  51851. * @param {string} type the event name
  51852. */
  51853. ;
  51854. _proto.trigger = function trigger(type) {
  51855. var callbacks = this.listeners[type];
  51856. if (!callbacks) {
  51857. return;
  51858. } // Slicing the arguments on every invocation of this method
  51859. // can add a significant amount of overhead. Avoid the
  51860. // intermediate object creation for the common case of a
  51861. // single callback argument
  51862. if (arguments.length === 2) {
  51863. var length = callbacks.length;
  51864. for (var i = 0; i < length; ++i) {
  51865. callbacks[i].call(this, arguments[1]);
  51866. }
  51867. } else {
  51868. var args = Array.prototype.slice.call(arguments, 1);
  51869. var _length = callbacks.length;
  51870. for (var _i = 0; _i < _length; ++_i) {
  51871. callbacks[_i].apply(this, args);
  51872. }
  51873. }
  51874. }
  51875. /**
  51876. * Destroys the stream and cleans up.
  51877. */
  51878. ;
  51879. _proto.dispose = function dispose() {
  51880. this.listeners = {};
  51881. }
  51882. /**
  51883. * Forwards all `data` events on this stream to the destination stream. The
  51884. * destination stream should provide a method `push` to receive the data
  51885. * events as they arrive.
  51886. *
  51887. * @param {Stream} destination the stream that will receive all `data` events
  51888. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  51889. */
  51890. ;
  51891. _proto.pipe = function pipe(destination) {
  51892. this.on('data', function (data) {
  51893. destination.push(data);
  51894. });
  51895. };
  51896. return Stream;
  51897. }();
  51898. /*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */
  51899. /**
  51900. * Returns the subarray of a Uint8Array without PKCS#7 padding.
  51901. *
  51902. * @param padded {Uint8Array} unencrypted bytes that have been padded
  51903. * @return {Uint8Array} the unpadded bytes
  51904. * @see http://tools.ietf.org/html/rfc5652
  51905. */
  51906. function unpad(padded) {
  51907. return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
  51908. }
  51909. /*! @name aes-decrypter @version 3.1.3 @license Apache-2.0 */
  51910. /**
  51911. * @file aes.js
  51912. *
  51913. * This file contains an adaptation of the AES decryption algorithm
  51914. * from the Standford Javascript Cryptography Library. That work is
  51915. * covered by the following copyright and permissions notice:
  51916. *
  51917. * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
  51918. * All rights reserved.
  51919. *
  51920. * Redistribution and use in source and binary forms, with or without
  51921. * modification, are permitted provided that the following conditions are
  51922. * met:
  51923. *
  51924. * 1. Redistributions of source code must retain the above copyright
  51925. * notice, this list of conditions and the following disclaimer.
  51926. *
  51927. * 2. Redistributions in binary form must reproduce the above
  51928. * copyright notice, this list of conditions and the following
  51929. * disclaimer in the documentation and/or other materials provided
  51930. * with the distribution.
  51931. *
  51932. * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
  51933. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  51934. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  51935. * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
  51936. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  51937. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  51938. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  51939. * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  51940. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  51941. * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  51942. * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  51943. *
  51944. * The views and conclusions contained in the software and documentation
  51945. * are those of the authors and should not be interpreted as representing
  51946. * official policies, either expressed or implied, of the authors.
  51947. */
  51948. /**
  51949. * Expand the S-box tables.
  51950. *
  51951. * @private
  51952. */
  51953. var precompute = function precompute() {
  51954. var tables = [[[], [], [], [], []], [[], [], [], [], []]];
  51955. var encTable = tables[0];
  51956. var decTable = tables[1];
  51957. var sbox = encTable[4];
  51958. var sboxInv = decTable[4];
  51959. var i;
  51960. var x;
  51961. var xInv;
  51962. var d = [];
  51963. var th = [];
  51964. var x2;
  51965. var x4;
  51966. var x8;
  51967. var s;
  51968. var tEnc;
  51969. var tDec; // Compute double and third tables
  51970. for (i = 0; i < 256; i++) {
  51971. th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
  51972. }
  51973. for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
  51974. // Compute sbox
  51975. s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
  51976. s = s >> 8 ^ s & 255 ^ 99;
  51977. sbox[x] = s;
  51978. sboxInv[s] = x; // Compute MixColumns
  51979. x8 = d[x4 = d[x2 = d[x]]];
  51980. tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  51981. tEnc = d[s] * 0x101 ^ s * 0x1010100;
  51982. for (i = 0; i < 4; i++) {
  51983. encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
  51984. decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
  51985. }
  51986. } // Compactify. Considerable speedup on Firefox.
  51987. for (i = 0; i < 5; i++) {
  51988. encTable[i] = encTable[i].slice(0);
  51989. decTable[i] = decTable[i].slice(0);
  51990. }
  51991. return tables;
  51992. };
  51993. var aesTables = null;
  51994. /**
  51995. * Schedule out an AES key for both encryption and decryption. This
  51996. * is a low-level class. Use a cipher mode to do bulk encryption.
  51997. *
  51998. * @class AES
  51999. * @param key {Array} The key as an array of 4, 6 or 8 words.
  52000. */
  52001. var AES = /*#__PURE__*/function () {
  52002. function AES(key) {
  52003. /**
  52004. * The expanded S-box and inverse S-box tables. These will be computed
  52005. * on the client so that we don't have to send them down the wire.
  52006. *
  52007. * There are two tables, _tables[0] is for encryption and
  52008. * _tables[1] is for decryption.
  52009. *
  52010. * The first 4 sub-tables are the expanded S-box with MixColumns. The
  52011. * last (_tables[01][4]) is the S-box itself.
  52012. *
  52013. * @private
  52014. */
  52015. // if we have yet to precompute the S-box tables
  52016. // do so now
  52017. if (!aesTables) {
  52018. aesTables = precompute();
  52019. } // then make a copy of that object for use
  52020. this._tables = [[aesTables[0][0].slice(), aesTables[0][1].slice(), aesTables[0][2].slice(), aesTables[0][3].slice(), aesTables[0][4].slice()], [aesTables[1][0].slice(), aesTables[1][1].slice(), aesTables[1][2].slice(), aesTables[1][3].slice(), aesTables[1][4].slice()]];
  52021. var i;
  52022. var j;
  52023. var tmp;
  52024. var sbox = this._tables[0][4];
  52025. var decTable = this._tables[1];
  52026. var keyLen = key.length;
  52027. var rcon = 1;
  52028. if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
  52029. throw new Error('Invalid aes key size');
  52030. }
  52031. var encKey = key.slice(0);
  52032. var decKey = [];
  52033. this._key = [encKey, decKey]; // schedule encryption keys
  52034. for (i = keyLen; i < 4 * keyLen + 28; i++) {
  52035. tmp = encKey[i - 1]; // apply sbox
  52036. if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
  52037. tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
  52038. if (i % keyLen === 0) {
  52039. tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
  52040. rcon = rcon << 1 ^ (rcon >> 7) * 283;
  52041. }
  52042. }
  52043. encKey[i] = encKey[i - keyLen] ^ tmp;
  52044. } // schedule decryption keys
  52045. for (j = 0; i; j++, i--) {
  52046. tmp = encKey[j & 3 ? i : i - 4];
  52047. if (i <= 4 || j < 4) {
  52048. decKey[j] = tmp;
  52049. } else {
  52050. decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
  52051. }
  52052. }
  52053. }
  52054. /**
  52055. * Decrypt 16 bytes, specified as four 32-bit words.
  52056. *
  52057. * @param {number} encrypted0 the first word to decrypt
  52058. * @param {number} encrypted1 the second word to decrypt
  52059. * @param {number} encrypted2 the third word to decrypt
  52060. * @param {number} encrypted3 the fourth word to decrypt
  52061. * @param {Int32Array} out the array to write the decrypted words
  52062. * into
  52063. * @param {number} offset the offset into the output array to start
  52064. * writing results
  52065. * @return {Array} The plaintext.
  52066. */
  52067. var _proto = AES.prototype;
  52068. _proto.decrypt = function decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
  52069. var key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
  52070. var a = encrypted0 ^ key[0];
  52071. var b = encrypted3 ^ key[1];
  52072. var c = encrypted2 ^ key[2];
  52073. var d = encrypted1 ^ key[3];
  52074. var a2;
  52075. var b2;
  52076. var c2; // key.length === 2 ?
  52077. var nInnerRounds = key.length / 4 - 2;
  52078. var i;
  52079. var kIndex = 4;
  52080. var table = this._tables[1]; // load up the tables
  52081. var table0 = table[0];
  52082. var table1 = table[1];
  52083. var table2 = table[2];
  52084. var table3 = table[3];
  52085. var sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.
  52086. for (i = 0; i < nInnerRounds; i++) {
  52087. a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
  52088. b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
  52089. c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
  52090. d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
  52091. kIndex += 4;
  52092. a = a2;
  52093. b = b2;
  52094. c = c2;
  52095. } // Last round.
  52096. for (i = 0; i < 4; i++) {
  52097. out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
  52098. a2 = a;
  52099. a = b;
  52100. b = c;
  52101. c = d;
  52102. d = a2;
  52103. }
  52104. };
  52105. return AES;
  52106. }();
  52107. /**
  52108. * A wrapper around the Stream class to use setTimeout
  52109. * and run stream "jobs" Asynchronously
  52110. *
  52111. * @class AsyncStream
  52112. * @extends Stream
  52113. */
  52114. var AsyncStream = /*#__PURE__*/function (_Stream) {
  52115. inheritsLoose(AsyncStream, _Stream);
  52116. function AsyncStream() {
  52117. var _this;
  52118. _this = _Stream.call(this, Stream) || this;
  52119. _this.jobs = [];
  52120. _this.delay = 1;
  52121. _this.timeout_ = null;
  52122. return _this;
  52123. }
  52124. /**
  52125. * process an async job
  52126. *
  52127. * @private
  52128. */
  52129. var _proto = AsyncStream.prototype;
  52130. _proto.processJob_ = function processJob_() {
  52131. this.jobs.shift()();
  52132. if (this.jobs.length) {
  52133. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  52134. } else {
  52135. this.timeout_ = null;
  52136. }
  52137. }
  52138. /**
  52139. * push a job into the stream
  52140. *
  52141. * @param {Function} job the job to push into the stream
  52142. */
  52143. ;
  52144. _proto.push = function push(job) {
  52145. this.jobs.push(job);
  52146. if (!this.timeout_) {
  52147. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  52148. }
  52149. };
  52150. return AsyncStream;
  52151. }(Stream);
  52152. /**
  52153. * Convert network-order (big-endian) bytes into their little-endian
  52154. * representation.
  52155. */
  52156. var ntoh = function ntoh(word) {
  52157. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  52158. };
  52159. /**
  52160. * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
  52161. *
  52162. * @param {Uint8Array} encrypted the encrypted bytes
  52163. * @param {Uint32Array} key the bytes of the decryption key
  52164. * @param {Uint32Array} initVector the initialization vector (IV) to
  52165. * use for the first round of CBC.
  52166. * @return {Uint8Array} the decrypted bytes
  52167. *
  52168. * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
  52169. * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
  52170. * @see https://tools.ietf.org/html/rfc2315
  52171. */
  52172. var decrypt = function decrypt(encrypted, key, initVector) {
  52173. // word-level access to the encrypted bytes
  52174. var encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
  52175. var decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
  52176. var decrypted = new Uint8Array(encrypted.byteLength);
  52177. var decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and
  52178. // decrypted data
  52179. var init0;
  52180. var init1;
  52181. var init2;
  52182. var init3;
  52183. var encrypted0;
  52184. var encrypted1;
  52185. var encrypted2;
  52186. var encrypted3; // iteration variable
  52187. var wordIx; // pull out the words of the IV to ensure we don't modify the
  52188. // passed-in reference and easier access
  52189. init0 = initVector[0];
  52190. init1 = initVector[1];
  52191. init2 = initVector[2];
  52192. init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)
  52193. // to each decrypted block
  52194. for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
  52195. // convert big-endian (network order) words into little-endian
  52196. // (javascript order)
  52197. encrypted0 = ntoh(encrypted32[wordIx]);
  52198. encrypted1 = ntoh(encrypted32[wordIx + 1]);
  52199. encrypted2 = ntoh(encrypted32[wordIx + 2]);
  52200. encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block
  52201. decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the
  52202. // plaintext
  52203. decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
  52204. decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
  52205. decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
  52206. decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round
  52207. init0 = encrypted0;
  52208. init1 = encrypted1;
  52209. init2 = encrypted2;
  52210. init3 = encrypted3;
  52211. }
  52212. return decrypted;
  52213. };
  52214. /**
  52215. * The `Decrypter` class that manages decryption of AES
  52216. * data through `AsyncStream` objects and the `decrypt`
  52217. * function
  52218. *
  52219. * @param {Uint8Array} encrypted the encrypted bytes
  52220. * @param {Uint32Array} key the bytes of the decryption key
  52221. * @param {Uint32Array} initVector the initialization vector (IV) to
  52222. * @param {Function} done the function to run when done
  52223. * @class Decrypter
  52224. */
  52225. var Decrypter = /*#__PURE__*/function () {
  52226. function Decrypter(encrypted, key, initVector, done) {
  52227. var step = Decrypter.STEP;
  52228. var encrypted32 = new Int32Array(encrypted.buffer);
  52229. var decrypted = new Uint8Array(encrypted.byteLength);
  52230. var i = 0;
  52231. this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously
  52232. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  52233. for (i = step; i < encrypted32.length; i += step) {
  52234. initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
  52235. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  52236. } // invoke the done() callback when everything is finished
  52237. this.asyncStream_.push(function () {
  52238. // remove pkcs#7 padding from the decrypted bytes
  52239. done(null, unpad(decrypted));
  52240. });
  52241. }
  52242. /**
  52243. * a getter for step the maximum number of bytes to process at one time
  52244. *
  52245. * @return {number} the value of step 32000
  52246. */
  52247. var _proto = Decrypter.prototype;
  52248. /**
  52249. * @private
  52250. */
  52251. _proto.decryptChunk_ = function decryptChunk_(encrypted, key, initVector, decrypted) {
  52252. return function () {
  52253. var bytes = decrypt(encrypted, key, initVector);
  52254. decrypted.set(bytes, encrypted.byteOffset);
  52255. };
  52256. };
  52257. createClass(Decrypter, null, [{
  52258. key: "STEP",
  52259. get: function get() {
  52260. // 4 * 8000;
  52261. return 32000;
  52262. }
  52263. }]);
  52264. return Decrypter;
  52265. }();
  52266. var win;
  52267. if (typeof window !== "undefined") {
  52268. win = window;
  52269. } else if (typeof commonjsGlobal !== "undefined") {
  52270. win = commonjsGlobal;
  52271. } else if (typeof self !== "undefined") {
  52272. win = self;
  52273. } else {
  52274. win = {};
  52275. }
  52276. var window_1 = win;
  52277. var isArrayBufferView = function isArrayBufferView(obj) {
  52278. if (ArrayBuffer.isView === 'function') {
  52279. return ArrayBuffer.isView(obj);
  52280. }
  52281. return obj && obj.buffer instanceof ArrayBuffer;
  52282. };
  52283. var BigInt = window_1.BigInt || Number;
  52284. [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
  52285. /**
  52286. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  52287. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  52288. *
  52289. * @param {Object} message
  52290. * Object of properties and values to send to the web worker
  52291. * @return {Object}
  52292. * Modified message with TypedArray values expanded
  52293. * @function createTransferableMessage
  52294. */
  52295. var createTransferableMessage = function createTransferableMessage(message) {
  52296. var transferable = {};
  52297. Object.keys(message).forEach(function (key) {
  52298. var value = message[key];
  52299. if (isArrayBufferView(value)) {
  52300. transferable[key] = {
  52301. bytes: value.buffer,
  52302. byteOffset: value.byteOffset,
  52303. byteLength: value.byteLength
  52304. };
  52305. } else {
  52306. transferable[key] = value;
  52307. }
  52308. });
  52309. return transferable;
  52310. };
  52311. /* global self */
  52312. /**
  52313. * Our web worker interface so that things can talk to aes-decrypter
  52314. * that will be running in a web worker. the scope is passed to this by
  52315. * webworkify.
  52316. */
  52317. self.onmessage = function (event) {
  52318. var data = event.data;
  52319. var encrypted = new Uint8Array(data.encrypted.bytes, data.encrypted.byteOffset, data.encrypted.byteLength);
  52320. var key = new Uint32Array(data.key.bytes, data.key.byteOffset, data.key.byteLength / 4);
  52321. var iv = new Uint32Array(data.iv.bytes, data.iv.byteOffset, data.iv.byteLength / 4);
  52322. /* eslint-disable no-new, handle-callback-err */
  52323. new Decrypter(encrypted, key, iv, function (err, bytes) {
  52324. self.postMessage(createTransferableMessage({
  52325. source: data.source,
  52326. decrypted: bytes
  52327. }), [bytes.buffer]);
  52328. });
  52329. /* eslint-enable */
  52330. };
  52331. }));
  52332. var Decrypter = factory(workerCode);
  52333. /* rollup-plugin-worker-factory end for worker!/Users/ddashkevich/projects/http-streaming/src/decrypter-worker.js */
  52334. /**
  52335. * Convert the properties of an HLS track into an audioTrackKind.
  52336. *
  52337. * @private
  52338. */
  52339. var audioTrackKind_ = function audioTrackKind_(properties) {
  52340. var kind = properties["default"] ? 'main' : 'alternative';
  52341. if (properties.characteristics && properties.characteristics.indexOf('public.accessibility.describes-video') >= 0) {
  52342. kind = 'main-desc';
  52343. }
  52344. return kind;
  52345. };
  52346. /**
  52347. * Pause provided segment loader and playlist loader if active
  52348. *
  52349. * @param {SegmentLoader} segmentLoader
  52350. * SegmentLoader to pause
  52351. * @param {Object} mediaType
  52352. * Active media type
  52353. * @function stopLoaders
  52354. */
  52355. var stopLoaders = function stopLoaders(segmentLoader, mediaType) {
  52356. segmentLoader.abort();
  52357. segmentLoader.pause();
  52358. if (mediaType && mediaType.activePlaylistLoader) {
  52359. mediaType.activePlaylistLoader.pause();
  52360. mediaType.activePlaylistLoader = null;
  52361. }
  52362. };
  52363. /**
  52364. * Start loading provided segment loader and playlist loader
  52365. *
  52366. * @param {PlaylistLoader} playlistLoader
  52367. * PlaylistLoader to start loading
  52368. * @param {Object} mediaType
  52369. * Active media type
  52370. * @function startLoaders
  52371. */
  52372. var startLoaders = function startLoaders(playlistLoader, mediaType) {
  52373. // Segment loader will be started after `loadedmetadata` or `loadedplaylist` from the
  52374. // playlist loader
  52375. mediaType.activePlaylistLoader = playlistLoader;
  52376. playlistLoader.load();
  52377. };
  52378. /**
  52379. * Returns a function to be called when the media group changes. It performs a
  52380. * non-destructive (preserve the buffer) resync of the SegmentLoader. This is because a
  52381. * change of group is merely a rendition switch of the same content at another encoding,
  52382. * rather than a change of content, such as switching audio from English to Spanish.
  52383. *
  52384. * @param {string} type
  52385. * MediaGroup type
  52386. * @param {Object} settings
  52387. * Object containing required information for media groups
  52388. * @return {Function}
  52389. * Handler for a non-destructive resync of SegmentLoader when the active media
  52390. * group changes.
  52391. * @function onGroupChanged
  52392. */
  52393. var onGroupChanged = function onGroupChanged(type, settings) {
  52394. return function () {
  52395. var _settings$segmentLoad = settings.segmentLoaders,
  52396. segmentLoader = _settings$segmentLoad[type],
  52397. mainSegmentLoader = _settings$segmentLoad.main,
  52398. mediaType = settings.mediaTypes[type];
  52399. var activeTrack = mediaType.activeTrack();
  52400. var activeGroup = mediaType.getActiveGroup();
  52401. var previousActiveLoader = mediaType.activePlaylistLoader;
  52402. var lastGroup = mediaType.lastGroup_; // the group did not change do nothing
  52403. if (activeGroup && lastGroup && activeGroup.id === lastGroup.id) {
  52404. return;
  52405. }
  52406. mediaType.lastGroup_ = activeGroup;
  52407. mediaType.lastTrack_ = activeTrack;
  52408. stopLoaders(segmentLoader, mediaType);
  52409. if (!activeGroup || activeGroup.isMasterPlaylist) {
  52410. // there is no group active or active group is a main playlist and won't change
  52411. return;
  52412. }
  52413. if (!activeGroup.playlistLoader) {
  52414. if (previousActiveLoader) {
  52415. // The previous group had a playlist loader but the new active group does not
  52416. // this means we are switching from demuxed to muxed audio. In this case we want to
  52417. // do a destructive reset of the main segment loader and not restart the audio
  52418. // loaders.
  52419. mainSegmentLoader.resetEverything();
  52420. }
  52421. return;
  52422. } // Non-destructive resync
  52423. segmentLoader.resyncLoader();
  52424. startLoaders(activeGroup.playlistLoader, mediaType);
  52425. };
  52426. };
  52427. var onGroupChanging = function onGroupChanging(type, settings) {
  52428. return function () {
  52429. var segmentLoader = settings.segmentLoaders[type],
  52430. mediaType = settings.mediaTypes[type];
  52431. mediaType.lastGroup_ = null;
  52432. segmentLoader.abort();
  52433. segmentLoader.pause();
  52434. };
  52435. };
  52436. /**
  52437. * Returns a function to be called when the media track changes. It performs a
  52438. * destructive reset of the SegmentLoader to ensure we start loading as close to
  52439. * currentTime as possible.
  52440. *
  52441. * @param {string} type
  52442. * MediaGroup type
  52443. * @param {Object} settings
  52444. * Object containing required information for media groups
  52445. * @return {Function}
  52446. * Handler for a destructive reset of SegmentLoader when the active media
  52447. * track changes.
  52448. * @function onTrackChanged
  52449. */
  52450. var onTrackChanged = function onTrackChanged(type, settings) {
  52451. return function () {
  52452. var masterPlaylistLoader = settings.masterPlaylistLoader,
  52453. _settings$segmentLoad2 = settings.segmentLoaders,
  52454. segmentLoader = _settings$segmentLoad2[type],
  52455. mainSegmentLoader = _settings$segmentLoad2.main,
  52456. mediaType = settings.mediaTypes[type];
  52457. var activeTrack = mediaType.activeTrack();
  52458. var activeGroup = mediaType.getActiveGroup();
  52459. var previousActiveLoader = mediaType.activePlaylistLoader;
  52460. var lastTrack = mediaType.lastTrack_; // track did not change, do nothing
  52461. if (lastTrack && activeTrack && lastTrack.id === activeTrack.id) {
  52462. return;
  52463. }
  52464. mediaType.lastGroup_ = activeGroup;
  52465. mediaType.lastTrack_ = activeTrack;
  52466. stopLoaders(segmentLoader, mediaType);
  52467. if (!activeGroup) {
  52468. // there is no group active so we do not want to restart loaders
  52469. return;
  52470. }
  52471. if (activeGroup.isMasterPlaylist) {
  52472. // track did not change, do nothing
  52473. if (!activeTrack || !lastTrack || activeTrack.id === lastTrack.id) {
  52474. return;
  52475. }
  52476. var mpc = settings.vhs.masterPlaylistController_;
  52477. var newPlaylist = mpc.selectPlaylist(); // media will not change do nothing
  52478. if (mpc.media() === newPlaylist) {
  52479. return;
  52480. }
  52481. mediaType.logger_("track change. Switching master audio from " + lastTrack.id + " to " + activeTrack.id);
  52482. masterPlaylistLoader.pause();
  52483. mainSegmentLoader.resetEverything();
  52484. mpc.fastQualityChange_(newPlaylist);
  52485. return;
  52486. }
  52487. if (type === 'AUDIO') {
  52488. if (!activeGroup.playlistLoader) {
  52489. // when switching from demuxed audio/video to muxed audio/video (noted by no
  52490. // playlist loader for the audio group), we want to do a destructive reset of the
  52491. // main segment loader and not restart the audio loaders
  52492. mainSegmentLoader.setAudio(true); // don't have to worry about disabling the audio of the audio segment loader since
  52493. // it should be stopped
  52494. mainSegmentLoader.resetEverything();
  52495. return;
  52496. } // although the segment loader is an audio segment loader, call the setAudio
  52497. // function to ensure it is prepared to re-append the init segment (or handle other
  52498. // config changes)
  52499. segmentLoader.setAudio(true);
  52500. mainSegmentLoader.setAudio(false);
  52501. }
  52502. if (previousActiveLoader === activeGroup.playlistLoader) {
  52503. // Nothing has actually changed. This can happen because track change events can fire
  52504. // multiple times for a "single" change. One for enabling the new active track, and
  52505. // one for disabling the track that was active
  52506. startLoaders(activeGroup.playlistLoader, mediaType);
  52507. return;
  52508. }
  52509. if (segmentLoader.track) {
  52510. // For WebVTT, set the new text track in the segmentloader
  52511. segmentLoader.track(activeTrack);
  52512. } // destructive reset
  52513. segmentLoader.resetEverything();
  52514. startLoaders(activeGroup.playlistLoader, mediaType);
  52515. };
  52516. };
  52517. var onError = {
  52518. /**
  52519. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  52520. * an error.
  52521. *
  52522. * @param {string} type
  52523. * MediaGroup type
  52524. * @param {Object} settings
  52525. * Object containing required information for media groups
  52526. * @return {Function}
  52527. * Error handler. Logs warning (or error if the playlist is blacklisted) to
  52528. * console and switches back to default audio track.
  52529. * @function onError.AUDIO
  52530. */
  52531. AUDIO: function AUDIO(type, settings) {
  52532. return function () {
  52533. var segmentLoader = settings.segmentLoaders[type],
  52534. mediaType = settings.mediaTypes[type],
  52535. blacklistCurrentPlaylist = settings.blacklistCurrentPlaylist;
  52536. stopLoaders(segmentLoader, mediaType); // switch back to default audio track
  52537. var activeTrack = mediaType.activeTrack();
  52538. var activeGroup = mediaType.activeGroup();
  52539. var id = (activeGroup.filter(function (group) {
  52540. return group["default"];
  52541. })[0] || activeGroup[0]).id;
  52542. var defaultTrack = mediaType.tracks[id];
  52543. if (activeTrack === defaultTrack) {
  52544. // Default track encountered an error. All we can do now is blacklist the current
  52545. // rendition and hope another will switch audio groups
  52546. blacklistCurrentPlaylist({
  52547. message: 'Problem encountered loading the default audio track.'
  52548. });
  52549. return;
  52550. }
  52551. videojs.log.warn('Problem encountered loading the alternate audio track.' + 'Switching back to default.');
  52552. for (var trackId in mediaType.tracks) {
  52553. mediaType.tracks[trackId].enabled = mediaType.tracks[trackId] === defaultTrack;
  52554. }
  52555. mediaType.onTrackChanged();
  52556. };
  52557. },
  52558. /**
  52559. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  52560. * an error.
  52561. *
  52562. * @param {string} type
  52563. * MediaGroup type
  52564. * @param {Object} settings
  52565. * Object containing required information for media groups
  52566. * @return {Function}
  52567. * Error handler. Logs warning to console and disables the active subtitle track
  52568. * @function onError.SUBTITLES
  52569. */
  52570. SUBTITLES: function SUBTITLES(type, settings) {
  52571. return function () {
  52572. var segmentLoader = settings.segmentLoaders[type],
  52573. mediaType = settings.mediaTypes[type];
  52574. videojs.log.warn('Problem encountered loading the subtitle track.' + 'Disabling subtitle track.');
  52575. stopLoaders(segmentLoader, mediaType);
  52576. var track = mediaType.activeTrack();
  52577. if (track) {
  52578. track.mode = 'disabled';
  52579. }
  52580. mediaType.onTrackChanged();
  52581. };
  52582. }
  52583. };
  52584. var setupListeners = {
  52585. /**
  52586. * Setup event listeners for audio playlist loader
  52587. *
  52588. * @param {string} type
  52589. * MediaGroup type
  52590. * @param {PlaylistLoader|null} playlistLoader
  52591. * PlaylistLoader to register listeners on
  52592. * @param {Object} settings
  52593. * Object containing required information for media groups
  52594. * @function setupListeners.AUDIO
  52595. */
  52596. AUDIO: function AUDIO(type, playlistLoader, settings) {
  52597. if (!playlistLoader) {
  52598. // no playlist loader means audio will be muxed with the video
  52599. return;
  52600. }
  52601. var tech = settings.tech,
  52602. requestOptions = settings.requestOptions,
  52603. segmentLoader = settings.segmentLoaders[type];
  52604. playlistLoader.on('loadedmetadata', function () {
  52605. var media = playlistLoader.media();
  52606. segmentLoader.playlist(media, requestOptions); // if the video is already playing, or if this isn't a live video and preload
  52607. // permits, start downloading segments
  52608. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  52609. segmentLoader.load();
  52610. }
  52611. });
  52612. playlistLoader.on('loadedplaylist', function () {
  52613. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  52614. if (!tech.paused()) {
  52615. segmentLoader.load();
  52616. }
  52617. });
  52618. playlistLoader.on('error', onError[type](type, settings));
  52619. },
  52620. /**
  52621. * Setup event listeners for subtitle playlist loader
  52622. *
  52623. * @param {string} type
  52624. * MediaGroup type
  52625. * @param {PlaylistLoader|null} playlistLoader
  52626. * PlaylistLoader to register listeners on
  52627. * @param {Object} settings
  52628. * Object containing required information for media groups
  52629. * @function setupListeners.SUBTITLES
  52630. */
  52631. SUBTITLES: function SUBTITLES(type, playlistLoader, settings) {
  52632. var tech = settings.tech,
  52633. requestOptions = settings.requestOptions,
  52634. segmentLoader = settings.segmentLoaders[type],
  52635. mediaType = settings.mediaTypes[type];
  52636. playlistLoader.on('loadedmetadata', function () {
  52637. var media = playlistLoader.media();
  52638. segmentLoader.playlist(media, requestOptions);
  52639. segmentLoader.track(mediaType.activeTrack()); // if the video is already playing, or if this isn't a live video and preload
  52640. // permits, start downloading segments
  52641. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  52642. segmentLoader.load();
  52643. }
  52644. });
  52645. playlistLoader.on('loadedplaylist', function () {
  52646. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  52647. if (!tech.paused()) {
  52648. segmentLoader.load();
  52649. }
  52650. });
  52651. playlistLoader.on('error', onError[type](type, settings));
  52652. }
  52653. };
  52654. var initialize = {
  52655. /**
  52656. * Setup PlaylistLoaders and AudioTracks for the audio groups
  52657. *
  52658. * @param {string} type
  52659. * MediaGroup type
  52660. * @param {Object} settings
  52661. * Object containing required information for media groups
  52662. * @function initialize.AUDIO
  52663. */
  52664. 'AUDIO': function AUDIO(type, settings) {
  52665. var vhs = settings.vhs,
  52666. sourceType = settings.sourceType,
  52667. segmentLoader = settings.segmentLoaders[type],
  52668. requestOptions = settings.requestOptions,
  52669. mediaGroups = settings.master.mediaGroups,
  52670. _settings$mediaTypes$ = settings.mediaTypes[type],
  52671. groups = _settings$mediaTypes$.groups,
  52672. tracks = _settings$mediaTypes$.tracks,
  52673. logger_ = _settings$mediaTypes$.logger_,
  52674. masterPlaylistLoader = settings.masterPlaylistLoader;
  52675. var audioOnlyMaster = isAudioOnly(masterPlaylistLoader.master); // force a default if we have none
  52676. if (!mediaGroups[type] || Object.keys(mediaGroups[type]).length === 0) {
  52677. mediaGroups[type] = {
  52678. main: {
  52679. "default": {
  52680. "default": true
  52681. }
  52682. }
  52683. };
  52684. if (audioOnlyMaster) {
  52685. mediaGroups[type].main["default"].playlists = masterPlaylistLoader.master.playlists;
  52686. }
  52687. }
  52688. for (var groupId in mediaGroups[type]) {
  52689. if (!groups[groupId]) {
  52690. groups[groupId] = [];
  52691. }
  52692. for (var variantLabel in mediaGroups[type][groupId]) {
  52693. var properties = mediaGroups[type][groupId][variantLabel];
  52694. var playlistLoader = void 0;
  52695. if (audioOnlyMaster) {
  52696. logger_("AUDIO group '" + groupId + "' label '" + variantLabel + "' is a master playlist");
  52697. properties.isMasterPlaylist = true;
  52698. playlistLoader = null; // if vhs-json was provided as the source, and the media playlist was resolved,
  52699. // use the resolved media playlist object
  52700. } else if (sourceType === 'vhs-json' && properties.playlists) {
  52701. playlistLoader = new PlaylistLoader(properties.playlists[0], vhs, requestOptions);
  52702. } else if (properties.resolvedUri) {
  52703. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions); // TODO: dash isn't the only type with properties.playlists
  52704. // should we even have properties.playlists in this check.
  52705. } else if (properties.playlists && sourceType === 'dash') {
  52706. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, masterPlaylistLoader);
  52707. } else {
  52708. // no resolvedUri means the audio is muxed with the video when using this
  52709. // audio track
  52710. playlistLoader = null;
  52711. }
  52712. properties = videojs.mergeOptions({
  52713. id: variantLabel,
  52714. playlistLoader: playlistLoader
  52715. }, properties);
  52716. setupListeners[type](type, properties.playlistLoader, settings);
  52717. groups[groupId].push(properties);
  52718. if (typeof tracks[variantLabel] === 'undefined') {
  52719. var track = new videojs.AudioTrack({
  52720. id: variantLabel,
  52721. kind: audioTrackKind_(properties),
  52722. enabled: false,
  52723. language: properties.language,
  52724. "default": properties["default"],
  52725. label: variantLabel
  52726. });
  52727. tracks[variantLabel] = track;
  52728. }
  52729. }
  52730. } // setup single error event handler for the segment loader
  52731. segmentLoader.on('error', onError[type](type, settings));
  52732. },
  52733. /**
  52734. * Setup PlaylistLoaders and TextTracks for the subtitle groups
  52735. *
  52736. * @param {string} type
  52737. * MediaGroup type
  52738. * @param {Object} settings
  52739. * Object containing required information for media groups
  52740. * @function initialize.SUBTITLES
  52741. */
  52742. 'SUBTITLES': function SUBTITLES(type, settings) {
  52743. var tech = settings.tech,
  52744. vhs = settings.vhs,
  52745. sourceType = settings.sourceType,
  52746. segmentLoader = settings.segmentLoaders[type],
  52747. requestOptions = settings.requestOptions,
  52748. mediaGroups = settings.master.mediaGroups,
  52749. _settings$mediaTypes$2 = settings.mediaTypes[type],
  52750. groups = _settings$mediaTypes$2.groups,
  52751. tracks = _settings$mediaTypes$2.tracks,
  52752. masterPlaylistLoader = settings.masterPlaylistLoader;
  52753. for (var groupId in mediaGroups[type]) {
  52754. if (!groups[groupId]) {
  52755. groups[groupId] = [];
  52756. }
  52757. for (var variantLabel in mediaGroups[type][groupId]) {
  52758. if (mediaGroups[type][groupId][variantLabel].forced) {
  52759. // Subtitle playlists with the forced attribute are not selectable in Safari.
  52760. // According to Apple's HLS Authoring Specification:
  52761. // If content has forced subtitles and regular subtitles in a given language,
  52762. // the regular subtitles track in that language MUST contain both the forced
  52763. // subtitles and the regular subtitles for that language.
  52764. // Because of this requirement and that Safari does not add forced subtitles,
  52765. // forced subtitles are skipped here to maintain consistent experience across
  52766. // all platforms
  52767. continue;
  52768. }
  52769. var properties = mediaGroups[type][groupId][variantLabel];
  52770. var playlistLoader = void 0;
  52771. if (sourceType === 'hls') {
  52772. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions);
  52773. } else if (sourceType === 'dash') {
  52774. var playlists = properties.playlists.filter(function (p) {
  52775. return p.excludeUntil !== Infinity;
  52776. });
  52777. if (!playlists.length) {
  52778. return;
  52779. }
  52780. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, masterPlaylistLoader);
  52781. } else if (sourceType === 'vhs-json') {
  52782. playlistLoader = new PlaylistLoader( // if the vhs-json object included the media playlist, use the media playlist
  52783. // as provided, otherwise use the resolved URI to load the playlist
  52784. properties.playlists ? properties.playlists[0] : properties.resolvedUri, vhs, requestOptions);
  52785. }
  52786. properties = videojs.mergeOptions({
  52787. id: variantLabel,
  52788. playlistLoader: playlistLoader
  52789. }, properties);
  52790. setupListeners[type](type, properties.playlistLoader, settings);
  52791. groups[groupId].push(properties);
  52792. if (typeof tracks[variantLabel] === 'undefined') {
  52793. var track = tech.addRemoteTextTrack({
  52794. id: variantLabel,
  52795. kind: 'subtitles',
  52796. "default": properties["default"] && properties.autoselect,
  52797. language: properties.language,
  52798. label: variantLabel
  52799. }, false).track;
  52800. tracks[variantLabel] = track;
  52801. }
  52802. }
  52803. } // setup single error event handler for the segment loader
  52804. segmentLoader.on('error', onError[type](type, settings));
  52805. },
  52806. /**
  52807. * Setup TextTracks for the closed-caption groups
  52808. *
  52809. * @param {String} type
  52810. * MediaGroup type
  52811. * @param {Object} settings
  52812. * Object containing required information for media groups
  52813. * @function initialize['CLOSED-CAPTIONS']
  52814. */
  52815. 'CLOSED-CAPTIONS': function CLOSEDCAPTIONS(type, settings) {
  52816. var tech = settings.tech,
  52817. mediaGroups = settings.master.mediaGroups,
  52818. _settings$mediaTypes$3 = settings.mediaTypes[type],
  52819. groups = _settings$mediaTypes$3.groups,
  52820. tracks = _settings$mediaTypes$3.tracks;
  52821. for (var groupId in mediaGroups[type]) {
  52822. if (!groups[groupId]) {
  52823. groups[groupId] = [];
  52824. }
  52825. for (var variantLabel in mediaGroups[type][groupId]) {
  52826. var properties = mediaGroups[type][groupId][variantLabel]; // Look for either 608 (CCn) or 708 (SERVICEn) caption services
  52827. if (!/^(?:CC|SERVICE)/.test(properties.instreamId)) {
  52828. continue;
  52829. }
  52830. var captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  52831. var newProps = {
  52832. label: variantLabel,
  52833. language: properties.language,
  52834. instreamId: properties.instreamId,
  52835. "default": properties["default"] && properties.autoselect
  52836. };
  52837. if (captionServices[newProps.instreamId]) {
  52838. newProps = videojs.mergeOptions(newProps, captionServices[newProps.instreamId]);
  52839. }
  52840. if (newProps["default"] === undefined) {
  52841. delete newProps["default"];
  52842. } // No PlaylistLoader is required for Closed-Captions because the captions are
  52843. // embedded within the video stream
  52844. groups[groupId].push(videojs.mergeOptions({
  52845. id: variantLabel
  52846. }, properties));
  52847. if (typeof tracks[variantLabel] === 'undefined') {
  52848. var track = tech.addRemoteTextTrack({
  52849. id: newProps.instreamId,
  52850. kind: 'captions',
  52851. "default": newProps["default"],
  52852. language: newProps.language,
  52853. label: newProps.label
  52854. }, false).track;
  52855. tracks[variantLabel] = track;
  52856. }
  52857. }
  52858. }
  52859. }
  52860. };
  52861. var groupMatch = function groupMatch(list, media) {
  52862. for (var i = 0; i < list.length; i++) {
  52863. if (playlistMatch(media, list[i])) {
  52864. return true;
  52865. }
  52866. if (list[i].playlists && groupMatch(list[i].playlists, media)) {
  52867. return true;
  52868. }
  52869. }
  52870. return false;
  52871. };
  52872. /**
  52873. * Returns a function used to get the active group of the provided type
  52874. *
  52875. * @param {string} type
  52876. * MediaGroup type
  52877. * @param {Object} settings
  52878. * Object containing required information for media groups
  52879. * @return {Function}
  52880. * Function that returns the active media group for the provided type. Takes an
  52881. * optional parameter {TextTrack} track. If no track is provided, a list of all
  52882. * variants in the group, otherwise the variant corresponding to the provided
  52883. * track is returned.
  52884. * @function activeGroup
  52885. */
  52886. var activeGroup = function activeGroup(type, settings) {
  52887. return function (track) {
  52888. var masterPlaylistLoader = settings.masterPlaylistLoader,
  52889. groups = settings.mediaTypes[type].groups;
  52890. var media = masterPlaylistLoader.media();
  52891. if (!media) {
  52892. return null;
  52893. }
  52894. var variants = null; // set to variants to main media active group
  52895. if (media.attributes[type]) {
  52896. variants = groups[media.attributes[type]];
  52897. }
  52898. var groupKeys = Object.keys(groups);
  52899. if (!variants) {
  52900. // find the masterPlaylistLoader media
  52901. // that is in a media group if we are dealing
  52902. // with audio only
  52903. if (type === 'AUDIO' && groupKeys.length > 1 && isAudioOnly(settings.master)) {
  52904. for (var i = 0; i < groupKeys.length; i++) {
  52905. var groupPropertyList = groups[groupKeys[i]];
  52906. if (groupMatch(groupPropertyList, media)) {
  52907. variants = groupPropertyList;
  52908. break;
  52909. }
  52910. } // use the main group if it exists
  52911. } else if (groups.main) {
  52912. variants = groups.main; // only one group, use that one
  52913. } else if (groupKeys.length === 1) {
  52914. variants = groups[groupKeys[0]];
  52915. }
  52916. }
  52917. if (typeof track === 'undefined') {
  52918. return variants;
  52919. }
  52920. if (track === null || !variants) {
  52921. // An active track was specified so a corresponding group is expected. track === null
  52922. // means no track is currently active so there is no corresponding group
  52923. return null;
  52924. }
  52925. return variants.filter(function (props) {
  52926. return props.id === track.id;
  52927. })[0] || null;
  52928. };
  52929. };
  52930. var activeTrack = {
  52931. /**
  52932. * Returns a function used to get the active track of type provided
  52933. *
  52934. * @param {string} type
  52935. * MediaGroup type
  52936. * @param {Object} settings
  52937. * Object containing required information for media groups
  52938. * @return {Function}
  52939. * Function that returns the active media track for the provided type. Returns
  52940. * null if no track is active
  52941. * @function activeTrack.AUDIO
  52942. */
  52943. AUDIO: function AUDIO(type, settings) {
  52944. return function () {
  52945. var tracks = settings.mediaTypes[type].tracks;
  52946. for (var id in tracks) {
  52947. if (tracks[id].enabled) {
  52948. return tracks[id];
  52949. }
  52950. }
  52951. return null;
  52952. };
  52953. },
  52954. /**
  52955. * Returns a function used to get the active track of type provided
  52956. *
  52957. * @param {string} type
  52958. * MediaGroup type
  52959. * @param {Object} settings
  52960. * Object containing required information for media groups
  52961. * @return {Function}
  52962. * Function that returns the active media track for the provided type. Returns
  52963. * null if no track is active
  52964. * @function activeTrack.SUBTITLES
  52965. */
  52966. SUBTITLES: function SUBTITLES(type, settings) {
  52967. return function () {
  52968. var tracks = settings.mediaTypes[type].tracks;
  52969. for (var id in tracks) {
  52970. if (tracks[id].mode === 'showing' || tracks[id].mode === 'hidden') {
  52971. return tracks[id];
  52972. }
  52973. }
  52974. return null;
  52975. };
  52976. }
  52977. };
  52978. var getActiveGroup = function getActiveGroup(type, _ref) {
  52979. var mediaTypes = _ref.mediaTypes;
  52980. return function () {
  52981. var activeTrack_ = mediaTypes[type].activeTrack();
  52982. if (!activeTrack_) {
  52983. return null;
  52984. }
  52985. return mediaTypes[type].activeGroup(activeTrack_);
  52986. };
  52987. };
  52988. /**
  52989. * Setup PlaylistLoaders and Tracks for media groups (Audio, Subtitles,
  52990. * Closed-Captions) specified in the master manifest.
  52991. *
  52992. * @param {Object} settings
  52993. * Object containing required information for setting up the media groups
  52994. * @param {Tech} settings.tech
  52995. * The tech of the player
  52996. * @param {Object} settings.requestOptions
  52997. * XHR request options used by the segment loaders
  52998. * @param {PlaylistLoader} settings.masterPlaylistLoader
  52999. * PlaylistLoader for the master source
  53000. * @param {VhsHandler} settings.vhs
  53001. * VHS SourceHandler
  53002. * @param {Object} settings.master
  53003. * The parsed master manifest
  53004. * @param {Object} settings.mediaTypes
  53005. * Object to store the loaders, tracks, and utility methods for each media type
  53006. * @param {Function} settings.blacklistCurrentPlaylist
  53007. * Blacklists the current rendition and forces a rendition switch.
  53008. * @function setupMediaGroups
  53009. */
  53010. var setupMediaGroups = function setupMediaGroups(settings) {
  53011. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(function (type) {
  53012. initialize[type](type, settings);
  53013. });
  53014. var mediaTypes = settings.mediaTypes,
  53015. masterPlaylistLoader = settings.masterPlaylistLoader,
  53016. tech = settings.tech,
  53017. vhs = settings.vhs,
  53018. _settings$segmentLoad3 = settings.segmentLoaders,
  53019. audioSegmentLoader = _settings$segmentLoad3['AUDIO'],
  53020. mainSegmentLoader = _settings$segmentLoad3.main; // setup active group and track getters and change event handlers
  53021. ['AUDIO', 'SUBTITLES'].forEach(function (type) {
  53022. mediaTypes[type].activeGroup = activeGroup(type, settings);
  53023. mediaTypes[type].activeTrack = activeTrack[type](type, settings);
  53024. mediaTypes[type].onGroupChanged = onGroupChanged(type, settings);
  53025. mediaTypes[type].onGroupChanging = onGroupChanging(type, settings);
  53026. mediaTypes[type].onTrackChanged = onTrackChanged(type, settings);
  53027. mediaTypes[type].getActiveGroup = getActiveGroup(type, settings);
  53028. }); // DO NOT enable the default subtitle or caption track.
  53029. // DO enable the default audio track
  53030. var audioGroup = mediaTypes.AUDIO.activeGroup();
  53031. if (audioGroup) {
  53032. var groupId = (audioGroup.filter(function (group) {
  53033. return group["default"];
  53034. })[0] || audioGroup[0]).id;
  53035. mediaTypes.AUDIO.tracks[groupId].enabled = true;
  53036. mediaTypes.AUDIO.onGroupChanged();
  53037. mediaTypes.AUDIO.onTrackChanged();
  53038. var activeAudioGroup = mediaTypes.AUDIO.getActiveGroup(); // a similar check for handling setAudio on each loader is run again each time the
  53039. // track is changed, but needs to be handled here since the track may not be considered
  53040. // changed on the first call to onTrackChanged
  53041. if (!activeAudioGroup.playlistLoader) {
  53042. // either audio is muxed with video or the stream is audio only
  53043. mainSegmentLoader.setAudio(true);
  53044. } else {
  53045. // audio is demuxed
  53046. mainSegmentLoader.setAudio(false);
  53047. audioSegmentLoader.setAudio(true);
  53048. }
  53049. }
  53050. masterPlaylistLoader.on('mediachange', function () {
  53051. ['AUDIO', 'SUBTITLES'].forEach(function (type) {
  53052. return mediaTypes[type].onGroupChanged();
  53053. });
  53054. });
  53055. masterPlaylistLoader.on('mediachanging', function () {
  53056. ['AUDIO', 'SUBTITLES'].forEach(function (type) {
  53057. return mediaTypes[type].onGroupChanging();
  53058. });
  53059. }); // custom audio track change event handler for usage event
  53060. var onAudioTrackChanged = function onAudioTrackChanged() {
  53061. mediaTypes.AUDIO.onTrackChanged();
  53062. tech.trigger({
  53063. type: 'usage',
  53064. name: 'vhs-audio-change'
  53065. });
  53066. tech.trigger({
  53067. type: 'usage',
  53068. name: 'hls-audio-change'
  53069. });
  53070. };
  53071. tech.audioTracks().addEventListener('change', onAudioTrackChanged);
  53072. tech.remoteTextTracks().addEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  53073. vhs.on('dispose', function () {
  53074. tech.audioTracks().removeEventListener('change', onAudioTrackChanged);
  53075. tech.remoteTextTracks().removeEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  53076. }); // clear existing audio tracks and add the ones we just created
  53077. tech.clearTracks('audio');
  53078. for (var id in mediaTypes.AUDIO.tracks) {
  53079. tech.audioTracks().addTrack(mediaTypes.AUDIO.tracks[id]);
  53080. }
  53081. };
  53082. /**
  53083. * Creates skeleton object used to store the loaders, tracks, and utility methods for each
  53084. * media type
  53085. *
  53086. * @return {Object}
  53087. * Object to store the loaders, tracks, and utility methods for each media type
  53088. * @function createMediaTypes
  53089. */
  53090. var createMediaTypes = function createMediaTypes() {
  53091. var mediaTypes = {};
  53092. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(function (type) {
  53093. mediaTypes[type] = {
  53094. groups: {},
  53095. tracks: {},
  53096. activePlaylistLoader: null,
  53097. activeGroup: noop,
  53098. activeTrack: noop,
  53099. getActiveGroup: noop,
  53100. onGroupChanged: noop,
  53101. onTrackChanged: noop,
  53102. lastTrack_: null,
  53103. logger_: logger("MediaGroups[" + type + "]")
  53104. };
  53105. });
  53106. return mediaTypes;
  53107. };
  53108. var ABORT_EARLY_BLACKLIST_SECONDS = 60 * 2;
  53109. var Vhs$1; // SegmentLoader stats that need to have each loader's
  53110. // values summed to calculate the final value
  53111. var loaderStats = ['mediaRequests', 'mediaRequestsAborted', 'mediaRequestsTimedout', 'mediaRequestsErrored', 'mediaTransferDuration', 'mediaBytesTransferred', 'mediaAppends'];
  53112. var sumLoaderStat = function sumLoaderStat(stat) {
  53113. return this.audioSegmentLoader_[stat] + this.mainSegmentLoader_[stat];
  53114. };
  53115. var shouldSwitchToMedia = function shouldSwitchToMedia(_ref) {
  53116. var currentPlaylist = _ref.currentPlaylist,
  53117. buffered = _ref.buffered,
  53118. currentTime = _ref.currentTime,
  53119. nextPlaylist = _ref.nextPlaylist,
  53120. bufferLowWaterLine = _ref.bufferLowWaterLine,
  53121. bufferHighWaterLine = _ref.bufferHighWaterLine,
  53122. duration = _ref.duration,
  53123. experimentalBufferBasedABR = _ref.experimentalBufferBasedABR,
  53124. log = _ref.log; // we have no other playlist to switch to
  53125. if (!nextPlaylist) {
  53126. videojs.log.warn('We received no playlist to switch to. Please check your stream.');
  53127. return false;
  53128. }
  53129. var sharedLogLine = "allowing switch " + (currentPlaylist && currentPlaylist.id || 'null') + " -> " + nextPlaylist.id;
  53130. if (!currentPlaylist) {
  53131. log(sharedLogLine + " as current playlist is not set");
  53132. return true;
  53133. } // no need to switch if playlist is the same
  53134. if (nextPlaylist.id === currentPlaylist.id) {
  53135. return false;
  53136. } // determine if current time is in a buffered range.
  53137. var isBuffered = Boolean(findRange(buffered, currentTime).length); // If the playlist is live, then we want to not take low water line into account.
  53138. // This is because in LIVE, the player plays 3 segments from the end of the
  53139. // playlist, and if `BUFFER_LOW_WATER_LINE` is greater than the duration availble
  53140. // in those segments, a viewer will never experience a rendition upswitch.
  53141. if (!currentPlaylist.endList) {
  53142. // For LLHLS live streams, don't switch renditions before playback has started, as it almost
  53143. // doubles the time to first playback.
  53144. if (!isBuffered && typeof currentPlaylist.partTargetDuration === 'number') {
  53145. log("not " + sharedLogLine + " as current playlist is live llhls, but currentTime isn't in buffered.");
  53146. return false;
  53147. }
  53148. log(sharedLogLine + " as current playlist is live");
  53149. return true;
  53150. }
  53151. var forwardBuffer = timeAheadOf(buffered, currentTime);
  53152. var maxBufferLowWaterLine = experimentalBufferBasedABR ? Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE : Config.MAX_BUFFER_LOW_WATER_LINE; // For the same reason as LIVE, we ignore the low water line when the VOD
  53153. // duration is below the max potential low water line
  53154. if (duration < maxBufferLowWaterLine) {
  53155. log(sharedLogLine + " as duration < max low water line (" + duration + " < " + maxBufferLowWaterLine + ")");
  53156. return true;
  53157. }
  53158. var nextBandwidth = nextPlaylist.attributes.BANDWIDTH;
  53159. var currBandwidth = currentPlaylist.attributes.BANDWIDTH; // when switching down, if our buffer is lower than the high water line,
  53160. // we can switch down
  53161. if (nextBandwidth < currBandwidth && (!experimentalBufferBasedABR || forwardBuffer < bufferHighWaterLine)) {
  53162. var logLine = sharedLogLine + " as next bandwidth < current bandwidth (" + nextBandwidth + " < " + currBandwidth + ")";
  53163. if (experimentalBufferBasedABR) {
  53164. logLine += " and forwardBuffer < bufferHighWaterLine (" + forwardBuffer + " < " + bufferHighWaterLine + ")";
  53165. }
  53166. log(logLine);
  53167. return true;
  53168. } // and if our buffer is higher than the low water line,
  53169. // we can switch up
  53170. if ((!experimentalBufferBasedABR || nextBandwidth > currBandwidth) && forwardBuffer >= bufferLowWaterLine) {
  53171. var _logLine = sharedLogLine + " as forwardBuffer >= bufferLowWaterLine (" + forwardBuffer + " >= " + bufferLowWaterLine + ")";
  53172. if (experimentalBufferBasedABR) {
  53173. _logLine += " and next bandwidth > current bandwidth (" + nextBandwidth + " > " + currBandwidth + ")";
  53174. }
  53175. log(_logLine);
  53176. return true;
  53177. }
  53178. log("not " + sharedLogLine + " as no switching criteria met");
  53179. return false;
  53180. };
  53181. /**
  53182. * the master playlist controller controller all interactons
  53183. * between playlists and segmentloaders. At this time this mainly
  53184. * involves a master playlist and a series of audio playlists
  53185. * if they are available
  53186. *
  53187. * @class MasterPlaylistController
  53188. * @extends videojs.EventTarget
  53189. */
  53190. var MasterPlaylistController = /*#__PURE__*/function (_videojs$EventTarget) {
  53191. inheritsLoose(MasterPlaylistController, _videojs$EventTarget);
  53192. function MasterPlaylistController(options) {
  53193. var _this;
  53194. _this = _videojs$EventTarget.call(this) || this;
  53195. var src = options.src,
  53196. handleManifestRedirects = options.handleManifestRedirects,
  53197. withCredentials = options.withCredentials,
  53198. tech = options.tech,
  53199. bandwidth = options.bandwidth,
  53200. externVhs = options.externVhs,
  53201. useCueTags = options.useCueTags,
  53202. blacklistDuration = options.blacklistDuration,
  53203. enableLowInitialPlaylist = options.enableLowInitialPlaylist,
  53204. sourceType = options.sourceType,
  53205. cacheEncryptionKeys = options.cacheEncryptionKeys,
  53206. experimentalBufferBasedABR = options.experimentalBufferBasedABR,
  53207. experimentalLeastPixelDiffSelector = options.experimentalLeastPixelDiffSelector,
  53208. captionServices = options.captionServices;
  53209. if (!src) {
  53210. throw new Error('A non-empty playlist URL or JSON manifest string is required');
  53211. }
  53212. var maxPlaylistRetries = options.maxPlaylistRetries;
  53213. if (maxPlaylistRetries === null || typeof maxPlaylistRetries === 'undefined') {
  53214. maxPlaylistRetries = Infinity;
  53215. }
  53216. Vhs$1 = externVhs;
  53217. _this.experimentalBufferBasedABR = Boolean(experimentalBufferBasedABR);
  53218. _this.experimentalLeastPixelDiffSelector = Boolean(experimentalLeastPixelDiffSelector);
  53219. _this.withCredentials = withCredentials;
  53220. _this.tech_ = tech;
  53221. _this.vhs_ = tech.vhs;
  53222. _this.sourceType_ = sourceType;
  53223. _this.useCueTags_ = useCueTags;
  53224. _this.blacklistDuration = blacklistDuration;
  53225. _this.maxPlaylistRetries = maxPlaylistRetries;
  53226. _this.enableLowInitialPlaylist = enableLowInitialPlaylist;
  53227. if (_this.useCueTags_) {
  53228. _this.cueTagsTrack_ = _this.tech_.addTextTrack('metadata', 'ad-cues');
  53229. _this.cueTagsTrack_.inBandMetadataTrackDispatchType = '';
  53230. }
  53231. _this.requestOptions_ = {
  53232. withCredentials: withCredentials,
  53233. handleManifestRedirects: handleManifestRedirects,
  53234. maxPlaylistRetries: maxPlaylistRetries,
  53235. timeout: null
  53236. };
  53237. _this.on('error', _this.pauseLoading);
  53238. _this.mediaTypes_ = createMediaTypes();
  53239. _this.mediaSource = new window.MediaSource();
  53240. _this.handleDurationChange_ = _this.handleDurationChange_.bind(assertThisInitialized(_this));
  53241. _this.handleSourceOpen_ = _this.handleSourceOpen_.bind(assertThisInitialized(_this));
  53242. _this.handleSourceEnded_ = _this.handleSourceEnded_.bind(assertThisInitialized(_this));
  53243. _this.mediaSource.addEventListener('durationchange', _this.handleDurationChange_); // load the media source into the player
  53244. _this.mediaSource.addEventListener('sourceopen', _this.handleSourceOpen_);
  53245. _this.mediaSource.addEventListener('sourceended', _this.handleSourceEnded_); // we don't have to handle sourceclose since dispose will handle termination of
  53246. // everything, and the MediaSource should not be detached without a proper disposal
  53247. _this.seekable_ = videojs.createTimeRanges();
  53248. _this.hasPlayed_ = false;
  53249. _this.syncController_ = new SyncController(options);
  53250. _this.segmentMetadataTrack_ = tech.addRemoteTextTrack({
  53251. kind: 'metadata',
  53252. label: 'segment-metadata'
  53253. }, false).track;
  53254. _this.decrypter_ = new Decrypter();
  53255. _this.sourceUpdater_ = new SourceUpdater(_this.mediaSource);
  53256. _this.inbandTextTracks_ = {};
  53257. _this.timelineChangeController_ = new TimelineChangeController();
  53258. var segmentLoaderSettings = {
  53259. vhs: _this.vhs_,
  53260. parse708captions: options.parse708captions,
  53261. useDtsForTimestampOffset: options.useDtsForTimestampOffset,
  53262. captionServices: captionServices,
  53263. mediaSource: _this.mediaSource,
  53264. currentTime: _this.tech_.currentTime.bind(_this.tech_),
  53265. seekable: function seekable() {
  53266. return _this.seekable();
  53267. },
  53268. seeking: function seeking() {
  53269. return _this.tech_.seeking();
  53270. },
  53271. duration: function duration() {
  53272. return _this.duration();
  53273. },
  53274. hasPlayed: function hasPlayed() {
  53275. return _this.hasPlayed_;
  53276. },
  53277. goalBufferLength: function goalBufferLength() {
  53278. return _this.goalBufferLength();
  53279. },
  53280. bandwidth: bandwidth,
  53281. syncController: _this.syncController_,
  53282. decrypter: _this.decrypter_,
  53283. sourceType: _this.sourceType_,
  53284. inbandTextTracks: _this.inbandTextTracks_,
  53285. cacheEncryptionKeys: cacheEncryptionKeys,
  53286. sourceUpdater: _this.sourceUpdater_,
  53287. timelineChangeController: _this.timelineChangeController_,
  53288. experimentalExactManifestTimings: options.experimentalExactManifestTimings
  53289. }; // The source type check not only determines whether a special DASH playlist loader
  53290. // should be used, but also covers the case where the provided src is a vhs-json
  53291. // manifest object (instead of a URL). In the case of vhs-json, the default
  53292. // PlaylistLoader should be used.
  53293. _this.masterPlaylistLoader_ = _this.sourceType_ === 'dash' ? new DashPlaylistLoader(src, _this.vhs_, _this.requestOptions_) : new PlaylistLoader(src, _this.vhs_, _this.requestOptions_);
  53294. _this.setupMasterPlaylistLoaderListeners_(); // setup segment loaders
  53295. // combined audio/video or just video when alternate audio track is selected
  53296. _this.mainSegmentLoader_ = new SegmentLoader(videojs.mergeOptions(segmentLoaderSettings, {
  53297. segmentMetadataTrack: _this.segmentMetadataTrack_,
  53298. loaderType: 'main'
  53299. }), options); // alternate audio track
  53300. _this.audioSegmentLoader_ = new SegmentLoader(videojs.mergeOptions(segmentLoaderSettings, {
  53301. loaderType: 'audio'
  53302. }), options);
  53303. _this.subtitleSegmentLoader_ = new VTTSegmentLoader(videojs.mergeOptions(segmentLoaderSettings, {
  53304. loaderType: 'vtt',
  53305. featuresNativeTextTracks: _this.tech_.featuresNativeTextTracks,
  53306. loadVttJs: function loadVttJs() {
  53307. return new Promise(function (resolve, reject) {
  53308. function onLoad() {
  53309. tech.off('vttjserror', onError);
  53310. resolve();
  53311. }
  53312. function onError() {
  53313. tech.off('vttjsloaded', onLoad);
  53314. reject();
  53315. }
  53316. tech.one('vttjsloaded', onLoad);
  53317. tech.one('vttjserror', onError); // safe to call multiple times, script will be loaded only once:
  53318. tech.addWebVttScript_();
  53319. });
  53320. }
  53321. }), options);
  53322. _this.setupSegmentLoaderListeners_();
  53323. if (_this.experimentalBufferBasedABR) {
  53324. _this.masterPlaylistLoader_.one('loadedplaylist', function () {
  53325. return _this.startABRTimer_();
  53326. });
  53327. _this.tech_.on('pause', function () {
  53328. return _this.stopABRTimer_();
  53329. });
  53330. _this.tech_.on('play', function () {
  53331. return _this.startABRTimer_();
  53332. });
  53333. } // Create SegmentLoader stat-getters
  53334. // mediaRequests_
  53335. // mediaRequestsAborted_
  53336. // mediaRequestsTimedout_
  53337. // mediaRequestsErrored_
  53338. // mediaTransferDuration_
  53339. // mediaBytesTransferred_
  53340. // mediaAppends_
  53341. loaderStats.forEach(function (stat) {
  53342. _this[stat + '_'] = sumLoaderStat.bind(assertThisInitialized(_this), stat);
  53343. });
  53344. _this.logger_ = logger('MPC');
  53345. _this.triggeredFmp4Usage = false;
  53346. if (_this.tech_.preload() === 'none') {
  53347. _this.loadOnPlay_ = function () {
  53348. _this.loadOnPlay_ = null;
  53349. _this.masterPlaylistLoader_.load();
  53350. };
  53351. _this.tech_.one('play', _this.loadOnPlay_);
  53352. } else {
  53353. _this.masterPlaylistLoader_.load();
  53354. }
  53355. _this.timeToLoadedData__ = -1;
  53356. _this.mainAppendsToLoadedData__ = -1;
  53357. _this.audioAppendsToLoadedData__ = -1;
  53358. var event = _this.tech_.preload() === 'none' ? 'play' : 'loadstart'; // start the first frame timer on loadstart or play (for preload none)
  53359. _this.tech_.one(event, function () {
  53360. var timeToLoadedDataStart = Date.now();
  53361. _this.tech_.one('loadeddata', function () {
  53362. _this.timeToLoadedData__ = Date.now() - timeToLoadedDataStart;
  53363. _this.mainAppendsToLoadedData__ = _this.mainSegmentLoader_.mediaAppends;
  53364. _this.audioAppendsToLoadedData__ = _this.audioSegmentLoader_.mediaAppends;
  53365. });
  53366. });
  53367. return _this;
  53368. }
  53369. var _proto = MasterPlaylistController.prototype;
  53370. _proto.mainAppendsToLoadedData_ = function mainAppendsToLoadedData_() {
  53371. return this.mainAppendsToLoadedData__;
  53372. };
  53373. _proto.audioAppendsToLoadedData_ = function audioAppendsToLoadedData_() {
  53374. return this.audioAppendsToLoadedData__;
  53375. };
  53376. _proto.appendsToLoadedData_ = function appendsToLoadedData_() {
  53377. var main = this.mainAppendsToLoadedData_();
  53378. var audio = this.audioAppendsToLoadedData_();
  53379. if (main === -1 || audio === -1) {
  53380. return -1;
  53381. }
  53382. return main + audio;
  53383. };
  53384. _proto.timeToLoadedData_ = function timeToLoadedData_() {
  53385. return this.timeToLoadedData__;
  53386. }
  53387. /**
  53388. * Run selectPlaylist and switch to the new playlist if we should
  53389. *
  53390. * @param {string} [reason=abr] a reason for why the ABR check is made
  53391. * @private
  53392. */
  53393. ;
  53394. _proto.checkABR_ = function checkABR_(reason) {
  53395. if (reason === void 0) {
  53396. reason = 'abr';
  53397. }
  53398. var nextPlaylist = this.selectPlaylist();
  53399. if (nextPlaylist && this.shouldSwitchToMedia_(nextPlaylist)) {
  53400. this.switchMedia_(nextPlaylist, reason);
  53401. }
  53402. };
  53403. _proto.switchMedia_ = function switchMedia_(playlist, cause, delay) {
  53404. var oldMedia = this.media();
  53405. var oldId = oldMedia && (oldMedia.id || oldMedia.uri);
  53406. var newId = playlist.id || playlist.uri;
  53407. if (oldId && oldId !== newId) {
  53408. this.logger_("switch media " + oldId + " -> " + newId + " from " + cause);
  53409. this.tech_.trigger({
  53410. type: 'usage',
  53411. name: "vhs-rendition-change-" + cause
  53412. });
  53413. }
  53414. this.masterPlaylistLoader_.media(playlist, delay);
  53415. }
  53416. /**
  53417. * Start a timer that periodically calls checkABR_
  53418. *
  53419. * @private
  53420. */
  53421. ;
  53422. _proto.startABRTimer_ = function startABRTimer_() {
  53423. var _this2 = this;
  53424. this.stopABRTimer_();
  53425. this.abrTimer_ = window.setInterval(function () {
  53426. return _this2.checkABR_();
  53427. }, 250);
  53428. }
  53429. /**
  53430. * Stop the timer that periodically calls checkABR_
  53431. *
  53432. * @private
  53433. */
  53434. ;
  53435. _proto.stopABRTimer_ = function stopABRTimer_() {
  53436. // if we're scrubbing, we don't need to pause.
  53437. // This getter will be added to Video.js in version 7.11.
  53438. if (this.tech_.scrubbing && this.tech_.scrubbing()) {
  53439. return;
  53440. }
  53441. window.clearInterval(this.abrTimer_);
  53442. this.abrTimer_ = null;
  53443. }
  53444. /**
  53445. * Get a list of playlists for the currently selected audio playlist
  53446. *
  53447. * @return {Array} the array of audio playlists
  53448. */
  53449. ;
  53450. _proto.getAudioTrackPlaylists_ = function getAudioTrackPlaylists_() {
  53451. var master = this.master();
  53452. var defaultPlaylists = master && master.playlists || []; // if we don't have any audio groups then we can only
  53453. // assume that the audio tracks are contained in masters
  53454. // playlist array, use that or an empty array.
  53455. if (!master || !master.mediaGroups || !master.mediaGroups.AUDIO) {
  53456. return defaultPlaylists;
  53457. }
  53458. var AUDIO = master.mediaGroups.AUDIO;
  53459. var groupKeys = Object.keys(AUDIO);
  53460. var track; // get the current active track
  53461. if (Object.keys(this.mediaTypes_.AUDIO.groups).length) {
  53462. track = this.mediaTypes_.AUDIO.activeTrack(); // or get the default track from master if mediaTypes_ isn't setup yet
  53463. } else {
  53464. // default group is `main` or just the first group.
  53465. var defaultGroup = AUDIO.main || groupKeys.length && AUDIO[groupKeys[0]];
  53466. for (var label in defaultGroup) {
  53467. if (defaultGroup[label]["default"]) {
  53468. track = {
  53469. label: label
  53470. };
  53471. break;
  53472. }
  53473. }
  53474. } // no active track no playlists.
  53475. if (!track) {
  53476. return defaultPlaylists;
  53477. }
  53478. var playlists = []; // get all of the playlists that are possible for the
  53479. // active track.
  53480. for (var group in AUDIO) {
  53481. if (AUDIO[group][track.label]) {
  53482. var properties = AUDIO[group][track.label];
  53483. if (properties.playlists && properties.playlists.length) {
  53484. playlists.push.apply(playlists, properties.playlists);
  53485. } else if (properties.uri) {
  53486. playlists.push(properties);
  53487. } else if (master.playlists.length) {
  53488. // if an audio group does not have a uri
  53489. // see if we have main playlists that use it as a group.
  53490. // if we do then add those to the playlists list.
  53491. for (var i = 0; i < master.playlists.length; i++) {
  53492. var playlist = master.playlists[i];
  53493. if (playlist.attributes && playlist.attributes.AUDIO && playlist.attributes.AUDIO === group) {
  53494. playlists.push(playlist);
  53495. }
  53496. }
  53497. }
  53498. }
  53499. }
  53500. if (!playlists.length) {
  53501. return defaultPlaylists;
  53502. }
  53503. return playlists;
  53504. }
  53505. /**
  53506. * Register event handlers on the master playlist loader. A helper
  53507. * function for construction time.
  53508. *
  53509. * @private
  53510. */
  53511. ;
  53512. _proto.setupMasterPlaylistLoaderListeners_ = function setupMasterPlaylistLoaderListeners_() {
  53513. var _this3 = this;
  53514. this.masterPlaylistLoader_.on('loadedmetadata', function () {
  53515. var media = _this3.masterPlaylistLoader_.media();
  53516. var requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  53517. // timeout the request.
  53518. if (isLowestEnabledRendition(_this3.masterPlaylistLoader_.master, _this3.masterPlaylistLoader_.media())) {
  53519. _this3.requestOptions_.timeout = 0;
  53520. } else {
  53521. _this3.requestOptions_.timeout = requestTimeout;
  53522. } // if this isn't a live video and preload permits, start
  53523. // downloading segments
  53524. if (media.endList && _this3.tech_.preload() !== 'none') {
  53525. _this3.mainSegmentLoader_.playlist(media, _this3.requestOptions_);
  53526. _this3.mainSegmentLoader_.load();
  53527. }
  53528. setupMediaGroups({
  53529. sourceType: _this3.sourceType_,
  53530. segmentLoaders: {
  53531. AUDIO: _this3.audioSegmentLoader_,
  53532. SUBTITLES: _this3.subtitleSegmentLoader_,
  53533. main: _this3.mainSegmentLoader_
  53534. },
  53535. tech: _this3.tech_,
  53536. requestOptions: _this3.requestOptions_,
  53537. masterPlaylistLoader: _this3.masterPlaylistLoader_,
  53538. vhs: _this3.vhs_,
  53539. master: _this3.master(),
  53540. mediaTypes: _this3.mediaTypes_,
  53541. blacklistCurrentPlaylist: _this3.blacklistCurrentPlaylist.bind(_this3)
  53542. });
  53543. _this3.triggerPresenceUsage_(_this3.master(), media);
  53544. _this3.setupFirstPlay();
  53545. if (!_this3.mediaTypes_.AUDIO.activePlaylistLoader || _this3.mediaTypes_.AUDIO.activePlaylistLoader.media()) {
  53546. _this3.trigger('selectedinitialmedia');
  53547. } else {
  53548. // We must wait for the active audio playlist loader to
  53549. // finish setting up before triggering this event so the
  53550. // representations API and EME setup is correct
  53551. _this3.mediaTypes_.AUDIO.activePlaylistLoader.one('loadedmetadata', function () {
  53552. _this3.trigger('selectedinitialmedia');
  53553. });
  53554. }
  53555. });
  53556. this.masterPlaylistLoader_.on('loadedplaylist', function () {
  53557. if (_this3.loadOnPlay_) {
  53558. _this3.tech_.off('play', _this3.loadOnPlay_);
  53559. }
  53560. var updatedPlaylist = _this3.masterPlaylistLoader_.media();
  53561. if (!updatedPlaylist) {
  53562. // exclude any variants that are not supported by the browser before selecting
  53563. // an initial media as the playlist selectors do not consider browser support
  53564. _this3.excludeUnsupportedVariants_();
  53565. var selectedMedia;
  53566. if (_this3.enableLowInitialPlaylist) {
  53567. selectedMedia = _this3.selectInitialPlaylist();
  53568. }
  53569. if (!selectedMedia) {
  53570. selectedMedia = _this3.selectPlaylist();
  53571. }
  53572. if (!selectedMedia || !_this3.shouldSwitchToMedia_(selectedMedia)) {
  53573. return;
  53574. }
  53575. _this3.initialMedia_ = selectedMedia;
  53576. _this3.switchMedia_(_this3.initialMedia_, 'initial'); // Under the standard case where a source URL is provided, loadedplaylist will
  53577. // fire again since the playlist will be requested. In the case of vhs-json
  53578. // (where the manifest object is provided as the source), when the media
  53579. // playlist's `segments` list is already available, a media playlist won't be
  53580. // requested, and loadedplaylist won't fire again, so the playlist handler must be
  53581. // called on its own here.
  53582. var haveJsonSource = _this3.sourceType_ === 'vhs-json' && _this3.initialMedia_.segments;
  53583. if (!haveJsonSource) {
  53584. return;
  53585. }
  53586. updatedPlaylist = _this3.initialMedia_;
  53587. }
  53588. _this3.handleUpdatedMediaPlaylist(updatedPlaylist);
  53589. });
  53590. this.masterPlaylistLoader_.on('error', function () {
  53591. _this3.blacklistCurrentPlaylist(_this3.masterPlaylistLoader_.error);
  53592. });
  53593. this.masterPlaylistLoader_.on('mediachanging', function () {
  53594. _this3.mainSegmentLoader_.abort();
  53595. _this3.mainSegmentLoader_.pause();
  53596. });
  53597. this.masterPlaylistLoader_.on('mediachange', function () {
  53598. var media = _this3.masterPlaylistLoader_.media();
  53599. var requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  53600. // timeout the request.
  53601. if (isLowestEnabledRendition(_this3.masterPlaylistLoader_.master, _this3.masterPlaylistLoader_.media())) {
  53602. _this3.requestOptions_.timeout = 0;
  53603. } else {
  53604. _this3.requestOptions_.timeout = requestTimeout;
  53605. }
  53606. _this3.masterPlaylistLoader_.load(); // TODO: Create a new event on the PlaylistLoader that signals
  53607. // that the segments have changed in some way and use that to
  53608. // update the SegmentLoader instead of doing it twice here and
  53609. // on `loadedplaylist`
  53610. _this3.mainSegmentLoader_.playlist(media, _this3.requestOptions_);
  53611. _this3.mainSegmentLoader_.load();
  53612. _this3.tech_.trigger({
  53613. type: 'mediachange',
  53614. bubbles: true
  53615. });
  53616. });
  53617. this.masterPlaylistLoader_.on('playlistunchanged', function () {
  53618. var updatedPlaylist = _this3.masterPlaylistLoader_.media(); // ignore unchanged playlists that have already been
  53619. // excluded for not-changing. We likely just have a really slowly updating
  53620. // playlist.
  53621. if (updatedPlaylist.lastExcludeReason_ === 'playlist-unchanged') {
  53622. return;
  53623. }
  53624. var playlistOutdated = _this3.stuckAtPlaylistEnd_(updatedPlaylist);
  53625. if (playlistOutdated) {
  53626. // Playlist has stopped updating and we're stuck at its end. Try to
  53627. // blacklist it and switch to another playlist in the hope that that
  53628. // one is updating (and give the player a chance to re-adjust to the
  53629. // safe live point).
  53630. _this3.blacklistCurrentPlaylist({
  53631. message: 'Playlist no longer updating.',
  53632. reason: 'playlist-unchanged'
  53633. }); // useful for monitoring QoS
  53634. _this3.tech_.trigger('playliststuck');
  53635. }
  53636. });
  53637. this.masterPlaylistLoader_.on('renditiondisabled', function () {
  53638. _this3.tech_.trigger({
  53639. type: 'usage',
  53640. name: 'vhs-rendition-disabled'
  53641. });
  53642. _this3.tech_.trigger({
  53643. type: 'usage',
  53644. name: 'hls-rendition-disabled'
  53645. });
  53646. });
  53647. this.masterPlaylistLoader_.on('renditionenabled', function () {
  53648. _this3.tech_.trigger({
  53649. type: 'usage',
  53650. name: 'vhs-rendition-enabled'
  53651. });
  53652. _this3.tech_.trigger({
  53653. type: 'usage',
  53654. name: 'hls-rendition-enabled'
  53655. });
  53656. });
  53657. }
  53658. /**
  53659. * Given an updated media playlist (whether it was loaded for the first time, or
  53660. * refreshed for live playlists), update any relevant properties and state to reflect
  53661. * changes in the media that should be accounted for (e.g., cues and duration).
  53662. *
  53663. * @param {Object} updatedPlaylist the updated media playlist object
  53664. *
  53665. * @private
  53666. */
  53667. ;
  53668. _proto.handleUpdatedMediaPlaylist = function handleUpdatedMediaPlaylist(updatedPlaylist) {
  53669. if (this.useCueTags_) {
  53670. this.updateAdCues_(updatedPlaylist);
  53671. } // TODO: Create a new event on the PlaylistLoader that signals
  53672. // that the segments have changed in some way and use that to
  53673. // update the SegmentLoader instead of doing it twice here and
  53674. // on `mediachange`
  53675. this.mainSegmentLoader_.playlist(updatedPlaylist, this.requestOptions_);
  53676. this.updateDuration(!updatedPlaylist.endList); // If the player isn't paused, ensure that the segment loader is running,
  53677. // as it is possible that it was temporarily stopped while waiting for
  53678. // a playlist (e.g., in case the playlist errored and we re-requested it).
  53679. if (!this.tech_.paused()) {
  53680. this.mainSegmentLoader_.load();
  53681. if (this.audioSegmentLoader_) {
  53682. this.audioSegmentLoader_.load();
  53683. }
  53684. }
  53685. }
  53686. /**
  53687. * A helper function for triggerring presence usage events once per source
  53688. *
  53689. * @private
  53690. */
  53691. ;
  53692. _proto.triggerPresenceUsage_ = function triggerPresenceUsage_(master, media) {
  53693. var mediaGroups = master.mediaGroups || {};
  53694. var defaultDemuxed = true;
  53695. var audioGroupKeys = Object.keys(mediaGroups.AUDIO);
  53696. for (var mediaGroup in mediaGroups.AUDIO) {
  53697. for (var label in mediaGroups.AUDIO[mediaGroup]) {
  53698. var properties = mediaGroups.AUDIO[mediaGroup][label];
  53699. if (!properties.uri) {
  53700. defaultDemuxed = false;
  53701. }
  53702. }
  53703. }
  53704. if (defaultDemuxed) {
  53705. this.tech_.trigger({
  53706. type: 'usage',
  53707. name: 'vhs-demuxed'
  53708. });
  53709. this.tech_.trigger({
  53710. type: 'usage',
  53711. name: 'hls-demuxed'
  53712. });
  53713. }
  53714. if (Object.keys(mediaGroups.SUBTITLES).length) {
  53715. this.tech_.trigger({
  53716. type: 'usage',
  53717. name: 'vhs-webvtt'
  53718. });
  53719. this.tech_.trigger({
  53720. type: 'usage',
  53721. name: 'hls-webvtt'
  53722. });
  53723. }
  53724. if (Vhs$1.Playlist.isAes(media)) {
  53725. this.tech_.trigger({
  53726. type: 'usage',
  53727. name: 'vhs-aes'
  53728. });
  53729. this.tech_.trigger({
  53730. type: 'usage',
  53731. name: 'hls-aes'
  53732. });
  53733. }
  53734. if (audioGroupKeys.length && Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length > 1) {
  53735. this.tech_.trigger({
  53736. type: 'usage',
  53737. name: 'vhs-alternate-audio'
  53738. });
  53739. this.tech_.trigger({
  53740. type: 'usage',
  53741. name: 'hls-alternate-audio'
  53742. });
  53743. }
  53744. if (this.useCueTags_) {
  53745. this.tech_.trigger({
  53746. type: 'usage',
  53747. name: 'vhs-playlist-cue-tags'
  53748. });
  53749. this.tech_.trigger({
  53750. type: 'usage',
  53751. name: 'hls-playlist-cue-tags'
  53752. });
  53753. }
  53754. };
  53755. _proto.shouldSwitchToMedia_ = function shouldSwitchToMedia_(nextPlaylist) {
  53756. var currentPlaylist = this.masterPlaylistLoader_.media() || this.masterPlaylistLoader_.pendingMedia_;
  53757. var currentTime = this.tech_.currentTime();
  53758. var bufferLowWaterLine = this.bufferLowWaterLine();
  53759. var bufferHighWaterLine = this.bufferHighWaterLine();
  53760. var buffered = this.tech_.buffered();
  53761. return shouldSwitchToMedia({
  53762. buffered: buffered,
  53763. currentTime: currentTime,
  53764. currentPlaylist: currentPlaylist,
  53765. nextPlaylist: nextPlaylist,
  53766. bufferLowWaterLine: bufferLowWaterLine,
  53767. bufferHighWaterLine: bufferHighWaterLine,
  53768. duration: this.duration(),
  53769. experimentalBufferBasedABR: this.experimentalBufferBasedABR,
  53770. log: this.logger_
  53771. });
  53772. }
  53773. /**
  53774. * Register event handlers on the segment loaders. A helper function
  53775. * for construction time.
  53776. *
  53777. * @private
  53778. */
  53779. ;
  53780. _proto.setupSegmentLoaderListeners_ = function setupSegmentLoaderListeners_() {
  53781. var _this4 = this;
  53782. this.mainSegmentLoader_.on('bandwidthupdate', function () {
  53783. // Whether or not buffer based ABR or another ABR is used, on a bandwidth change it's
  53784. // useful to check to see if a rendition switch should be made.
  53785. _this4.checkABR_('bandwidthupdate');
  53786. _this4.tech_.trigger('bandwidthupdate');
  53787. });
  53788. this.mainSegmentLoader_.on('timeout', function () {
  53789. if (_this4.experimentalBufferBasedABR) {
  53790. // If a rendition change is needed, then it would've be done on `bandwidthupdate`.
  53791. // Here the only consideration is that for buffer based ABR there's no guarantee
  53792. // of an immediate switch (since the bandwidth is averaged with a timeout
  53793. // bandwidth value of 1), so force a load on the segment loader to keep it going.
  53794. _this4.mainSegmentLoader_.load();
  53795. }
  53796. }); // `progress` events are not reliable enough of a bandwidth measure to trigger buffer
  53797. // based ABR.
  53798. if (!this.experimentalBufferBasedABR) {
  53799. this.mainSegmentLoader_.on('progress', function () {
  53800. _this4.trigger('progress');
  53801. });
  53802. }
  53803. this.mainSegmentLoader_.on('error', function () {
  53804. _this4.blacklistCurrentPlaylist(_this4.mainSegmentLoader_.error());
  53805. });
  53806. this.mainSegmentLoader_.on('appenderror', function () {
  53807. _this4.error = _this4.mainSegmentLoader_.error_;
  53808. _this4.trigger('error');
  53809. });
  53810. this.mainSegmentLoader_.on('syncinfoupdate', function () {
  53811. _this4.onSyncInfoUpdate_();
  53812. });
  53813. this.mainSegmentLoader_.on('timestampoffset', function () {
  53814. _this4.tech_.trigger({
  53815. type: 'usage',
  53816. name: 'vhs-timestamp-offset'
  53817. });
  53818. _this4.tech_.trigger({
  53819. type: 'usage',
  53820. name: 'hls-timestamp-offset'
  53821. });
  53822. });
  53823. this.audioSegmentLoader_.on('syncinfoupdate', function () {
  53824. _this4.onSyncInfoUpdate_();
  53825. });
  53826. this.audioSegmentLoader_.on('appenderror', function () {
  53827. _this4.error = _this4.audioSegmentLoader_.error_;
  53828. _this4.trigger('error');
  53829. });
  53830. this.mainSegmentLoader_.on('ended', function () {
  53831. _this4.logger_('main segment loader ended');
  53832. _this4.onEndOfStream();
  53833. });
  53834. this.mainSegmentLoader_.on('earlyabort', function (event) {
  53835. // never try to early abort with the new ABR algorithm
  53836. if (_this4.experimentalBufferBasedABR) {
  53837. return;
  53838. }
  53839. _this4.delegateLoaders_('all', ['abort']);
  53840. _this4.blacklistCurrentPlaylist({
  53841. message: 'Aborted early because there isn\'t enough bandwidth to complete the ' + 'request without rebuffering.'
  53842. }, ABORT_EARLY_BLACKLIST_SECONDS);
  53843. });
  53844. var updateCodecs = function updateCodecs() {
  53845. if (!_this4.sourceUpdater_.hasCreatedSourceBuffers()) {
  53846. return _this4.tryToCreateSourceBuffers_();
  53847. }
  53848. var codecs = _this4.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  53849. if (!codecs) {
  53850. return;
  53851. }
  53852. _this4.sourceUpdater_.addOrChangeSourceBuffers(codecs);
  53853. };
  53854. this.mainSegmentLoader_.on('trackinfo', updateCodecs);
  53855. this.audioSegmentLoader_.on('trackinfo', updateCodecs);
  53856. this.mainSegmentLoader_.on('fmp4', function () {
  53857. if (!_this4.triggeredFmp4Usage) {
  53858. _this4.tech_.trigger({
  53859. type: 'usage',
  53860. name: 'vhs-fmp4'
  53861. });
  53862. _this4.tech_.trigger({
  53863. type: 'usage',
  53864. name: 'hls-fmp4'
  53865. });
  53866. _this4.triggeredFmp4Usage = true;
  53867. }
  53868. });
  53869. this.audioSegmentLoader_.on('fmp4', function () {
  53870. if (!_this4.triggeredFmp4Usage) {
  53871. _this4.tech_.trigger({
  53872. type: 'usage',
  53873. name: 'vhs-fmp4'
  53874. });
  53875. _this4.tech_.trigger({
  53876. type: 'usage',
  53877. name: 'hls-fmp4'
  53878. });
  53879. _this4.triggeredFmp4Usage = true;
  53880. }
  53881. });
  53882. this.audioSegmentLoader_.on('ended', function () {
  53883. _this4.logger_('audioSegmentLoader ended');
  53884. _this4.onEndOfStream();
  53885. });
  53886. };
  53887. _proto.mediaSecondsLoaded_ = function mediaSecondsLoaded_() {
  53888. return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded + this.mainSegmentLoader_.mediaSecondsLoaded);
  53889. }
  53890. /**
  53891. * Call load on our SegmentLoaders
  53892. */
  53893. ;
  53894. _proto.load = function load() {
  53895. this.mainSegmentLoader_.load();
  53896. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  53897. this.audioSegmentLoader_.load();
  53898. }
  53899. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  53900. this.subtitleSegmentLoader_.load();
  53901. }
  53902. }
  53903. /**
  53904. * Re-tune playback quality level for the current player
  53905. * conditions without performing destructive actions, like
  53906. * removing already buffered content
  53907. *
  53908. * @private
  53909. * @deprecated
  53910. */
  53911. ;
  53912. _proto.smoothQualityChange_ = function smoothQualityChange_(media) {
  53913. if (media === void 0) {
  53914. media = this.selectPlaylist();
  53915. }
  53916. this.fastQualityChange_(media);
  53917. }
  53918. /**
  53919. * Re-tune playback quality level for the current player
  53920. * conditions. This method will perform destructive actions like removing
  53921. * already buffered content in order to readjust the currently active
  53922. * playlist quickly. This is good for manual quality changes
  53923. *
  53924. * @private
  53925. */
  53926. ;
  53927. _proto.fastQualityChange_ = function fastQualityChange_(media) {
  53928. var _this5 = this;
  53929. if (media === void 0) {
  53930. media = this.selectPlaylist();
  53931. }
  53932. if (media === this.masterPlaylistLoader_.media()) {
  53933. this.logger_('skipping fastQualityChange because new media is same as old');
  53934. return;
  53935. }
  53936. this.switchMedia_(media, 'fast-quality'); // Delete all buffered data to allow an immediate quality switch, then seek to give
  53937. // the browser a kick to remove any cached frames from the previous rendtion (.04 seconds
  53938. // ahead is roughly the minimum that will accomplish this across a variety of content
  53939. // in IE and Edge, but seeking in place is sufficient on all other browsers)
  53940. // Edge/IE bug: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14600375/
  53941. // Chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=651904
  53942. this.mainSegmentLoader_.resetEverything(function () {
  53943. // Since this is not a typical seek, we avoid the seekTo method which can cause segments
  53944. // from the previously enabled rendition to load before the new playlist has finished loading
  53945. if (videojs.browser.IE_VERSION || videojs.browser.IS_EDGE) {
  53946. _this5.tech_.setCurrentTime(_this5.tech_.currentTime() + 0.04);
  53947. } else {
  53948. _this5.tech_.setCurrentTime(_this5.tech_.currentTime());
  53949. }
  53950. }); // don't need to reset audio as it is reset when media changes
  53951. }
  53952. /**
  53953. * Begin playback.
  53954. */
  53955. ;
  53956. _proto.play = function play() {
  53957. if (this.setupFirstPlay()) {
  53958. return;
  53959. }
  53960. if (this.tech_.ended()) {
  53961. this.tech_.setCurrentTime(0);
  53962. }
  53963. if (this.hasPlayed_) {
  53964. this.load();
  53965. }
  53966. var seekable = this.tech_.seekable(); // if the viewer has paused and we fell out of the live window,
  53967. // seek forward to the live point
  53968. if (this.tech_.duration() === Infinity) {
  53969. if (this.tech_.currentTime() < seekable.start(0)) {
  53970. return this.tech_.setCurrentTime(seekable.end(seekable.length - 1));
  53971. }
  53972. }
  53973. }
  53974. /**
  53975. * Seek to the latest media position if this is a live video and the
  53976. * player and video are loaded and initialized.
  53977. */
  53978. ;
  53979. _proto.setupFirstPlay = function setupFirstPlay() {
  53980. var _this6 = this;
  53981. var media = this.masterPlaylistLoader_.media(); // Check that everything is ready to begin buffering for the first call to play
  53982. // If 1) there is no active media
  53983. // 2) the player is paused
  53984. // 3) the first play has already been setup
  53985. // then exit early
  53986. if (!media || this.tech_.paused() || this.hasPlayed_) {
  53987. return false;
  53988. } // when the video is a live stream
  53989. if (!media.endList) {
  53990. var seekable = this.seekable();
  53991. if (!seekable.length) {
  53992. // without a seekable range, the player cannot seek to begin buffering at the live
  53993. // point
  53994. return false;
  53995. }
  53996. if (videojs.browser.IE_VERSION && this.tech_.readyState() === 0) {
  53997. // IE11 throws an InvalidStateError if you try to set currentTime while the
  53998. // readyState is 0, so it must be delayed until the tech fires loadedmetadata.
  53999. this.tech_.one('loadedmetadata', function () {
  54000. _this6.trigger('firstplay');
  54001. _this6.tech_.setCurrentTime(seekable.end(0));
  54002. _this6.hasPlayed_ = true;
  54003. });
  54004. return false;
  54005. } // trigger firstplay to inform the source handler to ignore the next seek event
  54006. this.trigger('firstplay'); // seek to the live point
  54007. this.tech_.setCurrentTime(seekable.end(0));
  54008. }
  54009. this.hasPlayed_ = true; // we can begin loading now that everything is ready
  54010. this.load();
  54011. return true;
  54012. }
  54013. /**
  54014. * handle the sourceopen event on the MediaSource
  54015. *
  54016. * @private
  54017. */
  54018. ;
  54019. _proto.handleSourceOpen_ = function handleSourceOpen_() {
  54020. // Only attempt to create the source buffer if none already exist.
  54021. // handleSourceOpen is also called when we are "re-opening" a source buffer
  54022. // after `endOfStream` has been called (in response to a seek for instance)
  54023. this.tryToCreateSourceBuffers_(); // if autoplay is enabled, begin playback. This is duplicative of
  54024. // code in video.js but is required because play() must be invoked
  54025. // *after* the media source has opened.
  54026. if (this.tech_.autoplay()) {
  54027. var playPromise = this.tech_.play(); // Catch/silence error when a pause interrupts a play request
  54028. // on browsers which return a promise
  54029. if (typeof playPromise !== 'undefined' && typeof playPromise.then === 'function') {
  54030. playPromise.then(null, function (e) {});
  54031. }
  54032. }
  54033. this.trigger('sourceopen');
  54034. }
  54035. /**
  54036. * handle the sourceended event on the MediaSource
  54037. *
  54038. * @private
  54039. */
  54040. ;
  54041. _proto.handleSourceEnded_ = function handleSourceEnded_() {
  54042. if (!this.inbandTextTracks_.metadataTrack_) {
  54043. return;
  54044. }
  54045. var cues = this.inbandTextTracks_.metadataTrack_.cues;
  54046. if (!cues || !cues.length) {
  54047. return;
  54048. }
  54049. var duration = this.duration();
  54050. cues[cues.length - 1].endTime = isNaN(duration) || Math.abs(duration) === Infinity ? Number.MAX_VALUE : duration;
  54051. }
  54052. /**
  54053. * handle the durationchange event on the MediaSource
  54054. *
  54055. * @private
  54056. */
  54057. ;
  54058. _proto.handleDurationChange_ = function handleDurationChange_() {
  54059. this.tech_.trigger('durationchange');
  54060. }
  54061. /**
  54062. * Calls endOfStream on the media source when all active stream types have called
  54063. * endOfStream
  54064. *
  54065. * @param {string} streamType
  54066. * Stream type of the segment loader that called endOfStream
  54067. * @private
  54068. */
  54069. ;
  54070. _proto.onEndOfStream = function onEndOfStream() {
  54071. var isEndOfStream = this.mainSegmentLoader_.ended_;
  54072. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  54073. var mainMediaInfo = this.mainSegmentLoader_.getCurrentMediaInfo_(); // if the audio playlist loader exists, then alternate audio is active
  54074. if (!mainMediaInfo || mainMediaInfo.hasVideo) {
  54075. // if we do not know if the main segment loader contains video yet or if we
  54076. // definitively know the main segment loader contains video, then we need to wait
  54077. // for both main and audio segment loaders to call endOfStream
  54078. isEndOfStream = isEndOfStream && this.audioSegmentLoader_.ended_;
  54079. } else {
  54080. // otherwise just rely on the audio loader
  54081. isEndOfStream = this.audioSegmentLoader_.ended_;
  54082. }
  54083. }
  54084. if (!isEndOfStream) {
  54085. return;
  54086. }
  54087. this.stopABRTimer_();
  54088. this.sourceUpdater_.endOfStream();
  54089. }
  54090. /**
  54091. * Check if a playlist has stopped being updated
  54092. *
  54093. * @param {Object} playlist the media playlist object
  54094. * @return {boolean} whether the playlist has stopped being updated or not
  54095. */
  54096. ;
  54097. _proto.stuckAtPlaylistEnd_ = function stuckAtPlaylistEnd_(playlist) {
  54098. var seekable = this.seekable();
  54099. if (!seekable.length) {
  54100. // playlist doesn't have enough information to determine whether we are stuck
  54101. return false;
  54102. }
  54103. var expired = this.syncController_.getExpiredTime(playlist, this.duration());
  54104. if (expired === null) {
  54105. return false;
  54106. } // does not use the safe live end to calculate playlist end, since we
  54107. // don't want to say we are stuck while there is still content
  54108. var absolutePlaylistEnd = Vhs$1.Playlist.playlistEnd(playlist, expired);
  54109. var currentTime = this.tech_.currentTime();
  54110. var buffered = this.tech_.buffered();
  54111. if (!buffered.length) {
  54112. // return true if the playhead reached the absolute end of the playlist
  54113. return absolutePlaylistEnd - currentTime <= SAFE_TIME_DELTA;
  54114. }
  54115. var bufferedEnd = buffered.end(buffered.length - 1); // return true if there is too little buffer left and buffer has reached absolute
  54116. // end of playlist
  54117. return bufferedEnd - currentTime <= SAFE_TIME_DELTA && absolutePlaylistEnd - bufferedEnd <= SAFE_TIME_DELTA;
  54118. }
  54119. /**
  54120. * Blacklists a playlist when an error occurs for a set amount of time
  54121. * making it unavailable for selection by the rendition selection algorithm
  54122. * and then forces a new playlist (rendition) selection.
  54123. *
  54124. * @param {Object=} error an optional error that may include the playlist
  54125. * to blacklist
  54126. * @param {number=} blacklistDuration an optional number of seconds to blacklist the
  54127. * playlist
  54128. */
  54129. ;
  54130. _proto.blacklistCurrentPlaylist = function blacklistCurrentPlaylist(error, blacklistDuration) {
  54131. if (error === void 0) {
  54132. error = {};
  54133. } // If the `error` was generated by the playlist loader, it will contain
  54134. // the playlist we were trying to load (but failed) and that should be
  54135. // blacklisted instead of the currently selected playlist which is likely
  54136. // out-of-date in this scenario
  54137. var currentPlaylist = error.playlist || this.masterPlaylistLoader_.media();
  54138. blacklistDuration = blacklistDuration || error.blacklistDuration || this.blacklistDuration; // If there is no current playlist, then an error occurred while we were
  54139. // trying to load the master OR while we were disposing of the tech
  54140. if (!currentPlaylist) {
  54141. this.error = error;
  54142. if (this.mediaSource.readyState !== 'open') {
  54143. this.trigger('error');
  54144. } else {
  54145. this.sourceUpdater_.endOfStream('network');
  54146. }
  54147. return;
  54148. }
  54149. currentPlaylist.playlistErrors_++;
  54150. var playlists = this.masterPlaylistLoader_.master.playlists;
  54151. var enabledPlaylists = playlists.filter(isEnabled);
  54152. var isFinalRendition = enabledPlaylists.length === 1 && enabledPlaylists[0] === currentPlaylist; // Don't blacklist the only playlist unless it was blacklisted
  54153. // forever
  54154. if (playlists.length === 1 && blacklistDuration !== Infinity) {
  54155. videojs.log.warn("Problem encountered with playlist " + currentPlaylist.id + ". " + 'Trying again since it is the only playlist.');
  54156. this.tech_.trigger('retryplaylist'); // if this is a final rendition, we should delay
  54157. return this.masterPlaylistLoader_.load(isFinalRendition);
  54158. }
  54159. if (isFinalRendition) {
  54160. // Since we're on the final non-blacklisted playlist, and we're about to blacklist
  54161. // it, instead of erring the player or retrying this playlist, clear out the current
  54162. // blacklist. This allows other playlists to be attempted in case any have been
  54163. // fixed.
  54164. var reincluded = false;
  54165. playlists.forEach(function (playlist) {
  54166. // skip current playlist which is about to be blacklisted
  54167. if (playlist === currentPlaylist) {
  54168. return;
  54169. }
  54170. var excludeUntil = playlist.excludeUntil; // a playlist cannot be reincluded if it wasn't excluded to begin with.
  54171. if (typeof excludeUntil !== 'undefined' && excludeUntil !== Infinity) {
  54172. reincluded = true;
  54173. delete playlist.excludeUntil;
  54174. }
  54175. });
  54176. if (reincluded) {
  54177. videojs.log.warn('Removing other playlists from the exclusion list because the last ' + 'rendition is about to be excluded.'); // Technically we are retrying a playlist, in that we are simply retrying a previous
  54178. // playlist. This is needed for users relying on the retryplaylist event to catch a
  54179. // case where the player might be stuck and looping through "dead" playlists.
  54180. this.tech_.trigger('retryplaylist');
  54181. }
  54182. } // Blacklist this playlist
  54183. var excludeUntil;
  54184. if (currentPlaylist.playlistErrors_ > this.maxPlaylistRetries) {
  54185. excludeUntil = Infinity;
  54186. } else {
  54187. excludeUntil = Date.now() + blacklistDuration * 1000;
  54188. }
  54189. currentPlaylist.excludeUntil = excludeUntil;
  54190. if (error.reason) {
  54191. currentPlaylist.lastExcludeReason_ = error.reason;
  54192. }
  54193. this.tech_.trigger('blacklistplaylist');
  54194. this.tech_.trigger({
  54195. type: 'usage',
  54196. name: 'vhs-rendition-blacklisted'
  54197. });
  54198. this.tech_.trigger({
  54199. type: 'usage',
  54200. name: 'hls-rendition-blacklisted'
  54201. }); // TODO: should we select a new playlist if this blacklist wasn't for the currentPlaylist?
  54202. // Would be something like media().id !=== currentPlaylist.id and we would need something
  54203. // like `pendingMedia` in playlist loaders to check against that too. This will prevent us
  54204. // from loading a new playlist on any blacklist.
  54205. // Select a new playlist
  54206. var nextPlaylist = this.selectPlaylist();
  54207. if (!nextPlaylist) {
  54208. this.error = 'Playback cannot continue. No available working or supported playlists.';
  54209. this.trigger('error');
  54210. return;
  54211. }
  54212. var logFn = error.internal ? this.logger_ : videojs.log.warn;
  54213. var errorMessage = error.message ? ' ' + error.message : '';
  54214. logFn((error.internal ? 'Internal problem' : 'Problem') + " encountered with playlist " + currentPlaylist.id + "." + (errorMessage + " Switching to playlist " + nextPlaylist.id + ".")); // if audio group changed reset audio loaders
  54215. if (nextPlaylist.attributes.AUDIO !== currentPlaylist.attributes.AUDIO) {
  54216. this.delegateLoaders_('audio', ['abort', 'pause']);
  54217. } // if subtitle group changed reset subtitle loaders
  54218. if (nextPlaylist.attributes.SUBTITLES !== currentPlaylist.attributes.SUBTITLES) {
  54219. this.delegateLoaders_('subtitle', ['abort', 'pause']);
  54220. }
  54221. this.delegateLoaders_('main', ['abort', 'pause']);
  54222. var delayDuration = nextPlaylist.targetDuration / 2 * 1000 || 5 * 1000;
  54223. var shouldDelay = typeof nextPlaylist.lastRequest === 'number' && Date.now() - nextPlaylist.lastRequest <= delayDuration; // delay if it's a final rendition or if the last refresh is sooner than half targetDuration
  54224. return this.switchMedia_(nextPlaylist, 'exclude', isFinalRendition || shouldDelay);
  54225. }
  54226. /**
  54227. * Pause all segment/playlist loaders
  54228. */
  54229. ;
  54230. _proto.pauseLoading = function pauseLoading() {
  54231. this.delegateLoaders_('all', ['abort', 'pause']);
  54232. this.stopABRTimer_();
  54233. }
  54234. /**
  54235. * Call a set of functions in order on playlist loaders, segment loaders,
  54236. * or both types of loaders.
  54237. *
  54238. * @param {string} filter
  54239. * Filter loaders that should call fnNames using a string. Can be:
  54240. * * all - run on all loaders
  54241. * * audio - run on all audio loaders
  54242. * * subtitle - run on all subtitle loaders
  54243. * * main - run on the main/master loaders
  54244. *
  54245. * @param {Array|string} fnNames
  54246. * A string or array of function names to call.
  54247. */
  54248. ;
  54249. _proto.delegateLoaders_ = function delegateLoaders_(filter, fnNames) {
  54250. var _this7 = this;
  54251. var loaders = [];
  54252. var dontFilterPlaylist = filter === 'all';
  54253. if (dontFilterPlaylist || filter === 'main') {
  54254. loaders.push(this.masterPlaylistLoader_);
  54255. }
  54256. var mediaTypes = [];
  54257. if (dontFilterPlaylist || filter === 'audio') {
  54258. mediaTypes.push('AUDIO');
  54259. }
  54260. if (dontFilterPlaylist || filter === 'subtitle') {
  54261. mediaTypes.push('CLOSED-CAPTIONS');
  54262. mediaTypes.push('SUBTITLES');
  54263. }
  54264. mediaTypes.forEach(function (mediaType) {
  54265. var loader = _this7.mediaTypes_[mediaType] && _this7.mediaTypes_[mediaType].activePlaylistLoader;
  54266. if (loader) {
  54267. loaders.push(loader);
  54268. }
  54269. });
  54270. ['main', 'audio', 'subtitle'].forEach(function (name) {
  54271. var loader = _this7[name + "SegmentLoader_"];
  54272. if (loader && (filter === name || filter === 'all')) {
  54273. loaders.push(loader);
  54274. }
  54275. });
  54276. loaders.forEach(function (loader) {
  54277. return fnNames.forEach(function (fnName) {
  54278. if (typeof loader[fnName] === 'function') {
  54279. loader[fnName]();
  54280. }
  54281. });
  54282. });
  54283. }
  54284. /**
  54285. * set the current time on all segment loaders
  54286. *
  54287. * @param {TimeRange} currentTime the current time to set
  54288. * @return {TimeRange} the current time
  54289. */
  54290. ;
  54291. _proto.setCurrentTime = function setCurrentTime(currentTime) {
  54292. var buffered = findRange(this.tech_.buffered(), currentTime);
  54293. if (!(this.masterPlaylistLoader_ && this.masterPlaylistLoader_.media())) {
  54294. // return immediately if the metadata is not ready yet
  54295. return 0;
  54296. } // it's clearly an edge-case but don't thrown an error if asked to
  54297. // seek within an empty playlist
  54298. if (!this.masterPlaylistLoader_.media().segments) {
  54299. return 0;
  54300. } // if the seek location is already buffered, continue buffering as usual
  54301. if (buffered && buffered.length) {
  54302. return currentTime;
  54303. } // cancel outstanding requests so we begin buffering at the new
  54304. // location
  54305. this.mainSegmentLoader_.resetEverything();
  54306. this.mainSegmentLoader_.abort();
  54307. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  54308. this.audioSegmentLoader_.resetEverything();
  54309. this.audioSegmentLoader_.abort();
  54310. }
  54311. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  54312. this.subtitleSegmentLoader_.resetEverything();
  54313. this.subtitleSegmentLoader_.abort();
  54314. } // start segment loader loading in case they are paused
  54315. this.load();
  54316. }
  54317. /**
  54318. * get the current duration
  54319. *
  54320. * @return {TimeRange} the duration
  54321. */
  54322. ;
  54323. _proto.duration = function duration() {
  54324. if (!this.masterPlaylistLoader_) {
  54325. return 0;
  54326. }
  54327. var media = this.masterPlaylistLoader_.media();
  54328. if (!media) {
  54329. // no playlists loaded yet, so can't determine a duration
  54330. return 0;
  54331. } // Don't rely on the media source for duration in the case of a live playlist since
  54332. // setting the native MediaSource's duration to infinity ends up with consequences to
  54333. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  54334. //
  54335. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  54336. // however, few browsers have support for setLiveSeekableRange()
  54337. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  54338. //
  54339. // Until a time when the duration of the media source can be set to infinity, and a
  54340. // seekable range specified across browsers, just return Infinity.
  54341. if (!media.endList) {
  54342. return Infinity;
  54343. } // Since this is a VOD video, it is safe to rely on the media source's duration (if
  54344. // available). If it's not available, fall back to a playlist-calculated estimate.
  54345. if (this.mediaSource) {
  54346. return this.mediaSource.duration;
  54347. }
  54348. return Vhs$1.Playlist.duration(media);
  54349. }
  54350. /**
  54351. * check the seekable range
  54352. *
  54353. * @return {TimeRange} the seekable range
  54354. */
  54355. ;
  54356. _proto.seekable = function seekable() {
  54357. return this.seekable_;
  54358. };
  54359. _proto.onSyncInfoUpdate_ = function onSyncInfoUpdate_() {
  54360. var audioSeekable; // TODO check for creation of both source buffers before updating seekable
  54361. //
  54362. // A fix was made to this function where a check for
  54363. // this.sourceUpdater_.hasCreatedSourceBuffers
  54364. // was added to ensure that both source buffers were created before seekable was
  54365. // updated. However, it originally had a bug where it was checking for a true and
  54366. // returning early instead of checking for false. Setting it to check for false to
  54367. // return early though created other issues. A call to play() would check for seekable
  54368. // end without verifying that a seekable range was present. In addition, even checking
  54369. // for that didn't solve some issues, as handleFirstPlay is sometimes worked around
  54370. // due to a media update calling load on the segment loaders, skipping a seek to live,
  54371. // thereby starting live streams at the beginning of the stream rather than at the end.
  54372. //
  54373. // This conditional should be fixed to wait for the creation of two source buffers at
  54374. // the same time as the other sections of code are fixed to properly seek to live and
  54375. // not throw an error due to checking for a seekable end when no seekable range exists.
  54376. //
  54377. // For now, fall back to the older behavior, with the understanding that the seekable
  54378. // range may not be completely correct, leading to a suboptimal initial live point.
  54379. if (!this.masterPlaylistLoader_) {
  54380. return;
  54381. }
  54382. var media = this.masterPlaylistLoader_.media();
  54383. if (!media) {
  54384. return;
  54385. }
  54386. var expired = this.syncController_.getExpiredTime(media, this.duration());
  54387. if (expired === null) {
  54388. // not enough information to update seekable
  54389. return;
  54390. }
  54391. var master = this.masterPlaylistLoader_.master;
  54392. var mainSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(master, media));
  54393. if (mainSeekable.length === 0) {
  54394. return;
  54395. }
  54396. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  54397. media = this.mediaTypes_.AUDIO.activePlaylistLoader.media();
  54398. expired = this.syncController_.getExpiredTime(media, this.duration());
  54399. if (expired === null) {
  54400. return;
  54401. }
  54402. audioSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(master, media));
  54403. if (audioSeekable.length === 0) {
  54404. return;
  54405. }
  54406. }
  54407. var oldEnd;
  54408. var oldStart;
  54409. if (this.seekable_ && this.seekable_.length) {
  54410. oldEnd = this.seekable_.end(0);
  54411. oldStart = this.seekable_.start(0);
  54412. }
  54413. if (!audioSeekable) {
  54414. // seekable has been calculated based on buffering video data so it
  54415. // can be returned directly
  54416. this.seekable_ = mainSeekable;
  54417. } else if (audioSeekable.start(0) > mainSeekable.end(0) || mainSeekable.start(0) > audioSeekable.end(0)) {
  54418. // seekables are pretty far off, rely on main
  54419. this.seekable_ = mainSeekable;
  54420. } else {
  54421. this.seekable_ = videojs.createTimeRanges([[audioSeekable.start(0) > mainSeekable.start(0) ? audioSeekable.start(0) : mainSeekable.start(0), audioSeekable.end(0) < mainSeekable.end(0) ? audioSeekable.end(0) : mainSeekable.end(0)]]);
  54422. } // seekable is the same as last time
  54423. if (this.seekable_ && this.seekable_.length) {
  54424. if (this.seekable_.end(0) === oldEnd && this.seekable_.start(0) === oldStart) {
  54425. return;
  54426. }
  54427. }
  54428. this.logger_("seekable updated [" + printableRange(this.seekable_) + "]");
  54429. this.tech_.trigger('seekablechanged');
  54430. }
  54431. /**
  54432. * Update the player duration
  54433. */
  54434. ;
  54435. _proto.updateDuration = function updateDuration(isLive) {
  54436. if (this.updateDuration_) {
  54437. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  54438. this.updateDuration_ = null;
  54439. }
  54440. if (this.mediaSource.readyState !== 'open') {
  54441. this.updateDuration_ = this.updateDuration.bind(this, isLive);
  54442. this.mediaSource.addEventListener('sourceopen', this.updateDuration_);
  54443. return;
  54444. }
  54445. if (isLive) {
  54446. var seekable = this.seekable();
  54447. if (!seekable.length) {
  54448. return;
  54449. } // Even in the case of a live playlist, the native MediaSource's duration should not
  54450. // be set to Infinity (even though this would be expected for a live playlist), since
  54451. // setting the native MediaSource's duration to infinity ends up with consequences to
  54452. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  54453. //
  54454. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  54455. // however, few browsers have support for setLiveSeekableRange()
  54456. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  54457. //
  54458. // Until a time when the duration of the media source can be set to infinity, and a
  54459. // seekable range specified across browsers, the duration should be greater than or
  54460. // equal to the last possible seekable value.
  54461. // MediaSource duration starts as NaN
  54462. // It is possible (and probable) that this case will never be reached for many
  54463. // sources, since the MediaSource reports duration as the highest value without
  54464. // accounting for timestamp offset. For example, if the timestamp offset is -100 and
  54465. // we buffered times 0 to 100 with real times of 100 to 200, even though current
  54466. // time will be between 0 and 100, the native media source may report the duration
  54467. // as 200. However, since we report duration separate from the media source (as
  54468. // Infinity), and as long as the native media source duration value is greater than
  54469. // our reported seekable range, seeks will work as expected. The large number as
  54470. // duration for live is actually a strategy used by some players to work around the
  54471. // issue of live seekable ranges cited above.
  54472. if (isNaN(this.mediaSource.duration) || this.mediaSource.duration < seekable.end(seekable.length - 1)) {
  54473. this.sourceUpdater_.setDuration(seekable.end(seekable.length - 1));
  54474. }
  54475. return;
  54476. }
  54477. var buffered = this.tech_.buffered();
  54478. var duration = Vhs$1.Playlist.duration(this.masterPlaylistLoader_.media());
  54479. if (buffered.length > 0) {
  54480. duration = Math.max(duration, buffered.end(buffered.length - 1));
  54481. }
  54482. if (this.mediaSource.duration !== duration) {
  54483. this.sourceUpdater_.setDuration(duration);
  54484. }
  54485. }
  54486. /**
  54487. * dispose of the MasterPlaylistController and everything
  54488. * that it controls
  54489. */
  54490. ;
  54491. _proto.dispose = function dispose() {
  54492. var _this8 = this;
  54493. this.trigger('dispose');
  54494. this.decrypter_.terminate();
  54495. this.masterPlaylistLoader_.dispose();
  54496. this.mainSegmentLoader_.dispose();
  54497. if (this.loadOnPlay_) {
  54498. this.tech_.off('play', this.loadOnPlay_);
  54499. }
  54500. ['AUDIO', 'SUBTITLES'].forEach(function (type) {
  54501. var groups = _this8.mediaTypes_[type].groups;
  54502. for (var id in groups) {
  54503. groups[id].forEach(function (group) {
  54504. if (group.playlistLoader) {
  54505. group.playlistLoader.dispose();
  54506. }
  54507. });
  54508. }
  54509. });
  54510. this.audioSegmentLoader_.dispose();
  54511. this.subtitleSegmentLoader_.dispose();
  54512. this.sourceUpdater_.dispose();
  54513. this.timelineChangeController_.dispose();
  54514. this.stopABRTimer_();
  54515. if (this.updateDuration_) {
  54516. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  54517. }
  54518. this.mediaSource.removeEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  54519. this.mediaSource.removeEventListener('sourceopen', this.handleSourceOpen_);
  54520. this.mediaSource.removeEventListener('sourceended', this.handleSourceEnded_);
  54521. this.off();
  54522. }
  54523. /**
  54524. * return the master playlist object if we have one
  54525. *
  54526. * @return {Object} the master playlist object that we parsed
  54527. */
  54528. ;
  54529. _proto.master = function master() {
  54530. return this.masterPlaylistLoader_.master;
  54531. }
  54532. /**
  54533. * return the currently selected playlist
  54534. *
  54535. * @return {Object} the currently selected playlist object that we parsed
  54536. */
  54537. ;
  54538. _proto.media = function media() {
  54539. // playlist loader will not return media if it has not been fully loaded
  54540. return this.masterPlaylistLoader_.media() || this.initialMedia_;
  54541. };
  54542. _proto.areMediaTypesKnown_ = function areMediaTypesKnown_() {
  54543. var usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  54544. var hasMainMediaInfo = !!this.mainSegmentLoader_.getCurrentMediaInfo_(); // if we are not using an audio loader, then we have audio media info
  54545. // otherwise check on the segment loader.
  54546. var hasAudioMediaInfo = !usingAudioLoader ? true : !!this.audioSegmentLoader_.getCurrentMediaInfo_(); // one or both loaders has not loaded sufficently to get codecs
  54547. if (!hasMainMediaInfo || !hasAudioMediaInfo) {
  54548. return false;
  54549. }
  54550. return true;
  54551. };
  54552. _proto.getCodecsOrExclude_ = function getCodecsOrExclude_() {
  54553. var _this9 = this;
  54554. var media = {
  54555. main: this.mainSegmentLoader_.getCurrentMediaInfo_() || {},
  54556. audio: this.audioSegmentLoader_.getCurrentMediaInfo_() || {}
  54557. };
  54558. var playlist = this.mainSegmentLoader_.getPendingSegmentPlaylist() || this.media(); // set "main" media equal to video
  54559. media.video = media.main;
  54560. var playlistCodecs = codecsForPlaylist(this.master(), playlist);
  54561. var codecs = {};
  54562. var usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  54563. if (media.main.hasVideo) {
  54564. codecs.video = playlistCodecs.video || media.main.videoCodec || DEFAULT_VIDEO_CODEC;
  54565. }
  54566. if (media.main.isMuxed) {
  54567. codecs.video += "," + (playlistCodecs.audio || media.main.audioCodec || DEFAULT_AUDIO_CODEC);
  54568. }
  54569. if (media.main.hasAudio && !media.main.isMuxed || media.audio.hasAudio || usingAudioLoader) {
  54570. codecs.audio = playlistCodecs.audio || media.main.audioCodec || media.audio.audioCodec || DEFAULT_AUDIO_CODEC; // set audio isFmp4 so we use the correct "supports" function below
  54571. media.audio.isFmp4 = media.main.hasAudio && !media.main.isMuxed ? media.main.isFmp4 : media.audio.isFmp4;
  54572. } // no codecs, no playback.
  54573. if (!codecs.audio && !codecs.video) {
  54574. this.blacklistCurrentPlaylist({
  54575. playlist: playlist,
  54576. message: 'Could not determine codecs for playlist.',
  54577. blacklistDuration: Infinity
  54578. });
  54579. return;
  54580. } // fmp4 relies on browser support, while ts relies on muxer support
  54581. var supportFunction = function supportFunction(isFmp4, codec) {
  54582. return isFmp4 ? browserSupportsCodec(codec) : muxerSupportsCodec(codec);
  54583. };
  54584. var unsupportedCodecs = {};
  54585. var unsupportedAudio;
  54586. ['video', 'audio'].forEach(function (type) {
  54587. if (codecs.hasOwnProperty(type) && !supportFunction(media[type].isFmp4, codecs[type])) {
  54588. var supporter = media[type].isFmp4 ? 'browser' : 'muxer';
  54589. unsupportedCodecs[supporter] = unsupportedCodecs[supporter] || [];
  54590. unsupportedCodecs[supporter].push(codecs[type]);
  54591. if (type === 'audio') {
  54592. unsupportedAudio = supporter;
  54593. }
  54594. }
  54595. });
  54596. if (usingAudioLoader && unsupportedAudio && playlist.attributes.AUDIO) {
  54597. var audioGroup = playlist.attributes.AUDIO;
  54598. this.master().playlists.forEach(function (variant) {
  54599. var variantAudioGroup = variant.attributes && variant.attributes.AUDIO;
  54600. if (variantAudioGroup === audioGroup && variant !== playlist) {
  54601. variant.excludeUntil = Infinity;
  54602. }
  54603. });
  54604. this.logger_("excluding audio group " + audioGroup + " as " + unsupportedAudio + " does not support codec(s): \"" + codecs.audio + "\"");
  54605. } // if we have any unsupported codecs blacklist this playlist.
  54606. if (Object.keys(unsupportedCodecs).length) {
  54607. var message = Object.keys(unsupportedCodecs).reduce(function (acc, supporter) {
  54608. if (acc) {
  54609. acc += ', ';
  54610. }
  54611. acc += supporter + " does not support codec(s): \"" + unsupportedCodecs[supporter].join(',') + "\"";
  54612. return acc;
  54613. }, '') + '.';
  54614. this.blacklistCurrentPlaylist({
  54615. playlist: playlist,
  54616. internal: true,
  54617. message: message,
  54618. blacklistDuration: Infinity
  54619. });
  54620. return;
  54621. } // check if codec switching is happening
  54622. if (this.sourceUpdater_.hasCreatedSourceBuffers() && !this.sourceUpdater_.canChangeType()) {
  54623. var switchMessages = [];
  54624. ['video', 'audio'].forEach(function (type) {
  54625. var newCodec = (parseCodecs(_this9.sourceUpdater_.codecs[type] || '')[0] || {}).type;
  54626. var oldCodec = (parseCodecs(codecs[type] || '')[0] || {}).type;
  54627. if (newCodec && oldCodec && newCodec.toLowerCase() !== oldCodec.toLowerCase()) {
  54628. switchMessages.push("\"" + _this9.sourceUpdater_.codecs[type] + "\" -> \"" + codecs[type] + "\"");
  54629. }
  54630. });
  54631. if (switchMessages.length) {
  54632. this.blacklistCurrentPlaylist({
  54633. playlist: playlist,
  54634. message: "Codec switching not supported: " + switchMessages.join(', ') + ".",
  54635. blacklistDuration: Infinity,
  54636. internal: true
  54637. });
  54638. return;
  54639. }
  54640. } // TODO: when using the muxer shouldn't we just return
  54641. // the codecs that the muxer outputs?
  54642. return codecs;
  54643. }
  54644. /**
  54645. * Create source buffers and exlude any incompatible renditions.
  54646. *
  54647. * @private
  54648. */
  54649. ;
  54650. _proto.tryToCreateSourceBuffers_ = function tryToCreateSourceBuffers_() {
  54651. // media source is not ready yet or sourceBuffers are already
  54652. // created.
  54653. if (this.mediaSource.readyState !== 'open' || this.sourceUpdater_.hasCreatedSourceBuffers()) {
  54654. return;
  54655. }
  54656. if (!this.areMediaTypesKnown_()) {
  54657. return;
  54658. }
  54659. var codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  54660. if (!codecs) {
  54661. return;
  54662. }
  54663. this.sourceUpdater_.createSourceBuffers(codecs);
  54664. var codecString = [codecs.video, codecs.audio].filter(Boolean).join(',');
  54665. this.excludeIncompatibleVariants_(codecString);
  54666. }
  54667. /**
  54668. * Excludes playlists with codecs that are unsupported by the muxer and browser.
  54669. */
  54670. ;
  54671. _proto.excludeUnsupportedVariants_ = function excludeUnsupportedVariants_() {
  54672. var _this10 = this;
  54673. var playlists = this.master().playlists;
  54674. var ids = []; // TODO: why don't we have a property to loop through all
  54675. // playlist? Why did we ever mix indexes and keys?
  54676. Object.keys(playlists).forEach(function (key) {
  54677. var variant = playlists[key]; // check if we already processed this playlist.
  54678. if (ids.indexOf(variant.id) !== -1) {
  54679. return;
  54680. }
  54681. ids.push(variant.id);
  54682. var codecs = codecsForPlaylist(_this10.master, variant);
  54683. var unsupported = [];
  54684. if (codecs.audio && !muxerSupportsCodec(codecs.audio) && !browserSupportsCodec(codecs.audio)) {
  54685. unsupported.push("audio codec " + codecs.audio);
  54686. }
  54687. if (codecs.video && !muxerSupportsCodec(codecs.video) && !browserSupportsCodec(codecs.video)) {
  54688. unsupported.push("video codec " + codecs.video);
  54689. }
  54690. if (codecs.text && codecs.text === 'stpp.ttml.im1t') {
  54691. unsupported.push("text codec " + codecs.text);
  54692. }
  54693. if (unsupported.length) {
  54694. variant.excludeUntil = Infinity;
  54695. _this10.logger_("excluding " + variant.id + " for unsupported: " + unsupported.join(', '));
  54696. }
  54697. });
  54698. }
  54699. /**
  54700. * Blacklist playlists that are known to be codec or
  54701. * stream-incompatible with the SourceBuffer configuration. For
  54702. * instance, Media Source Extensions would cause the video element to
  54703. * stall waiting for video data if you switched from a variant with
  54704. * video and audio to an audio-only one.
  54705. *
  54706. * @param {Object} media a media playlist compatible with the current
  54707. * set of SourceBuffers. Variants in the current master playlist that
  54708. * do not appear to have compatible codec or stream configurations
  54709. * will be excluded from the default playlist selection algorithm
  54710. * indefinitely.
  54711. * @private
  54712. */
  54713. ;
  54714. _proto.excludeIncompatibleVariants_ = function excludeIncompatibleVariants_(codecString) {
  54715. var _this11 = this;
  54716. var ids = [];
  54717. var playlists = this.master().playlists;
  54718. var codecs = unwrapCodecList(parseCodecs(codecString));
  54719. var codecCount_ = codecCount(codecs);
  54720. var videoDetails = codecs.video && parseCodecs(codecs.video)[0] || null;
  54721. var audioDetails = codecs.audio && parseCodecs(codecs.audio)[0] || null;
  54722. Object.keys(playlists).forEach(function (key) {
  54723. var variant = playlists[key]; // check if we already processed this playlist.
  54724. // or it if it is already excluded forever.
  54725. if (ids.indexOf(variant.id) !== -1 || variant.excludeUntil === Infinity) {
  54726. return;
  54727. }
  54728. ids.push(variant.id);
  54729. var blacklistReasons = []; // get codecs from the playlist for this variant
  54730. var variantCodecs = codecsForPlaylist(_this11.masterPlaylistLoader_.master, variant);
  54731. var variantCodecCount = codecCount(variantCodecs); // if no codecs are listed, we cannot determine that this
  54732. // variant is incompatible. Wait for mux.js to probe
  54733. if (!variantCodecs.audio && !variantCodecs.video) {
  54734. return;
  54735. } // TODO: we can support this by removing the
  54736. // old media source and creating a new one, but it will take some work.
  54737. // The number of streams cannot change
  54738. if (variantCodecCount !== codecCount_) {
  54739. blacklistReasons.push("codec count \"" + variantCodecCount + "\" !== \"" + codecCount_ + "\"");
  54740. } // only exclude playlists by codec change, if codecs cannot switch
  54741. // during playback.
  54742. if (!_this11.sourceUpdater_.canChangeType()) {
  54743. var variantVideoDetails = variantCodecs.video && parseCodecs(variantCodecs.video)[0] || null;
  54744. var variantAudioDetails = variantCodecs.audio && parseCodecs(variantCodecs.audio)[0] || null; // the video codec cannot change
  54745. if (variantVideoDetails && videoDetails && variantVideoDetails.type.toLowerCase() !== videoDetails.type.toLowerCase()) {
  54746. blacklistReasons.push("video codec \"" + variantVideoDetails.type + "\" !== \"" + videoDetails.type + "\"");
  54747. } // the audio codec cannot change
  54748. if (variantAudioDetails && audioDetails && variantAudioDetails.type.toLowerCase() !== audioDetails.type.toLowerCase()) {
  54749. blacklistReasons.push("audio codec \"" + variantAudioDetails.type + "\" !== \"" + audioDetails.type + "\"");
  54750. }
  54751. }
  54752. if (blacklistReasons.length) {
  54753. variant.excludeUntil = Infinity;
  54754. _this11.logger_("blacklisting " + variant.id + ": " + blacklistReasons.join(' && '));
  54755. }
  54756. });
  54757. };
  54758. _proto.updateAdCues_ = function updateAdCues_(media) {
  54759. var offset = 0;
  54760. var seekable = this.seekable();
  54761. if (seekable.length) {
  54762. offset = seekable.start(0);
  54763. }
  54764. updateAdCues(media, this.cueTagsTrack_, offset);
  54765. }
  54766. /**
  54767. * Calculates the desired forward buffer length based on current time
  54768. *
  54769. * @return {number} Desired forward buffer length in seconds
  54770. */
  54771. ;
  54772. _proto.goalBufferLength = function goalBufferLength() {
  54773. var currentTime = this.tech_.currentTime();
  54774. var initial = Config.GOAL_BUFFER_LENGTH;
  54775. var rate = Config.GOAL_BUFFER_LENGTH_RATE;
  54776. var max = Math.max(initial, Config.MAX_GOAL_BUFFER_LENGTH);
  54777. return Math.min(initial + currentTime * rate, max);
  54778. }
  54779. /**
  54780. * Calculates the desired buffer low water line based on current time
  54781. *
  54782. * @return {number} Desired buffer low water line in seconds
  54783. */
  54784. ;
  54785. _proto.bufferLowWaterLine = function bufferLowWaterLine() {
  54786. var currentTime = this.tech_.currentTime();
  54787. var initial = Config.BUFFER_LOW_WATER_LINE;
  54788. var rate = Config.BUFFER_LOW_WATER_LINE_RATE;
  54789. var max = Math.max(initial, Config.MAX_BUFFER_LOW_WATER_LINE);
  54790. var newMax = Math.max(initial, Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);
  54791. return Math.min(initial + currentTime * rate, this.experimentalBufferBasedABR ? newMax : max);
  54792. };
  54793. _proto.bufferHighWaterLine = function bufferHighWaterLine() {
  54794. return Config.BUFFER_HIGH_WATER_LINE;
  54795. };
  54796. return MasterPlaylistController;
  54797. }(videojs.EventTarget);
  54798. /**
  54799. * Returns a function that acts as the Enable/disable playlist function.
  54800. *
  54801. * @param {PlaylistLoader} loader - The master playlist loader
  54802. * @param {string} playlistID - id of the playlist
  54803. * @param {Function} changePlaylistFn - A function to be called after a
  54804. * playlist's enabled-state has been changed. Will NOT be called if a
  54805. * playlist's enabled-state is unchanged
  54806. * @param {boolean=} enable - Value to set the playlist enabled-state to
  54807. * or if undefined returns the current enabled-state for the playlist
  54808. * @return {Function} Function for setting/getting enabled
  54809. */
  54810. var enableFunction = function enableFunction(loader, playlistID, changePlaylistFn) {
  54811. return function (enable) {
  54812. var playlist = loader.master.playlists[playlistID];
  54813. var incompatible = isIncompatible(playlist);
  54814. var currentlyEnabled = isEnabled(playlist);
  54815. if (typeof enable === 'undefined') {
  54816. return currentlyEnabled;
  54817. }
  54818. if (enable) {
  54819. delete playlist.disabled;
  54820. } else {
  54821. playlist.disabled = true;
  54822. }
  54823. if (enable !== currentlyEnabled && !incompatible) {
  54824. // Ensure the outside world knows about our changes
  54825. changePlaylistFn();
  54826. if (enable) {
  54827. loader.trigger('renditionenabled');
  54828. } else {
  54829. loader.trigger('renditiondisabled');
  54830. }
  54831. }
  54832. return enable;
  54833. };
  54834. };
  54835. /**
  54836. * The representation object encapsulates the publicly visible information
  54837. * in a media playlist along with a setter/getter-type function (enabled)
  54838. * for changing the enabled-state of a particular playlist entry
  54839. *
  54840. * @class Representation
  54841. */
  54842. var Representation = function Representation(vhsHandler, playlist, id) {
  54843. var mpc = vhsHandler.masterPlaylistController_,
  54844. smoothQualityChange = vhsHandler.options_.smoothQualityChange; // Get a reference to a bound version of the quality change function
  54845. var changeType = smoothQualityChange ? 'smooth' : 'fast';
  54846. var qualityChangeFunction = mpc[changeType + "QualityChange_"].bind(mpc); // some playlist attributes are optional
  54847. if (playlist.attributes) {
  54848. var resolution = playlist.attributes.RESOLUTION;
  54849. this.width = resolution && resolution.width;
  54850. this.height = resolution && resolution.height;
  54851. this.bandwidth = playlist.attributes.BANDWIDTH;
  54852. this.frameRate = playlist.attributes['FRAME-RATE'];
  54853. }
  54854. this.codecs = codecsForPlaylist(mpc.master(), playlist);
  54855. this.playlist = playlist; // The id is simply the ordinality of the media playlist
  54856. // within the master playlist
  54857. this.id = id; // Partially-apply the enableFunction to create a playlist-
  54858. // specific variant
  54859. this.enabled = enableFunction(vhsHandler.playlists, playlist.id, qualityChangeFunction);
  54860. };
  54861. /**
  54862. * A mixin function that adds the `representations` api to an instance
  54863. * of the VhsHandler class
  54864. *
  54865. * @param {VhsHandler} vhsHandler - An instance of VhsHandler to add the
  54866. * representation API into
  54867. */
  54868. var renditionSelectionMixin = function renditionSelectionMixin(vhsHandler) {
  54869. // Add a single API-specific function to the VhsHandler instance
  54870. vhsHandler.representations = function () {
  54871. var master = vhsHandler.masterPlaylistController_.master();
  54872. var playlists = isAudioOnly(master) ? vhsHandler.masterPlaylistController_.getAudioTrackPlaylists_() : master.playlists;
  54873. if (!playlists) {
  54874. return [];
  54875. }
  54876. return playlists.filter(function (media) {
  54877. return !isIncompatible(media);
  54878. }).map(function (e, i) {
  54879. return new Representation(vhsHandler, e, e.id);
  54880. });
  54881. };
  54882. };
  54883. /**
  54884. * @file playback-watcher.js
  54885. *
  54886. * Playback starts, and now my watch begins. It shall not end until my death. I shall
  54887. * take no wait, hold no uncleared timeouts, father no bad seeks. I shall wear no crowns
  54888. * and win no glory. I shall live and die at my post. I am the corrector of the underflow.
  54889. * I am the watcher of gaps. I am the shield that guards the realms of seekable. I pledge
  54890. * my life and honor to the Playback Watch, for this Player and all the Players to come.
  54891. */
  54892. var timerCancelEvents = ['seeking', 'seeked', 'pause', 'playing', 'error'];
  54893. /**
  54894. * @class PlaybackWatcher
  54895. */
  54896. var PlaybackWatcher = /*#__PURE__*/function () {
  54897. /**
  54898. * Represents an PlaybackWatcher object.
  54899. *
  54900. * @class
  54901. * @param {Object} options an object that includes the tech and settings
  54902. */
  54903. function PlaybackWatcher(options) {
  54904. var _this = this;
  54905. this.masterPlaylistController_ = options.masterPlaylistController;
  54906. this.tech_ = options.tech;
  54907. this.seekable = options.seekable;
  54908. this.allowSeeksWithinUnsafeLiveWindow = options.allowSeeksWithinUnsafeLiveWindow;
  54909. this.liveRangeSafeTimeDelta = options.liveRangeSafeTimeDelta;
  54910. this.media = options.media;
  54911. this.consecutiveUpdates = 0;
  54912. this.lastRecordedTime = null;
  54913. this.timer_ = null;
  54914. this.checkCurrentTimeTimeout_ = null;
  54915. this.logger_ = logger('PlaybackWatcher');
  54916. this.logger_('initialize');
  54917. var playHandler = function playHandler() {
  54918. return _this.monitorCurrentTime_();
  54919. };
  54920. var canPlayHandler = function canPlayHandler() {
  54921. return _this.monitorCurrentTime_();
  54922. };
  54923. var waitingHandler = function waitingHandler() {
  54924. return _this.techWaiting_();
  54925. };
  54926. var cancelTimerHandler = function cancelTimerHandler() {
  54927. return _this.cancelTimer_();
  54928. };
  54929. var mpc = this.masterPlaylistController_;
  54930. var loaderTypes = ['main', 'subtitle', 'audio'];
  54931. var loaderChecks = {};
  54932. loaderTypes.forEach(function (type) {
  54933. loaderChecks[type] = {
  54934. reset: function reset() {
  54935. return _this.resetSegmentDownloads_(type);
  54936. },
  54937. updateend: function updateend() {
  54938. return _this.checkSegmentDownloads_(type);
  54939. }
  54940. };
  54941. mpc[type + "SegmentLoader_"].on('appendsdone', loaderChecks[type].updateend); // If a rendition switch happens during a playback stall where the buffer
  54942. // isn't changing we want to reset. We cannot assume that the new rendition
  54943. // will also be stalled, until after new appends.
  54944. mpc[type + "SegmentLoader_"].on('playlistupdate', loaderChecks[type].reset); // Playback stalls should not be detected right after seeking.
  54945. // This prevents one segment playlists (single vtt or single segment content)
  54946. // from being detected as stalling. As the buffer will not change in those cases, since
  54947. // the buffer is the entire video duration.
  54948. _this.tech_.on(['seeked', 'seeking'], loaderChecks[type].reset);
  54949. });
  54950. /**
  54951. * We check if a seek was into a gap through the following steps:
  54952. * 1. We get a seeking event and we do not get a seeked event. This means that
  54953. * a seek was attempted but not completed.
  54954. * 2. We run `fixesBadSeeks_` on segment loader appends. This means that we already
  54955. * removed everything from our buffer and appended a segment, and should be ready
  54956. * to check for gaps.
  54957. */
  54958. var setSeekingHandlers = function setSeekingHandlers(fn) {
  54959. ['main', 'audio'].forEach(function (type) {
  54960. mpc[type + "SegmentLoader_"][fn]('appended', _this.seekingAppendCheck_);
  54961. });
  54962. };
  54963. this.seekingAppendCheck_ = function () {
  54964. if (_this.fixesBadSeeks_()) {
  54965. _this.consecutiveUpdates = 0;
  54966. _this.lastRecordedTime = _this.tech_.currentTime();
  54967. setSeekingHandlers('off');
  54968. }
  54969. };
  54970. this.clearSeekingAppendCheck_ = function () {
  54971. return setSeekingHandlers('off');
  54972. };
  54973. this.watchForBadSeeking_ = function () {
  54974. _this.clearSeekingAppendCheck_();
  54975. setSeekingHandlers('on');
  54976. };
  54977. this.tech_.on('seeked', this.clearSeekingAppendCheck_);
  54978. this.tech_.on('seeking', this.watchForBadSeeking_);
  54979. this.tech_.on('waiting', waitingHandler);
  54980. this.tech_.on(timerCancelEvents, cancelTimerHandler);
  54981. this.tech_.on('canplay', canPlayHandler);
  54982. /*
  54983. An edge case exists that results in gaps not being skipped when they exist at the beginning of a stream. This case
  54984. is surfaced in one of two ways:
  54985. 1) The `waiting` event is fired before the player has buffered content, making it impossible
  54986. to find or skip the gap. The `waiting` event is followed by a `play` event. On first play
  54987. we can check if playback is stalled due to a gap, and skip the gap if necessary.
  54988. 2) A source with a gap at the beginning of the stream is loaded programatically while the player
  54989. is in a playing state. To catch this case, it's important that our one-time play listener is setup
  54990. even if the player is in a playing state
  54991. */
  54992. this.tech_.one('play', playHandler); // Define the dispose function to clean up our events
  54993. this.dispose = function () {
  54994. _this.clearSeekingAppendCheck_();
  54995. _this.logger_('dispose');
  54996. _this.tech_.off('waiting', waitingHandler);
  54997. _this.tech_.off(timerCancelEvents, cancelTimerHandler);
  54998. _this.tech_.off('canplay', canPlayHandler);
  54999. _this.tech_.off('play', playHandler);
  55000. _this.tech_.off('seeking', _this.watchForBadSeeking_);
  55001. _this.tech_.off('seeked', _this.clearSeekingAppendCheck_);
  55002. loaderTypes.forEach(function (type) {
  55003. mpc[type + "SegmentLoader_"].off('appendsdone', loaderChecks[type].updateend);
  55004. mpc[type + "SegmentLoader_"].off('playlistupdate', loaderChecks[type].reset);
  55005. _this.tech_.off(['seeked', 'seeking'], loaderChecks[type].reset);
  55006. });
  55007. if (_this.checkCurrentTimeTimeout_) {
  55008. window.clearTimeout(_this.checkCurrentTimeTimeout_);
  55009. }
  55010. _this.cancelTimer_();
  55011. };
  55012. }
  55013. /**
  55014. * Periodically check current time to see if playback stopped
  55015. *
  55016. * @private
  55017. */
  55018. var _proto = PlaybackWatcher.prototype;
  55019. _proto.monitorCurrentTime_ = function monitorCurrentTime_() {
  55020. this.checkCurrentTime_();
  55021. if (this.checkCurrentTimeTimeout_) {
  55022. window.clearTimeout(this.checkCurrentTimeTimeout_);
  55023. } // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  55024. this.checkCurrentTimeTimeout_ = window.setTimeout(this.monitorCurrentTime_.bind(this), 250);
  55025. }
  55026. /**
  55027. * Reset stalled download stats for a specific type of loader
  55028. *
  55029. * @param {string} type
  55030. * The segment loader type to check.
  55031. *
  55032. * @listens SegmentLoader#playlistupdate
  55033. * @listens Tech#seeking
  55034. * @listens Tech#seeked
  55035. */
  55036. ;
  55037. _proto.resetSegmentDownloads_ = function resetSegmentDownloads_(type) {
  55038. var loader = this.masterPlaylistController_[type + "SegmentLoader_"];
  55039. if (this[type + "StalledDownloads_"] > 0) {
  55040. this.logger_("resetting possible stalled download count for " + type + " loader");
  55041. }
  55042. this[type + "StalledDownloads_"] = 0;
  55043. this[type + "Buffered_"] = loader.buffered_();
  55044. }
  55045. /**
  55046. * Checks on every segment `appendsdone` to see
  55047. * if segment appends are making progress. If they are not
  55048. * and we are still downloading bytes. We blacklist the playlist.
  55049. *
  55050. * @param {string} type
  55051. * The segment loader type to check.
  55052. *
  55053. * @listens SegmentLoader#appendsdone
  55054. */
  55055. ;
  55056. _proto.checkSegmentDownloads_ = function checkSegmentDownloads_(type) {
  55057. var mpc = this.masterPlaylistController_;
  55058. var loader = mpc[type + "SegmentLoader_"];
  55059. var buffered = loader.buffered_();
  55060. var isBufferedDifferent = isRangeDifferent(this[type + "Buffered_"], buffered);
  55061. this[type + "Buffered_"] = buffered; // if another watcher is going to fix the issue or
  55062. // the buffered value for this loader changed
  55063. // appends are working
  55064. if (isBufferedDifferent) {
  55065. this.resetSegmentDownloads_(type);
  55066. return;
  55067. }
  55068. this[type + "StalledDownloads_"]++;
  55069. this.logger_("found #" + this[type + "StalledDownloads_"] + " " + type + " appends that did not increase buffer (possible stalled download)", {
  55070. playlistId: loader.playlist_ && loader.playlist_.id,
  55071. buffered: timeRangesToArray(buffered)
  55072. }); // after 10 possibly stalled appends with no reset, exclude
  55073. if (this[type + "StalledDownloads_"] < 10) {
  55074. return;
  55075. }
  55076. this.logger_(type + " loader stalled download exclusion");
  55077. this.resetSegmentDownloads_(type);
  55078. this.tech_.trigger({
  55079. type: 'usage',
  55080. name: "vhs-" + type + "-download-exclusion"
  55081. });
  55082. if (type === 'subtitle') {
  55083. return;
  55084. } // TODO: should we exclude audio tracks rather than main tracks
  55085. // when type is audio?
  55086. mpc.blacklistCurrentPlaylist({
  55087. message: "Excessive " + type + " segment downloading detected."
  55088. }, Infinity);
  55089. }
  55090. /**
  55091. * The purpose of this function is to emulate the "waiting" event on
  55092. * browsers that do not emit it when they are waiting for more
  55093. * data to continue playback
  55094. *
  55095. * @private
  55096. */
  55097. ;
  55098. _proto.checkCurrentTime_ = function checkCurrentTime_() {
  55099. if (this.tech_.paused() || this.tech_.seeking()) {
  55100. return;
  55101. }
  55102. var currentTime = this.tech_.currentTime();
  55103. var buffered = this.tech_.buffered();
  55104. if (this.lastRecordedTime === currentTime && (!buffered.length || currentTime + SAFE_TIME_DELTA >= buffered.end(buffered.length - 1))) {
  55105. // If current time is at the end of the final buffered region, then any playback
  55106. // stall is most likely caused by buffering in a low bandwidth environment. The tech
  55107. // should fire a `waiting` event in this scenario, but due to browser and tech
  55108. // inconsistencies. Calling `techWaiting_` here allows us to simulate
  55109. // responding to a native `waiting` event when the tech fails to emit one.
  55110. return this.techWaiting_();
  55111. }
  55112. if (this.consecutiveUpdates >= 5 && currentTime === this.lastRecordedTime) {
  55113. this.consecutiveUpdates++;
  55114. this.waiting_();
  55115. } else if (currentTime === this.lastRecordedTime) {
  55116. this.consecutiveUpdates++;
  55117. } else {
  55118. this.consecutiveUpdates = 0;
  55119. this.lastRecordedTime = currentTime;
  55120. }
  55121. }
  55122. /**
  55123. * Cancels any pending timers and resets the 'timeupdate' mechanism
  55124. * designed to detect that we are stalled
  55125. *
  55126. * @private
  55127. */
  55128. ;
  55129. _proto.cancelTimer_ = function cancelTimer_() {
  55130. this.consecutiveUpdates = 0;
  55131. if (this.timer_) {
  55132. this.logger_('cancelTimer_');
  55133. clearTimeout(this.timer_);
  55134. }
  55135. this.timer_ = null;
  55136. }
  55137. /**
  55138. * Fixes situations where there's a bad seek
  55139. *
  55140. * @return {boolean} whether an action was taken to fix the seek
  55141. * @private
  55142. */
  55143. ;
  55144. _proto.fixesBadSeeks_ = function fixesBadSeeks_() {
  55145. var seeking = this.tech_.seeking();
  55146. if (!seeking) {
  55147. return false;
  55148. } // TODO: It's possible that these seekable checks should be moved out of this function
  55149. // and into a function that runs on seekablechange. It's also possible that we only need
  55150. // afterSeekableWindow as the buffered check at the bottom is good enough to handle before
  55151. // seekable range.
  55152. var seekable = this.seekable();
  55153. var currentTime = this.tech_.currentTime();
  55154. var isAfterSeekableRange = this.afterSeekableWindow_(seekable, currentTime, this.media(), this.allowSeeksWithinUnsafeLiveWindow);
  55155. var seekTo;
  55156. if (isAfterSeekableRange) {
  55157. var seekableEnd = seekable.end(seekable.length - 1); // sync to live point (if VOD, our seekable was updated and we're simply adjusting)
  55158. seekTo = seekableEnd;
  55159. }
  55160. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  55161. var seekableStart = seekable.start(0); // sync to the beginning of the live window
  55162. // provide a buffer of .1 seconds to handle rounding/imprecise numbers
  55163. seekTo = seekableStart + ( // if the playlist is too short and the seekable range is an exact time (can
  55164. // happen in live with a 3 segment playlist), then don't use a time delta
  55165. seekableStart === seekable.end(0) ? 0 : SAFE_TIME_DELTA);
  55166. }
  55167. if (typeof seekTo !== 'undefined') {
  55168. this.logger_("Trying to seek outside of seekable at time " + currentTime + " with " + ("seekable range " + printableRange(seekable) + ". Seeking to ") + (seekTo + "."));
  55169. this.tech_.setCurrentTime(seekTo);
  55170. return true;
  55171. }
  55172. var sourceUpdater = this.masterPlaylistController_.sourceUpdater_;
  55173. var buffered = this.tech_.buffered();
  55174. var audioBuffered = sourceUpdater.audioBuffer ? sourceUpdater.audioBuffered() : null;
  55175. var videoBuffered = sourceUpdater.videoBuffer ? sourceUpdater.videoBuffered() : null;
  55176. var media = this.media(); // verify that at least two segment durations or one part duration have been
  55177. // appended before checking for a gap.
  55178. var minAppendedDuration = media.partTargetDuration ? media.partTargetDuration : (media.targetDuration - TIME_FUDGE_FACTOR) * 2; // verify that at least two segment durations have been
  55179. // appended before checking for a gap.
  55180. var bufferedToCheck = [audioBuffered, videoBuffered];
  55181. for (var i = 0; i < bufferedToCheck.length; i++) {
  55182. // skip null buffered
  55183. if (!bufferedToCheck[i]) {
  55184. continue;
  55185. }
  55186. var timeAhead = timeAheadOf(bufferedToCheck[i], currentTime); // if we are less than two video/audio segment durations or one part
  55187. // duration behind we haven't appended enough to call this a bad seek.
  55188. if (timeAhead < minAppendedDuration) {
  55189. return false;
  55190. }
  55191. }
  55192. var nextRange = findNextRange(buffered, currentTime); // we have appended enough content, but we don't have anything buffered
  55193. // to seek over the gap
  55194. if (nextRange.length === 0) {
  55195. return false;
  55196. }
  55197. seekTo = nextRange.start(0) + SAFE_TIME_DELTA;
  55198. this.logger_("Buffered region starts (" + nextRange.start(0) + ") " + (" just beyond seek point (" + currentTime + "). Seeking to " + seekTo + "."));
  55199. this.tech_.setCurrentTime(seekTo);
  55200. return true;
  55201. }
  55202. /**
  55203. * Handler for situations when we determine the player is waiting.
  55204. *
  55205. * @private
  55206. */
  55207. ;
  55208. _proto.waiting_ = function waiting_() {
  55209. if (this.techWaiting_()) {
  55210. return;
  55211. } // All tech waiting checks failed. Use last resort correction
  55212. var currentTime = this.tech_.currentTime();
  55213. var buffered = this.tech_.buffered();
  55214. var currentRange = findRange(buffered, currentTime); // Sometimes the player can stall for unknown reasons within a contiguous buffered
  55215. // region with no indication that anything is amiss (seen in Firefox). Seeking to
  55216. // currentTime is usually enough to kickstart the player. This checks that the player
  55217. // is currently within a buffered region before attempting a corrective seek.
  55218. // Chrome does not appear to continue `timeupdate` events after a `waiting` event
  55219. // until there is ~ 3 seconds of forward buffer available. PlaybackWatcher should also
  55220. // make sure there is ~3 seconds of forward buffer before taking any corrective action
  55221. // to avoid triggering an `unknownwaiting` event when the network is slow.
  55222. if (currentRange.length && currentTime + 3 <= currentRange.end(0)) {
  55223. this.cancelTimer_();
  55224. this.tech_.setCurrentTime(currentTime);
  55225. this.logger_("Stopped at " + currentTime + " while inside a buffered region " + ("[" + currentRange.start(0) + " -> " + currentRange.end(0) + "]. Attempting to resume ") + 'playback by seeking to the current time.'); // unknown waiting corrections may be useful for monitoring QoS
  55226. this.tech_.trigger({
  55227. type: 'usage',
  55228. name: 'vhs-unknown-waiting'
  55229. });
  55230. this.tech_.trigger({
  55231. type: 'usage',
  55232. name: 'hls-unknown-waiting'
  55233. });
  55234. return;
  55235. }
  55236. }
  55237. /**
  55238. * Handler for situations when the tech fires a `waiting` event
  55239. *
  55240. * @return {boolean}
  55241. * True if an action (or none) was needed to correct the waiting. False if no
  55242. * checks passed
  55243. * @private
  55244. */
  55245. ;
  55246. _proto.techWaiting_ = function techWaiting_() {
  55247. var seekable = this.seekable();
  55248. var currentTime = this.tech_.currentTime();
  55249. if (this.tech_.seeking() || this.timer_ !== null) {
  55250. // Tech is seeking or already waiting on another action, no action needed
  55251. return true;
  55252. }
  55253. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  55254. var livePoint = seekable.end(seekable.length - 1);
  55255. this.logger_("Fell out of live window at time " + currentTime + ". Seeking to " + ("live point (seekable end) " + livePoint));
  55256. this.cancelTimer_();
  55257. this.tech_.setCurrentTime(livePoint); // live window resyncs may be useful for monitoring QoS
  55258. this.tech_.trigger({
  55259. type: 'usage',
  55260. name: 'vhs-live-resync'
  55261. });
  55262. this.tech_.trigger({
  55263. type: 'usage',
  55264. name: 'hls-live-resync'
  55265. });
  55266. return true;
  55267. }
  55268. var sourceUpdater = this.tech_.vhs.masterPlaylistController_.sourceUpdater_;
  55269. var buffered = this.tech_.buffered();
  55270. var videoUnderflow = this.videoUnderflow_({
  55271. audioBuffered: sourceUpdater.audioBuffered(),
  55272. videoBuffered: sourceUpdater.videoBuffered(),
  55273. currentTime: currentTime
  55274. });
  55275. if (videoUnderflow) {
  55276. // Even though the video underflowed and was stuck in a gap, the audio overplayed
  55277. // the gap, leading currentTime into a buffered range. Seeking to currentTime
  55278. // allows the video to catch up to the audio position without losing any audio
  55279. // (only suffering ~3 seconds of frozen video and a pause in audio playback).
  55280. this.cancelTimer_();
  55281. this.tech_.setCurrentTime(currentTime); // video underflow may be useful for monitoring QoS
  55282. this.tech_.trigger({
  55283. type: 'usage',
  55284. name: 'vhs-video-underflow'
  55285. });
  55286. this.tech_.trigger({
  55287. type: 'usage',
  55288. name: 'hls-video-underflow'
  55289. });
  55290. return true;
  55291. }
  55292. var nextRange = findNextRange(buffered, currentTime); // check for gap
  55293. if (nextRange.length > 0) {
  55294. var difference = nextRange.start(0) - currentTime;
  55295. this.logger_("Stopped at " + currentTime + ", setting timer for " + difference + ", seeking " + ("to " + nextRange.start(0)));
  55296. this.cancelTimer_();
  55297. this.timer_ = setTimeout(this.skipTheGap_.bind(this), difference * 1000, currentTime);
  55298. return true;
  55299. } // All checks failed. Returning false to indicate failure to correct waiting
  55300. return false;
  55301. };
  55302. _proto.afterSeekableWindow_ = function afterSeekableWindow_(seekable, currentTime, playlist, allowSeeksWithinUnsafeLiveWindow) {
  55303. if (allowSeeksWithinUnsafeLiveWindow === void 0) {
  55304. allowSeeksWithinUnsafeLiveWindow = false;
  55305. }
  55306. if (!seekable.length) {
  55307. // we can't make a solid case if there's no seekable, default to false
  55308. return false;
  55309. }
  55310. var allowedEnd = seekable.end(seekable.length - 1) + SAFE_TIME_DELTA;
  55311. var isLive = !playlist.endList;
  55312. if (isLive && allowSeeksWithinUnsafeLiveWindow) {
  55313. allowedEnd = seekable.end(seekable.length - 1) + playlist.targetDuration * 3;
  55314. }
  55315. if (currentTime > allowedEnd) {
  55316. return true;
  55317. }
  55318. return false;
  55319. };
  55320. _proto.beforeSeekableWindow_ = function beforeSeekableWindow_(seekable, currentTime) {
  55321. if (seekable.length && // can't fall before 0 and 0 seekable start identifies VOD stream
  55322. seekable.start(0) > 0 && currentTime < seekable.start(0) - this.liveRangeSafeTimeDelta) {
  55323. return true;
  55324. }
  55325. return false;
  55326. };
  55327. _proto.videoUnderflow_ = function videoUnderflow_(_ref) {
  55328. var videoBuffered = _ref.videoBuffered,
  55329. audioBuffered = _ref.audioBuffered,
  55330. currentTime = _ref.currentTime; // audio only content will not have video underflow :)
  55331. if (!videoBuffered) {
  55332. return;
  55333. }
  55334. var gap; // find a gap in demuxed content.
  55335. if (videoBuffered.length && audioBuffered.length) {
  55336. // in Chrome audio will continue to play for ~3s when we run out of video
  55337. // so we have to check that the video buffer did have some buffer in the
  55338. // past.
  55339. var lastVideoRange = findRange(videoBuffered, currentTime - 3);
  55340. var videoRange = findRange(videoBuffered, currentTime);
  55341. var audioRange = findRange(audioBuffered, currentTime);
  55342. if (audioRange.length && !videoRange.length && lastVideoRange.length) {
  55343. gap = {
  55344. start: lastVideoRange.end(0),
  55345. end: audioRange.end(0)
  55346. };
  55347. } // find a gap in muxed content.
  55348. } else {
  55349. var nextRange = findNextRange(videoBuffered, currentTime); // Even if there is no available next range, there is still a possibility we are
  55350. // stuck in a gap due to video underflow.
  55351. if (!nextRange.length) {
  55352. gap = this.gapFromVideoUnderflow_(videoBuffered, currentTime);
  55353. }
  55354. }
  55355. if (gap) {
  55356. this.logger_("Encountered a gap in video from " + gap.start + " to " + gap.end + ". " + ("Seeking to current time " + currentTime));
  55357. return true;
  55358. }
  55359. return false;
  55360. }
  55361. /**
  55362. * Timer callback. If playback still has not proceeded, then we seek
  55363. * to the start of the next buffered region.
  55364. *
  55365. * @private
  55366. */
  55367. ;
  55368. _proto.skipTheGap_ = function skipTheGap_(scheduledCurrentTime) {
  55369. var buffered = this.tech_.buffered();
  55370. var currentTime = this.tech_.currentTime();
  55371. var nextRange = findNextRange(buffered, currentTime);
  55372. this.cancelTimer_();
  55373. if (nextRange.length === 0 || currentTime !== scheduledCurrentTime) {
  55374. return;
  55375. }
  55376. this.logger_('skipTheGap_:', 'currentTime:', currentTime, 'scheduled currentTime:', scheduledCurrentTime, 'nextRange start:', nextRange.start(0)); // only seek if we still have not played
  55377. this.tech_.setCurrentTime(nextRange.start(0) + TIME_FUDGE_FACTOR);
  55378. this.tech_.trigger({
  55379. type: 'usage',
  55380. name: 'vhs-gap-skip'
  55381. });
  55382. this.tech_.trigger({
  55383. type: 'usage',
  55384. name: 'hls-gap-skip'
  55385. });
  55386. };
  55387. _proto.gapFromVideoUnderflow_ = function gapFromVideoUnderflow_(buffered, currentTime) {
  55388. // At least in Chrome, if there is a gap in the video buffer, the audio will continue
  55389. // playing for ~3 seconds after the video gap starts. This is done to account for
  55390. // video buffer underflow/underrun (note that this is not done when there is audio
  55391. // buffer underflow/underrun -- in that case the video will stop as soon as it
  55392. // encounters the gap, as audio stalls are more noticeable/jarring to a user than
  55393. // video stalls). The player's time will reflect the playthrough of audio, so the
  55394. // time will appear as if we are in a buffered region, even if we are stuck in a
  55395. // "gap."
  55396. //
  55397. // Example:
  55398. // video buffer: 0 => 10.1, 10.2 => 20
  55399. // audio buffer: 0 => 20
  55400. // overall buffer: 0 => 10.1, 10.2 => 20
  55401. // current time: 13
  55402. //
  55403. // Chrome's video froze at 10 seconds, where the video buffer encountered the gap,
  55404. // however, the audio continued playing until it reached ~3 seconds past the gap
  55405. // (13 seconds), at which point it stops as well. Since current time is past the
  55406. // gap, findNextRange will return no ranges.
  55407. //
  55408. // To check for this issue, we see if there is a gap that starts somewhere within
  55409. // a 3 second range (3 seconds +/- 1 second) back from our current time.
  55410. var gaps = findGaps(buffered);
  55411. for (var i = 0; i < gaps.length; i++) {
  55412. var start = gaps.start(i);
  55413. var end = gaps.end(i); // gap is starts no more than 4 seconds back
  55414. if (currentTime - start < 4 && currentTime - start > 2) {
  55415. return {
  55416. start: start,
  55417. end: end
  55418. };
  55419. }
  55420. }
  55421. return null;
  55422. };
  55423. return PlaybackWatcher;
  55424. }();
  55425. var defaultOptions = {
  55426. errorInterval: 30,
  55427. getSource: function getSource(next) {
  55428. var tech = this.tech({
  55429. IWillNotUseThisInPlugins: true
  55430. });
  55431. var sourceObj = tech.currentSource_ || this.currentSource();
  55432. return next(sourceObj);
  55433. }
  55434. };
  55435. /**
  55436. * Main entry point for the plugin
  55437. *
  55438. * @param {Player} player a reference to a videojs Player instance
  55439. * @param {Object} [options] an object with plugin options
  55440. * @private
  55441. */
  55442. var initPlugin = function initPlugin(player, options) {
  55443. var lastCalled = 0;
  55444. var seekTo = 0;
  55445. var localOptions = videojs.mergeOptions(defaultOptions, options);
  55446. player.ready(function () {
  55447. player.trigger({
  55448. type: 'usage',
  55449. name: 'vhs-error-reload-initialized'
  55450. });
  55451. player.trigger({
  55452. type: 'usage',
  55453. name: 'hls-error-reload-initialized'
  55454. });
  55455. });
  55456. /**
  55457. * Player modifications to perform that must wait until `loadedmetadata`
  55458. * has been triggered
  55459. *
  55460. * @private
  55461. */
  55462. var loadedMetadataHandler = function loadedMetadataHandler() {
  55463. if (seekTo) {
  55464. player.currentTime(seekTo);
  55465. }
  55466. };
  55467. /**
  55468. * Set the source on the player element, play, and seek if necessary
  55469. *
  55470. * @param {Object} sourceObj An object specifying the source url and mime-type to play
  55471. * @private
  55472. */
  55473. var setSource = function setSource(sourceObj) {
  55474. if (sourceObj === null || sourceObj === undefined) {
  55475. return;
  55476. }
  55477. seekTo = player.duration() !== Infinity && player.currentTime() || 0;
  55478. player.one('loadedmetadata', loadedMetadataHandler);
  55479. player.src(sourceObj);
  55480. player.trigger({
  55481. type: 'usage',
  55482. name: 'vhs-error-reload'
  55483. });
  55484. player.trigger({
  55485. type: 'usage',
  55486. name: 'hls-error-reload'
  55487. });
  55488. player.play();
  55489. };
  55490. /**
  55491. * Attempt to get a source from either the built-in getSource function
  55492. * or a custom function provided via the options
  55493. *
  55494. * @private
  55495. */
  55496. var errorHandler = function errorHandler() {
  55497. // Do not attempt to reload the source if a source-reload occurred before
  55498. // 'errorInterval' time has elapsed since the last source-reload
  55499. if (Date.now() - lastCalled < localOptions.errorInterval * 1000) {
  55500. player.trigger({
  55501. type: 'usage',
  55502. name: 'vhs-error-reload-canceled'
  55503. });
  55504. player.trigger({
  55505. type: 'usage',
  55506. name: 'hls-error-reload-canceled'
  55507. });
  55508. return;
  55509. }
  55510. if (!localOptions.getSource || typeof localOptions.getSource !== 'function') {
  55511. videojs.log.error('ERROR: reloadSourceOnError - The option getSource must be a function!');
  55512. return;
  55513. }
  55514. lastCalled = Date.now();
  55515. return localOptions.getSource.call(player, setSource);
  55516. };
  55517. /**
  55518. * Unbind any event handlers that were bound by the plugin
  55519. *
  55520. * @private
  55521. */
  55522. var cleanupEvents = function cleanupEvents() {
  55523. player.off('loadedmetadata', loadedMetadataHandler);
  55524. player.off('error', errorHandler);
  55525. player.off('dispose', cleanupEvents);
  55526. };
  55527. /**
  55528. * Cleanup before re-initializing the plugin
  55529. *
  55530. * @param {Object} [newOptions] an object with plugin options
  55531. * @private
  55532. */
  55533. var reinitPlugin = function reinitPlugin(newOptions) {
  55534. cleanupEvents();
  55535. initPlugin(player, newOptions);
  55536. };
  55537. player.on('error', errorHandler);
  55538. player.on('dispose', cleanupEvents); // Overwrite the plugin function so that we can correctly cleanup before
  55539. // initializing the plugin
  55540. player.reloadSourceOnError = reinitPlugin;
  55541. };
  55542. /**
  55543. * Reload the source when an error is detected as long as there
  55544. * wasn't an error previously within the last 30 seconds
  55545. *
  55546. * @param {Object} [options] an object with plugin options
  55547. */
  55548. var reloadSourceOnError = function reloadSourceOnError(options) {
  55549. initPlugin(this, options);
  55550. };
  55551. var version$4 = "2.16.2";
  55552. var version$3 = "6.0.1";
  55553. var version$2 = "0.22.1";
  55554. var version$1 = "4.8.0";
  55555. var version = "3.1.3";
  55556. var Vhs = {
  55557. PlaylistLoader: PlaylistLoader,
  55558. Playlist: Playlist,
  55559. utils: utils,
  55560. STANDARD_PLAYLIST_SELECTOR: lastBandwidthSelector,
  55561. INITIAL_PLAYLIST_SELECTOR: lowestBitrateCompatibleVariantSelector,
  55562. lastBandwidthSelector: lastBandwidthSelector,
  55563. movingAverageBandwidthSelector: movingAverageBandwidthSelector,
  55564. comparePlaylistBandwidth: comparePlaylistBandwidth,
  55565. comparePlaylistResolution: comparePlaylistResolution,
  55566. xhr: xhrFactory()
  55567. }; // Define getter/setters for config properties
  55568. Object.keys(Config).forEach(function (prop) {
  55569. Object.defineProperty(Vhs, prop, {
  55570. get: function get() {
  55571. videojs.log.warn("using Vhs." + prop + " is UNSAFE be sure you know what you are doing");
  55572. return Config[prop];
  55573. },
  55574. set: function set(value) {
  55575. videojs.log.warn("using Vhs." + prop + " is UNSAFE be sure you know what you are doing");
  55576. if (typeof value !== 'number' || value < 0) {
  55577. videojs.log.warn("value of Vhs." + prop + " must be greater than or equal to 0");
  55578. return;
  55579. }
  55580. Config[prop] = value;
  55581. }
  55582. });
  55583. });
  55584. var LOCAL_STORAGE_KEY = 'videojs-vhs';
  55585. /**
  55586. * Updates the selectedIndex of the QualityLevelList when a mediachange happens in vhs.
  55587. *
  55588. * @param {QualityLevelList} qualityLevels The QualityLevelList to update.
  55589. * @param {PlaylistLoader} playlistLoader PlaylistLoader containing the new media info.
  55590. * @function handleVhsMediaChange
  55591. */
  55592. var handleVhsMediaChange = function handleVhsMediaChange(qualityLevels, playlistLoader) {
  55593. var newPlaylist = playlistLoader.media();
  55594. var selectedIndex = -1;
  55595. for (var i = 0; i < qualityLevels.length; i++) {
  55596. if (qualityLevels[i].id === newPlaylist.id) {
  55597. selectedIndex = i;
  55598. break;
  55599. }
  55600. }
  55601. qualityLevels.selectedIndex_ = selectedIndex;
  55602. qualityLevels.trigger({
  55603. selectedIndex: selectedIndex,
  55604. type: 'change'
  55605. });
  55606. };
  55607. /**
  55608. * Adds quality levels to list once playlist metadata is available
  55609. *
  55610. * @param {QualityLevelList} qualityLevels The QualityLevelList to attach events to.
  55611. * @param {Object} vhs Vhs object to listen to for media events.
  55612. * @function handleVhsLoadedMetadata
  55613. */
  55614. var handleVhsLoadedMetadata = function handleVhsLoadedMetadata(qualityLevels, vhs) {
  55615. vhs.representations().forEach(function (rep) {
  55616. qualityLevels.addQualityLevel(rep);
  55617. });
  55618. handleVhsMediaChange(qualityLevels, vhs.playlists);
  55619. }; // HLS is a source handler, not a tech. Make sure attempts to use it
  55620. // as one do not cause exceptions.
  55621. Vhs.canPlaySource = function () {
  55622. return videojs.log.warn('HLS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  55623. };
  55624. var emeKeySystems = function emeKeySystems(keySystemOptions, mainPlaylist, audioPlaylist) {
  55625. if (!keySystemOptions) {
  55626. return keySystemOptions;
  55627. }
  55628. var codecs = {};
  55629. if (mainPlaylist && mainPlaylist.attributes && mainPlaylist.attributes.CODECS) {
  55630. codecs = unwrapCodecList(parseCodecs(mainPlaylist.attributes.CODECS));
  55631. }
  55632. if (audioPlaylist && audioPlaylist.attributes && audioPlaylist.attributes.CODECS) {
  55633. codecs.audio = audioPlaylist.attributes.CODECS;
  55634. }
  55635. var videoContentType = getMimeForCodec(codecs.video);
  55636. var audioContentType = getMimeForCodec(codecs.audio); // upsert the content types based on the selected playlist
  55637. var keySystemContentTypes = {};
  55638. for (var keySystem in keySystemOptions) {
  55639. keySystemContentTypes[keySystem] = {};
  55640. if (audioContentType) {
  55641. keySystemContentTypes[keySystem].audioContentType = audioContentType;
  55642. }
  55643. if (videoContentType) {
  55644. keySystemContentTypes[keySystem].videoContentType = videoContentType;
  55645. } // Default to using the video playlist's PSSH even though they may be different, as
  55646. // videojs-contrib-eme will only accept one in the options.
  55647. //
  55648. // This shouldn't be an issue for most cases as early intialization will handle all
  55649. // unique PSSH values, and if they aren't, then encrypted events should have the
  55650. // specific information needed for the unique license.
  55651. if (mainPlaylist.contentProtection && mainPlaylist.contentProtection[keySystem] && mainPlaylist.contentProtection[keySystem].pssh) {
  55652. keySystemContentTypes[keySystem].pssh = mainPlaylist.contentProtection[keySystem].pssh;
  55653. } // videojs-contrib-eme accepts the option of specifying: 'com.some.cdm': 'url'
  55654. // so we need to prevent overwriting the URL entirely
  55655. if (typeof keySystemOptions[keySystem] === 'string') {
  55656. keySystemContentTypes[keySystem].url = keySystemOptions[keySystem];
  55657. }
  55658. }
  55659. return videojs.mergeOptions(keySystemOptions, keySystemContentTypes);
  55660. };
  55661. /**
  55662. * @typedef {Object} KeySystems
  55663. *
  55664. * keySystems configuration for https://github.com/videojs/videojs-contrib-eme
  55665. * Note: not all options are listed here.
  55666. *
  55667. * @property {Uint8Array} [pssh]
  55668. * Protection System Specific Header
  55669. */
  55670. /**
  55671. * Goes through all the playlists and collects an array of KeySystems options objects
  55672. * containing each playlist's keySystems and their pssh values, if available.
  55673. *
  55674. * @param {Object[]} playlists
  55675. * The playlists to look through
  55676. * @param {string[]} keySystems
  55677. * The keySystems to collect pssh values for
  55678. *
  55679. * @return {KeySystems[]}
  55680. * An array of KeySystems objects containing available key systems and their
  55681. * pssh values
  55682. */
  55683. var getAllPsshKeySystemsOptions = function getAllPsshKeySystemsOptions(playlists, keySystems) {
  55684. return playlists.reduce(function (keySystemsArr, playlist) {
  55685. if (!playlist.contentProtection) {
  55686. return keySystemsArr;
  55687. }
  55688. var keySystemsOptions = keySystems.reduce(function (keySystemsObj, keySystem) {
  55689. var keySystemOptions = playlist.contentProtection[keySystem];
  55690. if (keySystemOptions && keySystemOptions.pssh) {
  55691. keySystemsObj[keySystem] = {
  55692. pssh: keySystemOptions.pssh
  55693. };
  55694. }
  55695. return keySystemsObj;
  55696. }, {});
  55697. if (Object.keys(keySystemsOptions).length) {
  55698. keySystemsArr.push(keySystemsOptions);
  55699. }
  55700. return keySystemsArr;
  55701. }, []);
  55702. };
  55703. /**
  55704. * Returns a promise that waits for the
  55705. * [eme plugin](https://github.com/videojs/videojs-contrib-eme) to create a key session.
  55706. *
  55707. * Works around https://bugs.chromium.org/p/chromium/issues/detail?id=895449 in non-IE11
  55708. * browsers.
  55709. *
  55710. * As per the above ticket, this is particularly important for Chrome, where, if
  55711. * unencrypted content is appended before encrypted content and the key session has not
  55712. * been created, a MEDIA_ERR_DECODE will be thrown once the encrypted content is reached
  55713. * during playback.
  55714. *
  55715. * @param {Object} player
  55716. * The player instance
  55717. * @param {Object[]} sourceKeySystems
  55718. * The key systems options from the player source
  55719. * @param {Object} [audioMedia]
  55720. * The active audio media playlist (optional)
  55721. * @param {Object[]} mainPlaylists
  55722. * The playlists found on the master playlist object
  55723. *
  55724. * @return {Object}
  55725. * Promise that resolves when the key session has been created
  55726. */
  55727. var waitForKeySessionCreation = function waitForKeySessionCreation(_ref) {
  55728. var player = _ref.player,
  55729. sourceKeySystems = _ref.sourceKeySystems,
  55730. audioMedia = _ref.audioMedia,
  55731. mainPlaylists = _ref.mainPlaylists;
  55732. if (!player.eme.initializeMediaKeys) {
  55733. return Promise.resolve();
  55734. } // TODO should all audio PSSH values be initialized for DRM?
  55735. //
  55736. // All unique video rendition pssh values are initialized for DRM, but here only
  55737. // the initial audio playlist license is initialized. In theory, an encrypted
  55738. // event should be fired if the user switches to an alternative audio playlist
  55739. // where a license is required, but this case hasn't yet been tested. In addition, there
  55740. // may be many alternate audio playlists unlikely to be used (e.g., multiple different
  55741. // languages).
  55742. var playlists = audioMedia ? mainPlaylists.concat([audioMedia]) : mainPlaylists;
  55743. var keySystemsOptionsArr = getAllPsshKeySystemsOptions(playlists, Object.keys(sourceKeySystems));
  55744. var initializationFinishedPromises = [];
  55745. var keySessionCreatedPromises = []; // Since PSSH values are interpreted as initData, EME will dedupe any duplicates. The
  55746. // only place where it should not be deduped is for ms-prefixed APIs, but the early
  55747. // return for IE11 above, and the existence of modern EME APIs in addition to
  55748. // ms-prefixed APIs on Edge should prevent this from being a concern.
  55749. // initializeMediaKeys also won't use the webkit-prefixed APIs.
  55750. keySystemsOptionsArr.forEach(function (keySystemsOptions) {
  55751. keySessionCreatedPromises.push(new Promise(function (resolve, reject) {
  55752. player.tech_.one('keysessioncreated', resolve);
  55753. }));
  55754. initializationFinishedPromises.push(new Promise(function (resolve, reject) {
  55755. player.eme.initializeMediaKeys({
  55756. keySystems: keySystemsOptions
  55757. }, function (err) {
  55758. if (err) {
  55759. reject(err);
  55760. return;
  55761. }
  55762. resolve();
  55763. });
  55764. }));
  55765. }); // The reasons Promise.race is chosen over Promise.any:
  55766. //
  55767. // * Promise.any is only available in Safari 14+.
  55768. // * None of these promises are expected to reject. If they do reject, it might be
  55769. // better here for the race to surface the rejection, rather than mask it by using
  55770. // Promise.any.
  55771. return Promise.race([// If a session was previously created, these will all finish resolving without
  55772. // creating a new session, otherwise it will take until the end of all license
  55773. // requests, which is why the key session check is used (to make setup much faster).
  55774. Promise.all(initializationFinishedPromises), // Once a single session is created, the browser knows DRM will be used.
  55775. Promise.race(keySessionCreatedPromises)]);
  55776. };
  55777. /**
  55778. * If the [eme](https://github.com/videojs/videojs-contrib-eme) plugin is available, and
  55779. * there are keySystems on the source, sets up source options to prepare the source for
  55780. * eme.
  55781. *
  55782. * @param {Object} player
  55783. * The player instance
  55784. * @param {Object[]} sourceKeySystems
  55785. * The key systems options from the player source
  55786. * @param {Object} media
  55787. * The active media playlist
  55788. * @param {Object} [audioMedia]
  55789. * The active audio media playlist (optional)
  55790. *
  55791. * @return {boolean}
  55792. * Whether or not options were configured and EME is available
  55793. */
  55794. var setupEmeOptions = function setupEmeOptions(_ref2) {
  55795. var player = _ref2.player,
  55796. sourceKeySystems = _ref2.sourceKeySystems,
  55797. media = _ref2.media,
  55798. audioMedia = _ref2.audioMedia;
  55799. var sourceOptions = emeKeySystems(sourceKeySystems, media, audioMedia);
  55800. if (!sourceOptions) {
  55801. return false;
  55802. }
  55803. player.currentSource().keySystems = sourceOptions; // eme handles the rest of the setup, so if it is missing
  55804. // do nothing.
  55805. if (sourceOptions && !player.eme) {
  55806. videojs.log.warn('DRM encrypted source cannot be decrypted without a DRM plugin');
  55807. return false;
  55808. }
  55809. return true;
  55810. };
  55811. var getVhsLocalStorage = function getVhsLocalStorage() {
  55812. if (!window.localStorage) {
  55813. return null;
  55814. }
  55815. var storedObject = window.localStorage.getItem(LOCAL_STORAGE_KEY);
  55816. if (!storedObject) {
  55817. return null;
  55818. }
  55819. try {
  55820. return JSON.parse(storedObject);
  55821. } catch (e) {
  55822. // someone may have tampered with the value
  55823. return null;
  55824. }
  55825. };
  55826. var updateVhsLocalStorage = function updateVhsLocalStorage(options) {
  55827. if (!window.localStorage) {
  55828. return false;
  55829. }
  55830. var objectToStore = getVhsLocalStorage();
  55831. objectToStore = objectToStore ? videojs.mergeOptions(objectToStore, options) : options;
  55832. try {
  55833. window.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(objectToStore));
  55834. } catch (e) {
  55835. // Throws if storage is full (e.g., always on iOS 5+ Safari private mode, where
  55836. // storage is set to 0).
  55837. // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions
  55838. // No need to perform any operation.
  55839. return false;
  55840. }
  55841. return objectToStore;
  55842. };
  55843. /**
  55844. * Parses VHS-supported media types from data URIs. See
  55845. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
  55846. * for information on data URIs.
  55847. *
  55848. * @param {string} dataUri
  55849. * The data URI
  55850. *
  55851. * @return {string|Object}
  55852. * The parsed object/string, or the original string if no supported media type
  55853. * was found
  55854. */
  55855. var expandDataUri = function expandDataUri(dataUri) {
  55856. if (dataUri.toLowerCase().indexOf('data:application/vnd.videojs.vhs+json,') === 0) {
  55857. return JSON.parse(dataUri.substring(dataUri.indexOf(',') + 1));
  55858. } // no known case for this data URI, return the string as-is
  55859. return dataUri;
  55860. };
  55861. /**
  55862. * Whether the browser has built-in HLS support.
  55863. */
  55864. Vhs.supportsNativeHls = function () {
  55865. if (!document || !document.createElement) {
  55866. return false;
  55867. }
  55868. var video = document.createElement('video'); // native HLS is definitely not supported if HTML5 video isn't
  55869. if (!videojs.getTech('Html5').isSupported()) {
  55870. return false;
  55871. } // HLS manifests can go by many mime-types
  55872. var canPlay = [// Apple santioned
  55873. 'application/vnd.apple.mpegurl', // Apple sanctioned for backwards compatibility
  55874. 'audio/mpegurl', // Very common
  55875. 'audio/x-mpegurl', // Very common
  55876. 'application/x-mpegurl', // Included for completeness
  55877. 'video/x-mpegurl', 'video/mpegurl', 'application/mpegurl'];
  55878. return canPlay.some(function (canItPlay) {
  55879. return /maybe|probably/i.test(video.canPlayType(canItPlay));
  55880. });
  55881. }();
  55882. Vhs.supportsNativeDash = function () {
  55883. if (!document || !document.createElement || !videojs.getTech('Html5').isSupported()) {
  55884. return false;
  55885. }
  55886. return /maybe|probably/i.test(document.createElement('video').canPlayType('application/dash+xml'));
  55887. }();
  55888. Vhs.supportsTypeNatively = function (type) {
  55889. if (type === 'hls') {
  55890. return Vhs.supportsNativeHls;
  55891. }
  55892. if (type === 'dash') {
  55893. return Vhs.supportsNativeDash;
  55894. }
  55895. return false;
  55896. };
  55897. /**
  55898. * HLS is a source handler, not a tech. Make sure attempts to use it
  55899. * as one do not cause exceptions.
  55900. */
  55901. Vhs.isSupported = function () {
  55902. return videojs.log.warn('HLS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  55903. };
  55904. var Component = videojs.getComponent('Component');
  55905. /**
  55906. * The Vhs Handler object, where we orchestrate all of the parts
  55907. * of HLS to interact with video.js
  55908. *
  55909. * @class VhsHandler
  55910. * @extends videojs.Component
  55911. * @param {Object} source the soruce object
  55912. * @param {Tech} tech the parent tech object
  55913. * @param {Object} options optional and required options
  55914. */
  55915. var VhsHandler = /*#__PURE__*/function (_Component) {
  55916. inheritsLoose(VhsHandler, _Component);
  55917. function VhsHandler(source, tech, options) {
  55918. var _this;
  55919. _this = _Component.call(this, tech, videojs.mergeOptions(options.hls, options.vhs)) || this;
  55920. if (options.hls && Object.keys(options.hls).length) {
  55921. videojs.log.warn('Using hls options is deprecated. Please rename `hls` to `vhs` in your options object.');
  55922. } // if a tech level `initialBandwidth` option was passed
  55923. // use that over the VHS level `bandwidth` option
  55924. if (typeof options.initialBandwidth === 'number') {
  55925. _this.options_.bandwidth = options.initialBandwidth;
  55926. }
  55927. _this.logger_ = logger('VhsHandler'); // tech.player() is deprecated but setup a reference to HLS for
  55928. // backwards-compatibility
  55929. if (tech.options_ && tech.options_.playerId) {
  55930. var _player = videojs(tech.options_.playerId);
  55931. if (!_player.hasOwnProperty('hls')) {
  55932. Object.defineProperty(_player, 'hls', {
  55933. get: function get() {
  55934. videojs.log.warn('player.hls is deprecated. Use player.tech().vhs instead.');
  55935. tech.trigger({
  55936. type: 'usage',
  55937. name: 'hls-player-access'
  55938. });
  55939. return assertThisInitialized(_this);
  55940. },
  55941. configurable: true
  55942. });
  55943. }
  55944. if (!_player.hasOwnProperty('vhs')) {
  55945. Object.defineProperty(_player, 'vhs', {
  55946. get: function get() {
  55947. videojs.log.warn('player.vhs is deprecated. Use player.tech().vhs instead.');
  55948. tech.trigger({
  55949. type: 'usage',
  55950. name: 'vhs-player-access'
  55951. });
  55952. return assertThisInitialized(_this);
  55953. },
  55954. configurable: true
  55955. });
  55956. }
  55957. if (!_player.hasOwnProperty('dash')) {
  55958. Object.defineProperty(_player, 'dash', {
  55959. get: function get() {
  55960. videojs.log.warn('player.dash is deprecated. Use player.tech().vhs instead.');
  55961. return assertThisInitialized(_this);
  55962. },
  55963. configurable: true
  55964. });
  55965. }
  55966. _this.player_ = _player;
  55967. }
  55968. _this.tech_ = tech;
  55969. _this.source_ = source;
  55970. _this.stats = {};
  55971. _this.ignoreNextSeekingEvent_ = false;
  55972. _this.setOptions_();
  55973. if (_this.options_.overrideNative && tech.overrideNativeAudioTracks && tech.overrideNativeVideoTracks) {
  55974. tech.overrideNativeAudioTracks(true);
  55975. tech.overrideNativeVideoTracks(true);
  55976. } else if (_this.options_.overrideNative && (tech.featuresNativeVideoTracks || tech.featuresNativeAudioTracks)) {
  55977. // overriding native HLS only works if audio tracks have been emulated
  55978. // error early if we're misconfigured
  55979. throw new Error('Overriding native HLS requires emulated tracks. ' + 'See https://git.io/vMpjB');
  55980. } // listen for fullscreenchange events for this player so that we
  55981. // can adjust our quality selection quickly
  55982. _this.on(document, ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'], function (event) {
  55983. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  55984. if (fullscreenElement && fullscreenElement.contains(_this.tech_.el())) {
  55985. _this.masterPlaylistController_.fastQualityChange_();
  55986. } else {
  55987. // When leaving fullscreen, since the in page pixel dimensions should be smaller
  55988. // than full screen, see if there should be a rendition switch down to preserve
  55989. // bandwidth.
  55990. _this.masterPlaylistController_.checkABR_();
  55991. }
  55992. });
  55993. _this.on(_this.tech_, 'seeking', function () {
  55994. if (this.ignoreNextSeekingEvent_) {
  55995. this.ignoreNextSeekingEvent_ = false;
  55996. return;
  55997. }
  55998. this.setCurrentTime(this.tech_.currentTime());
  55999. });
  56000. _this.on(_this.tech_, 'error', function () {
  56001. // verify that the error was real and we are loaded
  56002. // enough to have mpc loaded.
  56003. if (this.tech_.error() && this.masterPlaylistController_) {
  56004. this.masterPlaylistController_.pauseLoading();
  56005. }
  56006. });
  56007. _this.on(_this.tech_, 'play', _this.play);
  56008. return _this;
  56009. }
  56010. var _proto = VhsHandler.prototype;
  56011. _proto.setOptions_ = function setOptions_() {
  56012. var _this2 = this; // defaults
  56013. this.options_.withCredentials = this.options_.withCredentials || false;
  56014. this.options_.handleManifestRedirects = this.options_.handleManifestRedirects === false ? false : true;
  56015. this.options_.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions === false ? false : true;
  56016. this.options_.useDevicePixelRatio = this.options_.useDevicePixelRatio || false;
  56017. this.options_.smoothQualityChange = this.options_.smoothQualityChange || false;
  56018. this.options_.useBandwidthFromLocalStorage = typeof this.source_.useBandwidthFromLocalStorage !== 'undefined' ? this.source_.useBandwidthFromLocalStorage : this.options_.useBandwidthFromLocalStorage || false;
  56019. this.options_.useNetworkInformationApi = this.options_.useNetworkInformationApi || false;
  56020. this.options_.useDtsForTimestampOffset = this.options_.useDtsForTimestampOffset || false;
  56021. this.options_.customTagParsers = this.options_.customTagParsers || [];
  56022. this.options_.customTagMappers = this.options_.customTagMappers || [];
  56023. this.options_.cacheEncryptionKeys = this.options_.cacheEncryptionKeys || false;
  56024. if (typeof this.options_.blacklistDuration !== 'number') {
  56025. this.options_.blacklistDuration = 5 * 60;
  56026. }
  56027. if (typeof this.options_.bandwidth !== 'number') {
  56028. if (this.options_.useBandwidthFromLocalStorage) {
  56029. var storedObject = getVhsLocalStorage();
  56030. if (storedObject && storedObject.bandwidth) {
  56031. this.options_.bandwidth = storedObject.bandwidth;
  56032. this.tech_.trigger({
  56033. type: 'usage',
  56034. name: 'vhs-bandwidth-from-local-storage'
  56035. });
  56036. this.tech_.trigger({
  56037. type: 'usage',
  56038. name: 'hls-bandwidth-from-local-storage'
  56039. });
  56040. }
  56041. if (storedObject && storedObject.throughput) {
  56042. this.options_.throughput = storedObject.throughput;
  56043. this.tech_.trigger({
  56044. type: 'usage',
  56045. name: 'vhs-throughput-from-local-storage'
  56046. });
  56047. this.tech_.trigger({
  56048. type: 'usage',
  56049. name: 'hls-throughput-from-local-storage'
  56050. });
  56051. }
  56052. }
  56053. } // if bandwidth was not set by options or pulled from local storage, start playlist
  56054. // selection at a reasonable bandwidth
  56055. if (typeof this.options_.bandwidth !== 'number') {
  56056. this.options_.bandwidth = Config.INITIAL_BANDWIDTH;
  56057. } // If the bandwidth number is unchanged from the initial setting
  56058. // then this takes precedence over the enableLowInitialPlaylist option
  56059. this.options_.enableLowInitialPlaylist = this.options_.enableLowInitialPlaylist && this.options_.bandwidth === Config.INITIAL_BANDWIDTH; // grab options passed to player.src
  56060. ['withCredentials', 'useDevicePixelRatio', 'limitRenditionByPlayerDimensions', 'bandwidth', 'smoothQualityChange', 'customTagParsers', 'customTagMappers', 'handleManifestRedirects', 'cacheEncryptionKeys', 'playlistSelector', 'initialPlaylistSelector', 'experimentalBufferBasedABR', 'liveRangeSafeTimeDelta', 'experimentalLLHLS', 'useNetworkInformationApi', 'useDtsForTimestampOffset', 'experimentalExactManifestTimings', 'experimentalLeastPixelDiffSelector'].forEach(function (option) {
  56061. if (typeof _this2.source_[option] !== 'undefined') {
  56062. _this2.options_[option] = _this2.source_[option];
  56063. }
  56064. });
  56065. this.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions;
  56066. this.useDevicePixelRatio = this.options_.useDevicePixelRatio;
  56067. }
  56068. /**
  56069. * called when player.src gets called, handle a new source
  56070. *
  56071. * @param {Object} src the source object to handle
  56072. */
  56073. ;
  56074. _proto.src = function src(_src, type) {
  56075. var _this3 = this; // do nothing if the src is falsey
  56076. if (!_src) {
  56077. return;
  56078. }
  56079. this.setOptions_(); // add master playlist controller options
  56080. this.options_.src = expandDataUri(this.source_.src);
  56081. this.options_.tech = this.tech_;
  56082. this.options_.externVhs = Vhs;
  56083. this.options_.sourceType = simpleTypeFromSourceType(type); // Whenever we seek internally, we should update the tech
  56084. this.options_.seekTo = function (time) {
  56085. _this3.tech_.setCurrentTime(time);
  56086. };
  56087. if (this.options_.smoothQualityChange) {
  56088. videojs.log.warn('smoothQualityChange is deprecated and will be removed in the next major version');
  56089. }
  56090. this.masterPlaylistController_ = new MasterPlaylistController(this.options_);
  56091. var playbackWatcherOptions = videojs.mergeOptions({
  56092. liveRangeSafeTimeDelta: SAFE_TIME_DELTA
  56093. }, this.options_, {
  56094. seekable: function seekable() {
  56095. return _this3.seekable();
  56096. },
  56097. media: function media() {
  56098. return _this3.masterPlaylistController_.media();
  56099. },
  56100. masterPlaylistController: this.masterPlaylistController_
  56101. });
  56102. this.playbackWatcher_ = new PlaybackWatcher(playbackWatcherOptions);
  56103. this.masterPlaylistController_.on('error', function () {
  56104. var player = videojs.players[_this3.tech_.options_.playerId];
  56105. var error = _this3.masterPlaylistController_.error;
  56106. if (typeof error === 'object' && !error.code) {
  56107. error.code = 3;
  56108. } else if (typeof error === 'string') {
  56109. error = {
  56110. message: error,
  56111. code: 3
  56112. };
  56113. }
  56114. player.error(error);
  56115. });
  56116. var defaultSelector = this.options_.experimentalBufferBasedABR ? Vhs.movingAverageBandwidthSelector(0.55) : Vhs.STANDARD_PLAYLIST_SELECTOR; // `this` in selectPlaylist should be the VhsHandler for backwards
  56117. // compatibility with < v2
  56118. this.masterPlaylistController_.selectPlaylist = this.selectPlaylist ? this.selectPlaylist.bind(this) : defaultSelector.bind(this);
  56119. this.masterPlaylistController_.selectInitialPlaylist = Vhs.INITIAL_PLAYLIST_SELECTOR.bind(this); // re-expose some internal objects for backwards compatibility with < v2
  56120. this.playlists = this.masterPlaylistController_.masterPlaylistLoader_;
  56121. this.mediaSource = this.masterPlaylistController_.mediaSource; // Proxy assignment of some properties to the master playlist
  56122. // controller. Using a custom property for backwards compatibility
  56123. // with < v2
  56124. Object.defineProperties(this, {
  56125. selectPlaylist: {
  56126. get: function get() {
  56127. return this.masterPlaylistController_.selectPlaylist;
  56128. },
  56129. set: function set(selectPlaylist) {
  56130. this.masterPlaylistController_.selectPlaylist = selectPlaylist.bind(this);
  56131. }
  56132. },
  56133. throughput: {
  56134. get: function get() {
  56135. return this.masterPlaylistController_.mainSegmentLoader_.throughput.rate;
  56136. },
  56137. set: function set(throughput) {
  56138. this.masterPlaylistController_.mainSegmentLoader_.throughput.rate = throughput; // By setting `count` to 1 the throughput value becomes the starting value
  56139. // for the cumulative average
  56140. this.masterPlaylistController_.mainSegmentLoader_.throughput.count = 1;
  56141. }
  56142. },
  56143. bandwidth: {
  56144. get: function get() {
  56145. var playerBandwidthEst = this.masterPlaylistController_.mainSegmentLoader_.bandwidth;
  56146. var networkInformation = window.navigator.connection || window.navigator.mozConnection || window.navigator.webkitConnection;
  56147. var tenMbpsAsBitsPerSecond = 10e6;
  56148. if (this.options_.useNetworkInformationApi && networkInformation) {
  56149. // downlink returns Mbps
  56150. // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/downlink
  56151. var networkInfoBandwidthEstBitsPerSec = networkInformation.downlink * 1000 * 1000; // downlink maxes out at 10 Mbps. In the event that both networkInformationApi and the player
  56152. // estimate a bandwidth greater than 10 Mbps, use the larger of the two estimates to ensure that
  56153. // high quality streams are not filtered out.
  56154. if (networkInfoBandwidthEstBitsPerSec >= tenMbpsAsBitsPerSecond && playerBandwidthEst >= tenMbpsAsBitsPerSecond) {
  56155. playerBandwidthEst = Math.max(playerBandwidthEst, networkInfoBandwidthEstBitsPerSec);
  56156. } else {
  56157. playerBandwidthEst = networkInfoBandwidthEstBitsPerSec;
  56158. }
  56159. }
  56160. return playerBandwidthEst;
  56161. },
  56162. set: function set(bandwidth) {
  56163. this.masterPlaylistController_.mainSegmentLoader_.bandwidth = bandwidth; // setting the bandwidth manually resets the throughput counter
  56164. // `count` is set to zero that current value of `rate` isn't included
  56165. // in the cumulative average
  56166. this.masterPlaylistController_.mainSegmentLoader_.throughput = {
  56167. rate: 0,
  56168. count: 0
  56169. };
  56170. }
  56171. },
  56172. /**
  56173. * `systemBandwidth` is a combination of two serial processes bit-rates. The first
  56174. * is the network bitrate provided by `bandwidth` and the second is the bitrate of
  56175. * the entire process after that - decryption, transmuxing, and appending - provided
  56176. * by `throughput`.
  56177. *
  56178. * Since the two process are serial, the overall system bandwidth is given by:
  56179. * sysBandwidth = 1 / (1 / bandwidth + 1 / throughput)
  56180. */
  56181. systemBandwidth: {
  56182. get: function get() {
  56183. var invBandwidth = 1 / (this.bandwidth || 1);
  56184. var invThroughput;
  56185. if (this.throughput > 0) {
  56186. invThroughput = 1 / this.throughput;
  56187. } else {
  56188. invThroughput = 0;
  56189. }
  56190. var systemBitrate = Math.floor(1 / (invBandwidth + invThroughput));
  56191. return systemBitrate;
  56192. },
  56193. set: function set() {
  56194. videojs.log.error('The "systemBandwidth" property is read-only');
  56195. }
  56196. }
  56197. });
  56198. if (this.options_.bandwidth) {
  56199. this.bandwidth = this.options_.bandwidth;
  56200. }
  56201. if (this.options_.throughput) {
  56202. this.throughput = this.options_.throughput;
  56203. }
  56204. Object.defineProperties(this.stats, {
  56205. bandwidth: {
  56206. get: function get() {
  56207. return _this3.bandwidth || 0;
  56208. },
  56209. enumerable: true
  56210. },
  56211. mediaRequests: {
  56212. get: function get() {
  56213. return _this3.masterPlaylistController_.mediaRequests_() || 0;
  56214. },
  56215. enumerable: true
  56216. },
  56217. mediaRequestsAborted: {
  56218. get: function get() {
  56219. return _this3.masterPlaylistController_.mediaRequestsAborted_() || 0;
  56220. },
  56221. enumerable: true
  56222. },
  56223. mediaRequestsTimedout: {
  56224. get: function get() {
  56225. return _this3.masterPlaylistController_.mediaRequestsTimedout_() || 0;
  56226. },
  56227. enumerable: true
  56228. },
  56229. mediaRequestsErrored: {
  56230. get: function get() {
  56231. return _this3.masterPlaylistController_.mediaRequestsErrored_() || 0;
  56232. },
  56233. enumerable: true
  56234. },
  56235. mediaTransferDuration: {
  56236. get: function get() {
  56237. return _this3.masterPlaylistController_.mediaTransferDuration_() || 0;
  56238. },
  56239. enumerable: true
  56240. },
  56241. mediaBytesTransferred: {
  56242. get: function get() {
  56243. return _this3.masterPlaylistController_.mediaBytesTransferred_() || 0;
  56244. },
  56245. enumerable: true
  56246. },
  56247. mediaSecondsLoaded: {
  56248. get: function get() {
  56249. return _this3.masterPlaylistController_.mediaSecondsLoaded_() || 0;
  56250. },
  56251. enumerable: true
  56252. },
  56253. mediaAppends: {
  56254. get: function get() {
  56255. return _this3.masterPlaylistController_.mediaAppends_() || 0;
  56256. },
  56257. enumerable: true
  56258. },
  56259. mainAppendsToLoadedData: {
  56260. get: function get() {
  56261. return _this3.masterPlaylistController_.mainAppendsToLoadedData_() || 0;
  56262. },
  56263. enumerable: true
  56264. },
  56265. audioAppendsToLoadedData: {
  56266. get: function get() {
  56267. return _this3.masterPlaylistController_.audioAppendsToLoadedData_() || 0;
  56268. },
  56269. enumerable: true
  56270. },
  56271. appendsToLoadedData: {
  56272. get: function get() {
  56273. return _this3.masterPlaylistController_.appendsToLoadedData_() || 0;
  56274. },
  56275. enumerable: true
  56276. },
  56277. timeToLoadedData: {
  56278. get: function get() {
  56279. return _this3.masterPlaylistController_.timeToLoadedData_() || 0;
  56280. },
  56281. enumerable: true
  56282. },
  56283. buffered: {
  56284. get: function get() {
  56285. return timeRangesToArray(_this3.tech_.buffered());
  56286. },
  56287. enumerable: true
  56288. },
  56289. currentTime: {
  56290. get: function get() {
  56291. return _this3.tech_.currentTime();
  56292. },
  56293. enumerable: true
  56294. },
  56295. currentSource: {
  56296. get: function get() {
  56297. return _this3.tech_.currentSource_;
  56298. },
  56299. enumerable: true
  56300. },
  56301. currentTech: {
  56302. get: function get() {
  56303. return _this3.tech_.name_;
  56304. },
  56305. enumerable: true
  56306. },
  56307. duration: {
  56308. get: function get() {
  56309. return _this3.tech_.duration();
  56310. },
  56311. enumerable: true
  56312. },
  56313. master: {
  56314. get: function get() {
  56315. return _this3.playlists.master;
  56316. },
  56317. enumerable: true
  56318. },
  56319. playerDimensions: {
  56320. get: function get() {
  56321. return _this3.tech_.currentDimensions();
  56322. },
  56323. enumerable: true
  56324. },
  56325. seekable: {
  56326. get: function get() {
  56327. return timeRangesToArray(_this3.tech_.seekable());
  56328. },
  56329. enumerable: true
  56330. },
  56331. timestamp: {
  56332. get: function get() {
  56333. return Date.now();
  56334. },
  56335. enumerable: true
  56336. },
  56337. videoPlaybackQuality: {
  56338. get: function get() {
  56339. return _this3.tech_.getVideoPlaybackQuality();
  56340. },
  56341. enumerable: true
  56342. }
  56343. });
  56344. this.tech_.one('canplay', this.masterPlaylistController_.setupFirstPlay.bind(this.masterPlaylistController_));
  56345. this.tech_.on('bandwidthupdate', function () {
  56346. if (_this3.options_.useBandwidthFromLocalStorage) {
  56347. updateVhsLocalStorage({
  56348. bandwidth: _this3.bandwidth,
  56349. throughput: Math.round(_this3.throughput)
  56350. });
  56351. }
  56352. });
  56353. this.masterPlaylistController_.on('selectedinitialmedia', function () {
  56354. // Add the manual rendition mix-in to VhsHandler
  56355. renditionSelectionMixin(_this3);
  56356. });
  56357. this.masterPlaylistController_.sourceUpdater_.on('createdsourcebuffers', function () {
  56358. _this3.setupEme_();
  56359. }); // the bandwidth of the primary segment loader is our best
  56360. // estimate of overall bandwidth
  56361. this.on(this.masterPlaylistController_, 'progress', function () {
  56362. this.tech_.trigger('progress');
  56363. }); // In the live case, we need to ignore the very first `seeking` event since
  56364. // that will be the result of the seek-to-live behavior
  56365. this.on(this.masterPlaylistController_, 'firstplay', function () {
  56366. this.ignoreNextSeekingEvent_ = true;
  56367. });
  56368. this.setupQualityLevels_(); // do nothing if the tech has been disposed already
  56369. // this can occur if someone sets the src in player.ready(), for instance
  56370. if (!this.tech_.el()) {
  56371. return;
  56372. }
  56373. this.mediaSourceUrl_ = window.URL.createObjectURL(this.masterPlaylistController_.mediaSource);
  56374. this.tech_.src(this.mediaSourceUrl_);
  56375. };
  56376. _proto.createKeySessions_ = function createKeySessions_() {
  56377. var _this4 = this;
  56378. var audioPlaylistLoader = this.masterPlaylistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  56379. this.logger_('waiting for EME key session creation');
  56380. waitForKeySessionCreation({
  56381. player: this.player_,
  56382. sourceKeySystems: this.source_.keySystems,
  56383. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media(),
  56384. mainPlaylists: this.playlists.master.playlists
  56385. }).then(function () {
  56386. _this4.logger_('created EME key session');
  56387. _this4.masterPlaylistController_.sourceUpdater_.initializedEme();
  56388. })["catch"](function (err) {
  56389. _this4.logger_('error while creating EME key session', err);
  56390. _this4.player_.error({
  56391. message: 'Failed to initialize media keys for EME',
  56392. code: 3
  56393. });
  56394. });
  56395. };
  56396. _proto.handleWaitingForKey_ = function handleWaitingForKey_() {
  56397. // If waitingforkey is fired, it's possible that the data that's necessary to retrieve
  56398. // the key is in the manifest. While this should've happened on initial source load, it
  56399. // may happen again in live streams where the keys change, and the manifest info
  56400. // reflects the update.
  56401. //
  56402. // Because videojs-contrib-eme compares the PSSH data we send to that of PSSH data it's
  56403. // already requested keys for, we don't have to worry about this generating extraneous
  56404. // requests.
  56405. this.logger_('waitingforkey fired, attempting to create any new key sessions');
  56406. this.createKeySessions_();
  56407. }
  56408. /**
  56409. * If necessary and EME is available, sets up EME options and waits for key session
  56410. * creation.
  56411. *
  56412. * This function also updates the source updater so taht it can be used, as for some
  56413. * browsers, EME must be configured before content is appended (if appending unencrypted
  56414. * content before encrypted content).
  56415. */
  56416. ;
  56417. _proto.setupEme_ = function setupEme_() {
  56418. var _this5 = this;
  56419. var audioPlaylistLoader = this.masterPlaylistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  56420. var didSetupEmeOptions = setupEmeOptions({
  56421. player: this.player_,
  56422. sourceKeySystems: this.source_.keySystems,
  56423. media: this.playlists.media(),
  56424. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media()
  56425. });
  56426. this.player_.tech_.on('keystatuschange', function (e) {
  56427. if (e.status !== 'output-restricted') {
  56428. return;
  56429. }
  56430. var masterPlaylist = _this5.masterPlaylistController_.master();
  56431. if (!masterPlaylist || !masterPlaylist.playlists) {
  56432. return;
  56433. }
  56434. var excludedHDPlaylists = []; // Assume all HD streams are unplayable and exclude them from ABR selection
  56435. masterPlaylist.playlists.forEach(function (playlist) {
  56436. if (playlist && playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height >= 720) {
  56437. if (!playlist.excludeUntil || playlist.excludeUntil < Infinity) {
  56438. playlist.excludeUntil = Infinity;
  56439. excludedHDPlaylists.push(playlist);
  56440. }
  56441. }
  56442. });
  56443. if (excludedHDPlaylists.length) {
  56444. var _videojs$log;
  56445. (_videojs$log = videojs.log).warn.apply(_videojs$log, ['DRM keystatus changed to "output-restricted." Removing the following HD playlists ' + 'that will most likely fail to play and clearing the buffer. ' + 'This may be due to HDCP restrictions on the stream and the capabilities of the current device.'].concat(excludedHDPlaylists)); // Clear the buffer before switching playlists, since it may already contain unplayable segments
  56446. _this5.masterPlaylistController_.fastQualityChange_();
  56447. }
  56448. });
  56449. this.handleWaitingForKey_ = this.handleWaitingForKey_.bind(this);
  56450. this.player_.tech_.on('waitingforkey', this.handleWaitingForKey_); // In IE11 this is too early to initialize media keys, and IE11 does not support
  56451. // promises.
  56452. if (videojs.browser.IE_VERSION === 11 || !didSetupEmeOptions) {
  56453. // If EME options were not set up, we've done all we could to initialize EME.
  56454. this.masterPlaylistController_.sourceUpdater_.initializedEme();
  56455. return;
  56456. }
  56457. this.createKeySessions_();
  56458. }
  56459. /**
  56460. * Initializes the quality levels and sets listeners to update them.
  56461. *
  56462. * @method setupQualityLevels_
  56463. * @private
  56464. */
  56465. ;
  56466. _proto.setupQualityLevels_ = function setupQualityLevels_() {
  56467. var _this6 = this;
  56468. var player = videojs.players[this.tech_.options_.playerId]; // if there isn't a player or there isn't a qualityLevels plugin
  56469. // or qualityLevels_ listeners have already been setup, do nothing.
  56470. if (!player || !player.qualityLevels || this.qualityLevels_) {
  56471. return;
  56472. }
  56473. this.qualityLevels_ = player.qualityLevels();
  56474. this.masterPlaylistController_.on('selectedinitialmedia', function () {
  56475. handleVhsLoadedMetadata(_this6.qualityLevels_, _this6);
  56476. });
  56477. this.playlists.on('mediachange', function () {
  56478. handleVhsMediaChange(_this6.qualityLevels_, _this6.playlists);
  56479. });
  56480. }
  56481. /**
  56482. * return the version
  56483. */
  56484. ;
  56485. VhsHandler.version = function version$5() {
  56486. return {
  56487. '@videojs/http-streaming': version$4,
  56488. 'mux.js': version$3,
  56489. 'mpd-parser': version$2,
  56490. 'm3u8-parser': version$1,
  56491. 'aes-decrypter': version
  56492. };
  56493. }
  56494. /**
  56495. * return the version
  56496. */
  56497. ;
  56498. _proto.version = function version() {
  56499. return this.constructor.version();
  56500. };
  56501. _proto.canChangeType = function canChangeType() {
  56502. return SourceUpdater.canChangeType();
  56503. }
  56504. /**
  56505. * Begin playing the video.
  56506. */
  56507. ;
  56508. _proto.play = function play() {
  56509. this.masterPlaylistController_.play();
  56510. }
  56511. /**
  56512. * a wrapper around the function in MasterPlaylistController
  56513. */
  56514. ;
  56515. _proto.setCurrentTime = function setCurrentTime(currentTime) {
  56516. this.masterPlaylistController_.setCurrentTime(currentTime);
  56517. }
  56518. /**
  56519. * a wrapper around the function in MasterPlaylistController
  56520. */
  56521. ;
  56522. _proto.duration = function duration() {
  56523. return this.masterPlaylistController_.duration();
  56524. }
  56525. /**
  56526. * a wrapper around the function in MasterPlaylistController
  56527. */
  56528. ;
  56529. _proto.seekable = function seekable() {
  56530. return this.masterPlaylistController_.seekable();
  56531. }
  56532. /**
  56533. * Abort all outstanding work and cleanup.
  56534. */
  56535. ;
  56536. _proto.dispose = function dispose() {
  56537. if (this.playbackWatcher_) {
  56538. this.playbackWatcher_.dispose();
  56539. }
  56540. if (this.masterPlaylistController_) {
  56541. this.masterPlaylistController_.dispose();
  56542. }
  56543. if (this.qualityLevels_) {
  56544. this.qualityLevels_.dispose();
  56545. }
  56546. if (this.player_) {
  56547. delete this.player_.vhs;
  56548. delete this.player_.dash;
  56549. delete this.player_.hls;
  56550. }
  56551. if (this.tech_ && this.tech_.vhs) {
  56552. delete this.tech_.vhs;
  56553. } // don't check this.tech_.hls as it will log a deprecated warning
  56554. if (this.tech_) {
  56555. delete this.tech_.hls;
  56556. }
  56557. if (this.mediaSourceUrl_ && window.URL.revokeObjectURL) {
  56558. window.URL.revokeObjectURL(this.mediaSourceUrl_);
  56559. this.mediaSourceUrl_ = null;
  56560. }
  56561. if (this.tech_) {
  56562. this.tech_.off('waitingforkey', this.handleWaitingForKey_);
  56563. }
  56564. _Component.prototype.dispose.call(this);
  56565. };
  56566. _proto.convertToProgramTime = function convertToProgramTime(time, callback) {
  56567. return getProgramTime({
  56568. playlist: this.masterPlaylistController_.media(),
  56569. time: time,
  56570. callback: callback
  56571. });
  56572. } // the player must be playing before calling this
  56573. ;
  56574. _proto.seekToProgramTime = function seekToProgramTime$1(programTime, callback, pauseAfterSeek, retryCount) {
  56575. if (pauseAfterSeek === void 0) {
  56576. pauseAfterSeek = true;
  56577. }
  56578. if (retryCount === void 0) {
  56579. retryCount = 2;
  56580. }
  56581. return seekToProgramTime({
  56582. programTime: programTime,
  56583. playlist: this.masterPlaylistController_.media(),
  56584. retryCount: retryCount,
  56585. pauseAfterSeek: pauseAfterSeek,
  56586. seekTo: this.options_.seekTo,
  56587. tech: this.options_.tech,
  56588. callback: callback
  56589. });
  56590. };
  56591. return VhsHandler;
  56592. }(Component);
  56593. /**
  56594. * The Source Handler object, which informs video.js what additional
  56595. * MIME types are supported and sets up playback. It is registered
  56596. * automatically to the appropriate tech based on the capabilities of
  56597. * the browser it is running in. It is not necessary to use or modify
  56598. * this object in normal usage.
  56599. */
  56600. var VhsSourceHandler = {
  56601. name: 'videojs-http-streaming',
  56602. VERSION: version$4,
  56603. canHandleSource: function canHandleSource(srcObj, options) {
  56604. if (options === void 0) {
  56605. options = {};
  56606. }
  56607. var localOptions = videojs.mergeOptions(videojs.options, options);
  56608. return VhsSourceHandler.canPlayType(srcObj.type, localOptions);
  56609. },
  56610. handleSource: function handleSource(source, tech, options) {
  56611. if (options === void 0) {
  56612. options = {};
  56613. }
  56614. var localOptions = videojs.mergeOptions(videojs.options, options);
  56615. tech.vhs = new VhsHandler(source, tech, localOptions);
  56616. if (!videojs.hasOwnProperty('hls')) {
  56617. Object.defineProperty(tech, 'hls', {
  56618. get: function get() {
  56619. videojs.log.warn('player.tech().hls is deprecated. Use player.tech().vhs instead.');
  56620. return tech.vhs;
  56621. },
  56622. configurable: true
  56623. });
  56624. }
  56625. tech.vhs.xhr = xhrFactory();
  56626. tech.vhs.src(source.src, source.type);
  56627. return tech.vhs;
  56628. },
  56629. canPlayType: function canPlayType(type, options) {
  56630. var simpleType = simpleTypeFromSourceType(type);
  56631. if (!simpleType) {
  56632. return '';
  56633. }
  56634. var overrideNative = VhsSourceHandler.getOverrideNative(options);
  56635. var supportsTypeNatively = Vhs.supportsTypeNatively(simpleType);
  56636. var canUseMsePlayback = !supportsTypeNatively || overrideNative;
  56637. return canUseMsePlayback ? 'maybe' : '';
  56638. },
  56639. getOverrideNative: function getOverrideNative(options) {
  56640. if (options === void 0) {
  56641. options = {};
  56642. }
  56643. var _options = options,
  56644. _options$vhs = _options.vhs,
  56645. vhs = _options$vhs === void 0 ? {} : _options$vhs,
  56646. _options$hls = _options.hls,
  56647. hls = _options$hls === void 0 ? {} : _options$hls;
  56648. var defaultOverrideNative = !(videojs.browser.IS_ANY_SAFARI || videojs.browser.IS_IOS);
  56649. var _vhs$overrideNative = vhs.overrideNative,
  56650. overrideNative = _vhs$overrideNative === void 0 ? defaultOverrideNative : _vhs$overrideNative;
  56651. var _hls$overrideNative = hls.overrideNative,
  56652. legacyOverrideNative = _hls$overrideNative === void 0 ? false : _hls$overrideNative;
  56653. return legacyOverrideNative || overrideNative;
  56654. }
  56655. };
  56656. /**
  56657. * Check to see if the native MediaSource object exists and supports
  56658. * an MP4 container with both H.264 video and AAC-LC audio.
  56659. *
  56660. * @return {boolean} if native media sources are supported
  56661. */
  56662. var supportsNativeMediaSources = function supportsNativeMediaSources() {
  56663. return browserSupportsCodec('avc1.4d400d,mp4a.40.2');
  56664. }; // register source handlers with the appropriate techs
  56665. if (supportsNativeMediaSources()) {
  56666. videojs.getTech('Html5').registerSourceHandler(VhsSourceHandler, 0);
  56667. }
  56668. videojs.VhsHandler = VhsHandler;
  56669. Object.defineProperty(videojs, 'HlsHandler', {
  56670. get: function get() {
  56671. videojs.log.warn('videojs.HlsHandler is deprecated. Use videojs.VhsHandler instead.');
  56672. return VhsHandler;
  56673. },
  56674. configurable: true
  56675. });
  56676. videojs.VhsSourceHandler = VhsSourceHandler;
  56677. Object.defineProperty(videojs, 'HlsSourceHandler', {
  56678. get: function get() {
  56679. videojs.log.warn('videojs.HlsSourceHandler is deprecated. ' + 'Use videojs.VhsSourceHandler instead.');
  56680. return VhsSourceHandler;
  56681. },
  56682. configurable: true
  56683. });
  56684. videojs.Vhs = Vhs;
  56685. Object.defineProperty(videojs, 'Hls', {
  56686. get: function get() {
  56687. videojs.log.warn('videojs.Hls is deprecated. Use videojs.Vhs instead.');
  56688. return Vhs;
  56689. },
  56690. configurable: true
  56691. });
  56692. if (!videojs.use) {
  56693. videojs.registerComponent('Hls', Vhs);
  56694. videojs.registerComponent('Vhs', Vhs);
  56695. }
  56696. videojs.options.vhs = videojs.options.vhs || {};
  56697. videojs.options.hls = videojs.options.hls || {};
  56698. if (!videojs.getPlugin || !videojs.getPlugin('reloadSourceOnError')) {
  56699. var registerPlugin = videojs.registerPlugin || videojs.plugin;
  56700. registerPlugin('reloadSourceOnError', reloadSourceOnError);
  56701. }
  56702. return videojs;
  56703. })));