video.novtt.js 2.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657
  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 vtt = {};
  7755. /**
  7756. * An Object containing a structure like: `{src: 'url', type: 'mimetype'}` or string
  7757. * that just contains the src url alone.
  7758. * * `var SourceObject = {src: 'http://ex.com/video.mp4', type: 'video/mp4'};`
  7759. * `var SourceString = 'http://example.com/some-video.mp4';`
  7760. *
  7761. * @typedef {Object|string} Tech~SourceObject
  7762. *
  7763. * @property {string} src
  7764. * The url to the source
  7765. *
  7766. * @property {string} type
  7767. * The mime type of the source
  7768. */
  7769. /**
  7770. * A function used by {@link Tech} to create a new {@link TextTrack}.
  7771. *
  7772. * @private
  7773. *
  7774. * @param {Tech} self
  7775. * An instance of the Tech class.
  7776. *
  7777. * @param {string} kind
  7778. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  7779. *
  7780. * @param {string} [label]
  7781. * Label to identify the text track
  7782. *
  7783. * @param {string} [language]
  7784. * Two letter language abbreviation
  7785. *
  7786. * @param {Object} [options={}]
  7787. * An object with additional text track options
  7788. *
  7789. * @return {TextTrack}
  7790. * The text track that was created.
  7791. */
  7792. function createTrackHelper(self, kind, label, language, options) {
  7793. if (options === void 0) {
  7794. options = {};
  7795. }
  7796. var tracks = self.textTracks();
  7797. options.kind = kind;
  7798. if (label) {
  7799. options.label = label;
  7800. }
  7801. if (language) {
  7802. options.language = language;
  7803. }
  7804. options.tech = self;
  7805. var track = new ALL.text.TrackClass(options);
  7806. tracks.addTrack(track);
  7807. return track;
  7808. }
  7809. /**
  7810. * This is the base class for media playback technology controllers, such as
  7811. * {@link HTML5}
  7812. *
  7813. * @extends Component
  7814. */
  7815. var Tech = /*#__PURE__*/function (_Component) {
  7816. inheritsLoose(Tech, _Component);
  7817. /**
  7818. * Create an instance of this Tech.
  7819. *
  7820. * @param {Object} [options]
  7821. * The key/value store of player options.
  7822. *
  7823. * @param {Component~ReadyCallback} ready
  7824. * Callback function to call when the `HTML5` Tech is ready.
  7825. */
  7826. function Tech(options, ready) {
  7827. var _this;
  7828. if (options === void 0) {
  7829. options = {};
  7830. }
  7831. if (ready === void 0) {
  7832. ready = function ready() {};
  7833. }
  7834. // we don't want the tech to report user activity automatically.
  7835. // This is done manually in addControlsListeners
  7836. options.reportTouchActivity = false;
  7837. _this = _Component.call(this, null, options, ready) || this;
  7838. _this.onDurationChange_ = function (e) {
  7839. return _this.onDurationChange(e);
  7840. };
  7841. _this.trackProgress_ = function (e) {
  7842. return _this.trackProgress(e);
  7843. };
  7844. _this.trackCurrentTime_ = function (e) {
  7845. return _this.trackCurrentTime(e);
  7846. };
  7847. _this.stopTrackingCurrentTime_ = function (e) {
  7848. return _this.stopTrackingCurrentTime(e);
  7849. };
  7850. _this.disposeSourceHandler_ = function (e) {
  7851. return _this.disposeSourceHandler(e);
  7852. };
  7853. _this.queuedHanders_ = new Set(); // keep track of whether the current source has played at all to
  7854. // implement a very limited played()
  7855. _this.hasStarted_ = false;
  7856. _this.on('playing', function () {
  7857. this.hasStarted_ = true;
  7858. });
  7859. _this.on('loadstart', function () {
  7860. this.hasStarted_ = false;
  7861. });
  7862. ALL.names.forEach(function (name) {
  7863. var props = ALL[name];
  7864. if (options && options[props.getterName]) {
  7865. _this[props.privateName] = options[props.getterName];
  7866. }
  7867. }); // Manually track progress in cases where the browser/tech doesn't report it.
  7868. if (!_this.featuresProgressEvents) {
  7869. _this.manualProgressOn();
  7870. } // Manually track timeupdates in cases where the browser/tech doesn't report it.
  7871. if (!_this.featuresTimeupdateEvents) {
  7872. _this.manualTimeUpdatesOn();
  7873. }
  7874. ['Text', 'Audio', 'Video'].forEach(function (track) {
  7875. if (options["native" + track + "Tracks"] === false) {
  7876. _this["featuresNative" + track + "Tracks"] = false;
  7877. }
  7878. });
  7879. if (options.nativeCaptions === false || options.nativeTextTracks === false) {
  7880. _this.featuresNativeTextTracks = false;
  7881. } else if (options.nativeCaptions === true || options.nativeTextTracks === true) {
  7882. _this.featuresNativeTextTracks = true;
  7883. }
  7884. if (!_this.featuresNativeTextTracks) {
  7885. _this.emulateTextTracks();
  7886. }
  7887. _this.preloadTextTracks = options.preloadTextTracks !== false;
  7888. _this.autoRemoteTextTracks_ = new ALL.text.ListClass();
  7889. _this.initTrackListeners(); // Turn on component tap events only if not using native controls
  7890. if (!options.nativeControlsForTouch) {
  7891. _this.emitTapEvents();
  7892. }
  7893. if (_this.constructor) {
  7894. _this.name_ = _this.constructor.name || 'Unknown Tech';
  7895. }
  7896. return _this;
  7897. }
  7898. /**
  7899. * A special function to trigger source set in a way that will allow player
  7900. * to re-trigger if the player or tech are not ready yet.
  7901. *
  7902. * @fires Tech#sourceset
  7903. * @param {string} src The source string at the time of the source changing.
  7904. */
  7905. var _proto = Tech.prototype;
  7906. _proto.triggerSourceset = function triggerSourceset(src) {
  7907. var _this2 = this;
  7908. if (!this.isReady_) {
  7909. // on initial ready we have to trigger source set
  7910. // 1ms after ready so that player can watch for it.
  7911. this.one('ready', function () {
  7912. return _this2.setTimeout(function () {
  7913. return _this2.triggerSourceset(src);
  7914. }, 1);
  7915. });
  7916. }
  7917. /**
  7918. * Fired when the source is set on the tech causing the media element
  7919. * to reload.
  7920. *
  7921. * @see {@link Player#event:sourceset}
  7922. * @event Tech#sourceset
  7923. * @type {EventTarget~Event}
  7924. */
  7925. this.trigger({
  7926. src: src,
  7927. type: 'sourceset'
  7928. });
  7929. }
  7930. /* Fallbacks for unsupported event types
  7931. ================================================================================ */
  7932. /**
  7933. * Polyfill the `progress` event for browsers that don't support it natively.
  7934. *
  7935. * @see {@link Tech#trackProgress}
  7936. */
  7937. ;
  7938. _proto.manualProgressOn = function manualProgressOn() {
  7939. this.on('durationchange', this.onDurationChange_);
  7940. this.manualProgress = true; // Trigger progress watching when a source begins loading
  7941. this.one('ready', this.trackProgress_);
  7942. }
  7943. /**
  7944. * Turn off the polyfill for `progress` events that was created in
  7945. * {@link Tech#manualProgressOn}
  7946. */
  7947. ;
  7948. _proto.manualProgressOff = function manualProgressOff() {
  7949. this.manualProgress = false;
  7950. this.stopTrackingProgress();
  7951. this.off('durationchange', this.onDurationChange_);
  7952. }
  7953. /**
  7954. * This is used to trigger a `progress` event when the buffered percent changes. It
  7955. * sets an interval function that will be called every 500 milliseconds to check if the
  7956. * buffer end percent has changed.
  7957. *
  7958. * > This function is called by {@link Tech#manualProgressOn}
  7959. *
  7960. * @param {EventTarget~Event} event
  7961. * The `ready` event that caused this to run.
  7962. *
  7963. * @listens Tech#ready
  7964. * @fires Tech#progress
  7965. */
  7966. ;
  7967. _proto.trackProgress = function trackProgress(event) {
  7968. this.stopTrackingProgress();
  7969. this.progressInterval = this.setInterval(bind(this, function () {
  7970. // Don't trigger unless buffered amount is greater than last time
  7971. var numBufferedPercent = this.bufferedPercent();
  7972. if (this.bufferedPercent_ !== numBufferedPercent) {
  7973. /**
  7974. * See {@link Player#progress}
  7975. *
  7976. * @event Tech#progress
  7977. * @type {EventTarget~Event}
  7978. */
  7979. this.trigger('progress');
  7980. }
  7981. this.bufferedPercent_ = numBufferedPercent;
  7982. if (numBufferedPercent === 1) {
  7983. this.stopTrackingProgress();
  7984. }
  7985. }), 500);
  7986. }
  7987. /**
  7988. * Update our internal duration on a `durationchange` event by calling
  7989. * {@link Tech#duration}.
  7990. *
  7991. * @param {EventTarget~Event} event
  7992. * The `durationchange` event that caused this to run.
  7993. *
  7994. * @listens Tech#durationchange
  7995. */
  7996. ;
  7997. _proto.onDurationChange = function onDurationChange(event) {
  7998. this.duration_ = this.duration();
  7999. }
  8000. /**
  8001. * Get and create a `TimeRange` object for buffering.
  8002. *
  8003. * @return {TimeRange}
  8004. * The time range object that was created.
  8005. */
  8006. ;
  8007. _proto.buffered = function buffered() {
  8008. return createTimeRanges(0, 0);
  8009. }
  8010. /**
  8011. * Get the percentage of the current video that is currently buffered.
  8012. *
  8013. * @return {number}
  8014. * A number from 0 to 1 that represents the decimal percentage of the
  8015. * video that is buffered.
  8016. *
  8017. */
  8018. ;
  8019. _proto.bufferedPercent = function bufferedPercent$1() {
  8020. return bufferedPercent(this.buffered(), this.duration_);
  8021. }
  8022. /**
  8023. * Turn off the polyfill for `progress` events that was created in
  8024. * {@link Tech#manualProgressOn}
  8025. * Stop manually tracking progress events by clearing the interval that was set in
  8026. * {@link Tech#trackProgress}.
  8027. */
  8028. ;
  8029. _proto.stopTrackingProgress = function stopTrackingProgress() {
  8030. this.clearInterval(this.progressInterval);
  8031. }
  8032. /**
  8033. * Polyfill the `timeupdate` event for browsers that don't support it.
  8034. *
  8035. * @see {@link Tech#trackCurrentTime}
  8036. */
  8037. ;
  8038. _proto.manualTimeUpdatesOn = function manualTimeUpdatesOn() {
  8039. this.manualTimeUpdates = true;
  8040. this.on('play', this.trackCurrentTime_);
  8041. this.on('pause', this.stopTrackingCurrentTime_);
  8042. }
  8043. /**
  8044. * Turn off the polyfill for `timeupdate` events that was created in
  8045. * {@link Tech#manualTimeUpdatesOn}
  8046. */
  8047. ;
  8048. _proto.manualTimeUpdatesOff = function manualTimeUpdatesOff() {
  8049. this.manualTimeUpdates = false;
  8050. this.stopTrackingCurrentTime();
  8051. this.off('play', this.trackCurrentTime_);
  8052. this.off('pause', this.stopTrackingCurrentTime_);
  8053. }
  8054. /**
  8055. * Sets up an interval function to track current time and trigger `timeupdate` every
  8056. * 250 milliseconds.
  8057. *
  8058. * @listens Tech#play
  8059. * @triggers Tech#timeupdate
  8060. */
  8061. ;
  8062. _proto.trackCurrentTime = function trackCurrentTime() {
  8063. if (this.currentTimeInterval) {
  8064. this.stopTrackingCurrentTime();
  8065. }
  8066. this.currentTimeInterval = this.setInterval(function () {
  8067. /**
  8068. * Triggered at an interval of 250ms to indicated that time is passing in the video.
  8069. *
  8070. * @event Tech#timeupdate
  8071. * @type {EventTarget~Event}
  8072. */
  8073. this.trigger({
  8074. type: 'timeupdate',
  8075. target: this,
  8076. manuallyTriggered: true
  8077. }); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  8078. }, 250);
  8079. }
  8080. /**
  8081. * Stop the interval function created in {@link Tech#trackCurrentTime} so that the
  8082. * `timeupdate` event is no longer triggered.
  8083. *
  8084. * @listens {Tech#pause}
  8085. */
  8086. ;
  8087. _proto.stopTrackingCurrentTime = function stopTrackingCurrentTime() {
  8088. this.clearInterval(this.currentTimeInterval); // #1002 - if the video ends right before the next timeupdate would happen,
  8089. // the progress bar won't make it all the way to the end
  8090. this.trigger({
  8091. type: 'timeupdate',
  8092. target: this,
  8093. manuallyTriggered: true
  8094. });
  8095. }
  8096. /**
  8097. * Turn off all event polyfills, clear the `Tech`s {@link AudioTrackList},
  8098. * {@link VideoTrackList}, and {@link TextTrackList}, and dispose of this Tech.
  8099. *
  8100. * @fires Component#dispose
  8101. */
  8102. ;
  8103. _proto.dispose = function dispose() {
  8104. // clear out all tracks because we can't reuse them between techs
  8105. this.clearTracks(NORMAL.names); // Turn off any manual progress or timeupdate tracking
  8106. if (this.manualProgress) {
  8107. this.manualProgressOff();
  8108. }
  8109. if (this.manualTimeUpdates) {
  8110. this.manualTimeUpdatesOff();
  8111. }
  8112. _Component.prototype.dispose.call(this);
  8113. }
  8114. /**
  8115. * Clear out a single `TrackList` or an array of `TrackLists` given their names.
  8116. *
  8117. * > Note: Techs without source handlers should call this between sources for `video`
  8118. * & `audio` tracks. You don't want to use them between tracks!
  8119. *
  8120. * @param {string[]|string} types
  8121. * TrackList names to clear, valid names are `video`, `audio`, and
  8122. * `text`.
  8123. */
  8124. ;
  8125. _proto.clearTracks = function clearTracks(types) {
  8126. var _this3 = this;
  8127. types = [].concat(types); // clear out all tracks because we can't reuse them between techs
  8128. types.forEach(function (type) {
  8129. var list = _this3[type + "Tracks"]() || [];
  8130. var i = list.length;
  8131. while (i--) {
  8132. var track = list[i];
  8133. if (type === 'text') {
  8134. _this3.removeRemoteTextTrack(track);
  8135. }
  8136. list.removeTrack(track);
  8137. }
  8138. });
  8139. }
  8140. /**
  8141. * Remove any TextTracks added via addRemoteTextTrack that are
  8142. * flagged for automatic garbage collection
  8143. */
  8144. ;
  8145. _proto.cleanupAutoTextTracks = function cleanupAutoTextTracks() {
  8146. var list = this.autoRemoteTextTracks_ || [];
  8147. var i = list.length;
  8148. while (i--) {
  8149. var track = list[i];
  8150. this.removeRemoteTextTrack(track);
  8151. }
  8152. }
  8153. /**
  8154. * Reset the tech, which will removes all sources and reset the internal readyState.
  8155. *
  8156. * @abstract
  8157. */
  8158. ;
  8159. _proto.reset = function reset() {}
  8160. /**
  8161. * Get the value of `crossOrigin` from the tech.
  8162. *
  8163. * @abstract
  8164. *
  8165. * @see {Html5#crossOrigin}
  8166. */
  8167. ;
  8168. _proto.crossOrigin = function crossOrigin() {}
  8169. /**
  8170. * Set the value of `crossOrigin` on the tech.
  8171. *
  8172. * @abstract
  8173. *
  8174. * @param {string} crossOrigin the crossOrigin value
  8175. * @see {Html5#setCrossOrigin}
  8176. */
  8177. ;
  8178. _proto.setCrossOrigin = function setCrossOrigin() {}
  8179. /**
  8180. * Get or set an error on the Tech.
  8181. *
  8182. * @param {MediaError} [err]
  8183. * Error to set on the Tech
  8184. *
  8185. * @return {MediaError|null}
  8186. * The current error object on the tech, or null if there isn't one.
  8187. */
  8188. ;
  8189. _proto.error = function error(err) {
  8190. if (err !== undefined) {
  8191. this.error_ = new MediaError(err);
  8192. this.trigger('error');
  8193. }
  8194. return this.error_;
  8195. }
  8196. /**
  8197. * Returns the `TimeRange`s that have been played through for the current source.
  8198. *
  8199. * > NOTE: This implementation is incomplete. It does not track the played `TimeRange`.
  8200. * It only checks whether the source has played at all or not.
  8201. *
  8202. * @return {TimeRange}
  8203. * - A single time range if this video has played
  8204. * - An empty set of ranges if not.
  8205. */
  8206. ;
  8207. _proto.played = function played() {
  8208. if (this.hasStarted_) {
  8209. return createTimeRanges(0, 0);
  8210. }
  8211. return createTimeRanges();
  8212. }
  8213. /**
  8214. * Start playback
  8215. *
  8216. * @abstract
  8217. *
  8218. * @see {Html5#play}
  8219. */
  8220. ;
  8221. _proto.play = function play() {}
  8222. /**
  8223. * Set whether we are scrubbing or not
  8224. *
  8225. * @abstract
  8226. *
  8227. * @see {Html5#setScrubbing}
  8228. */
  8229. ;
  8230. _proto.setScrubbing = function setScrubbing() {}
  8231. /**
  8232. * Get whether we are scrubbing or not
  8233. *
  8234. * @abstract
  8235. *
  8236. * @see {Html5#scrubbing}
  8237. */
  8238. ;
  8239. _proto.scrubbing = function scrubbing() {}
  8240. /**
  8241. * Causes a manual time update to occur if {@link Tech#manualTimeUpdatesOn} was
  8242. * previously called.
  8243. *
  8244. * @fires Tech#timeupdate
  8245. */
  8246. ;
  8247. _proto.setCurrentTime = function setCurrentTime() {
  8248. // improve the accuracy of manual timeupdates
  8249. if (this.manualTimeUpdates) {
  8250. /**
  8251. * A manual `timeupdate` event.
  8252. *
  8253. * @event Tech#timeupdate
  8254. * @type {EventTarget~Event}
  8255. */
  8256. this.trigger({
  8257. type: 'timeupdate',
  8258. target: this,
  8259. manuallyTriggered: true
  8260. });
  8261. }
  8262. }
  8263. /**
  8264. * Turn on listeners for {@link VideoTrackList}, {@link {AudioTrackList}, and
  8265. * {@link TextTrackList} events.
  8266. *
  8267. * This adds {@link EventTarget~EventListeners} for `addtrack`, and `removetrack`.
  8268. *
  8269. * @fires Tech#audiotrackchange
  8270. * @fires Tech#videotrackchange
  8271. * @fires Tech#texttrackchange
  8272. */
  8273. ;
  8274. _proto.initTrackListeners = function initTrackListeners() {
  8275. var _this4 = this;
  8276. /**
  8277. * Triggered when tracks are added or removed on the Tech {@link AudioTrackList}
  8278. *
  8279. * @event Tech#audiotrackchange
  8280. * @type {EventTarget~Event}
  8281. */
  8282. /**
  8283. * Triggered when tracks are added or removed on the Tech {@link VideoTrackList}
  8284. *
  8285. * @event Tech#videotrackchange
  8286. * @type {EventTarget~Event}
  8287. */
  8288. /**
  8289. * Triggered when tracks are added or removed on the Tech {@link TextTrackList}
  8290. *
  8291. * @event Tech#texttrackchange
  8292. * @type {EventTarget~Event}
  8293. */
  8294. NORMAL.names.forEach(function (name) {
  8295. var props = NORMAL[name];
  8296. var trackListChanges = function trackListChanges() {
  8297. _this4.trigger(name + "trackchange");
  8298. };
  8299. var tracks = _this4[props.getterName]();
  8300. tracks.addEventListener('removetrack', trackListChanges);
  8301. tracks.addEventListener('addtrack', trackListChanges);
  8302. _this4.on('dispose', function () {
  8303. tracks.removeEventListener('removetrack', trackListChanges);
  8304. tracks.removeEventListener('addtrack', trackListChanges);
  8305. });
  8306. });
  8307. }
  8308. /**
  8309. * Emulate TextTracks using vtt.js if necessary
  8310. *
  8311. * @fires Tech#vttjsloaded
  8312. * @fires Tech#vttjserror
  8313. */
  8314. ;
  8315. _proto.addWebVttScript_ = function addWebVttScript_() {
  8316. var _this5 = this;
  8317. if (window.WebVTT) {
  8318. return;
  8319. } // Initially, Tech.el_ is a child of a dummy-div wait until the Component system
  8320. // signals that the Tech is ready at which point Tech.el_ is part of the DOM
  8321. // before inserting the WebVTT script
  8322. if (document.body.contains(this.el())) {
  8323. // load via require if available and vtt.js script location was not passed in
  8324. // as an option. novtt builds will turn the above require call into an empty object
  8325. // which will cause this if check to always fail.
  8326. if (!this.options_['vtt.js'] && isPlain(vtt) && Object.keys(vtt).length > 0) {
  8327. this.trigger('vttjsloaded');
  8328. return;
  8329. } // load vtt.js via the script location option or the cdn of no location was
  8330. // passed in
  8331. var script = document.createElement('script');
  8332. script.src = this.options_['vtt.js'] || 'https://vjs.zencdn.net/vttjs/0.14.1/vtt.min.js';
  8333. script.onload = function () {
  8334. /**
  8335. * Fired when vtt.js is loaded.
  8336. *
  8337. * @event Tech#vttjsloaded
  8338. * @type {EventTarget~Event}
  8339. */
  8340. _this5.trigger('vttjsloaded');
  8341. };
  8342. script.onerror = function () {
  8343. /**
  8344. * Fired when vtt.js was not loaded due to an error
  8345. *
  8346. * @event Tech#vttjsloaded
  8347. * @type {EventTarget~Event}
  8348. */
  8349. _this5.trigger('vttjserror');
  8350. };
  8351. this.on('dispose', function () {
  8352. script.onload = null;
  8353. script.onerror = null;
  8354. }); // but have not loaded yet and we set it to true before the inject so that
  8355. // we don't overwrite the injected window.WebVTT if it loads right away
  8356. window.WebVTT = true;
  8357. this.el().parentNode.appendChild(script);
  8358. } else {
  8359. this.ready(this.addWebVttScript_);
  8360. }
  8361. }
  8362. /**
  8363. * Emulate texttracks
  8364. *
  8365. */
  8366. ;
  8367. _proto.emulateTextTracks = function emulateTextTracks() {
  8368. var _this6 = this;
  8369. var tracks = this.textTracks();
  8370. var remoteTracks = this.remoteTextTracks();
  8371. var handleAddTrack = function handleAddTrack(e) {
  8372. return tracks.addTrack(e.track);
  8373. };
  8374. var handleRemoveTrack = function handleRemoveTrack(e) {
  8375. return tracks.removeTrack(e.track);
  8376. };
  8377. remoteTracks.on('addtrack', handleAddTrack);
  8378. remoteTracks.on('removetrack', handleRemoveTrack);
  8379. this.addWebVttScript_();
  8380. var updateDisplay = function updateDisplay() {
  8381. return _this6.trigger('texttrackchange');
  8382. };
  8383. var textTracksChanges = function textTracksChanges() {
  8384. updateDisplay();
  8385. for (var i = 0; i < tracks.length; i++) {
  8386. var track = tracks[i];
  8387. track.removeEventListener('cuechange', updateDisplay);
  8388. if (track.mode === 'showing') {
  8389. track.addEventListener('cuechange', updateDisplay);
  8390. }
  8391. }
  8392. };
  8393. textTracksChanges();
  8394. tracks.addEventListener('change', textTracksChanges);
  8395. tracks.addEventListener('addtrack', textTracksChanges);
  8396. tracks.addEventListener('removetrack', textTracksChanges);
  8397. this.on('dispose', function () {
  8398. remoteTracks.off('addtrack', handleAddTrack);
  8399. remoteTracks.off('removetrack', handleRemoveTrack);
  8400. tracks.removeEventListener('change', textTracksChanges);
  8401. tracks.removeEventListener('addtrack', textTracksChanges);
  8402. tracks.removeEventListener('removetrack', textTracksChanges);
  8403. for (var i = 0; i < tracks.length; i++) {
  8404. var track = tracks[i];
  8405. track.removeEventListener('cuechange', updateDisplay);
  8406. }
  8407. });
  8408. }
  8409. /**
  8410. * Create and returns a remote {@link TextTrack} object.
  8411. *
  8412. * @param {string} kind
  8413. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  8414. *
  8415. * @param {string} [label]
  8416. * Label to identify the text track
  8417. *
  8418. * @param {string} [language]
  8419. * Two letter language abbreviation
  8420. *
  8421. * @return {TextTrack}
  8422. * The TextTrack that gets created.
  8423. */
  8424. ;
  8425. _proto.addTextTrack = function addTextTrack(kind, label, language) {
  8426. if (!kind) {
  8427. throw new Error('TextTrack kind is required but was not provided');
  8428. }
  8429. return createTrackHelper(this, kind, label, language);
  8430. }
  8431. /**
  8432. * Create an emulated TextTrack for use by addRemoteTextTrack
  8433. *
  8434. * This is intended to be overridden by classes that inherit from
  8435. * Tech in order to create native or custom TextTracks.
  8436. *
  8437. * @param {Object} options
  8438. * The object should contain the options to initialize the TextTrack with.
  8439. *
  8440. * @param {string} [options.kind]
  8441. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
  8442. *
  8443. * @param {string} [options.label].
  8444. * Label to identify the text track
  8445. *
  8446. * @param {string} [options.language]
  8447. * Two letter language abbreviation.
  8448. *
  8449. * @return {HTMLTrackElement}
  8450. * The track element that gets created.
  8451. */
  8452. ;
  8453. _proto.createRemoteTextTrack = function createRemoteTextTrack(options) {
  8454. var track = mergeOptions$3(options, {
  8455. tech: this
  8456. });
  8457. return new REMOTE.remoteTextEl.TrackClass(track);
  8458. }
  8459. /**
  8460. * Creates a remote text track object and returns an html track element.
  8461. *
  8462. * > Note: This can be an emulated {@link HTMLTrackElement} or a native one.
  8463. *
  8464. * @param {Object} options
  8465. * See {@link Tech#createRemoteTextTrack} for more detailed properties.
  8466. *
  8467. * @param {boolean} [manualCleanup=true]
  8468. * - When false: the TextTrack will be automatically removed from the video
  8469. * element whenever the source changes
  8470. * - When True: The TextTrack will have to be cleaned up manually
  8471. *
  8472. * @return {HTMLTrackElement}
  8473. * An Html Track Element.
  8474. *
  8475. * @deprecated The default functionality for this function will be equivalent
  8476. * to "manualCleanup=false" in the future. The manualCleanup parameter will
  8477. * also be removed.
  8478. */
  8479. ;
  8480. _proto.addRemoteTextTrack = function addRemoteTextTrack(options, manualCleanup) {
  8481. var _this7 = this;
  8482. if (options === void 0) {
  8483. options = {};
  8484. }
  8485. var htmlTrackElement = this.createRemoteTextTrack(options);
  8486. if (manualCleanup !== true && manualCleanup !== false) {
  8487. // deprecation warning
  8488. 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');
  8489. manualCleanup = true;
  8490. } // store HTMLTrackElement and TextTrack to remote list
  8491. this.remoteTextTrackEls().addTrackElement_(htmlTrackElement);
  8492. this.remoteTextTracks().addTrack(htmlTrackElement.track);
  8493. if (manualCleanup !== true) {
  8494. // create the TextTrackList if it doesn't exist
  8495. this.ready(function () {
  8496. return _this7.autoRemoteTextTracks_.addTrack(htmlTrackElement.track);
  8497. });
  8498. }
  8499. return htmlTrackElement;
  8500. }
  8501. /**
  8502. * Remove a remote text track from the remote `TextTrackList`.
  8503. *
  8504. * @param {TextTrack} track
  8505. * `TextTrack` to remove from the `TextTrackList`
  8506. */
  8507. ;
  8508. _proto.removeRemoteTextTrack = function removeRemoteTextTrack(track) {
  8509. var trackElement = this.remoteTextTrackEls().getTrackElementByTrack_(track); // remove HTMLTrackElement and TextTrack from remote list
  8510. this.remoteTextTrackEls().removeTrackElement_(trackElement);
  8511. this.remoteTextTracks().removeTrack(track);
  8512. this.autoRemoteTextTracks_.removeTrack(track);
  8513. }
  8514. /**
  8515. * Gets available media playback quality metrics as specified by the W3C's Media
  8516. * Playback Quality API.
  8517. *
  8518. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  8519. *
  8520. * @return {Object}
  8521. * An object with supported media playback quality metrics
  8522. *
  8523. * @abstract
  8524. */
  8525. ;
  8526. _proto.getVideoPlaybackQuality = function getVideoPlaybackQuality() {
  8527. return {};
  8528. }
  8529. /**
  8530. * Attempt to create a floating video window always on top of other windows
  8531. * so that users may continue consuming media while they interact with other
  8532. * content sites, or applications on their device.
  8533. *
  8534. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  8535. *
  8536. * @return {Promise|undefined}
  8537. * A promise with a Picture-in-Picture window if the browser supports
  8538. * Promises (or one was passed in as an option). It returns undefined
  8539. * otherwise.
  8540. *
  8541. * @abstract
  8542. */
  8543. ;
  8544. _proto.requestPictureInPicture = function requestPictureInPicture() {
  8545. var PromiseClass = this.options_.Promise || window.Promise;
  8546. if (PromiseClass) {
  8547. return PromiseClass.reject();
  8548. }
  8549. }
  8550. /**
  8551. * A method to check for the value of the 'disablePictureInPicture' <video> property.
  8552. * Defaults to true, as it should be considered disabled if the tech does not support pip
  8553. *
  8554. * @abstract
  8555. */
  8556. ;
  8557. _proto.disablePictureInPicture = function disablePictureInPicture() {
  8558. return true;
  8559. }
  8560. /**
  8561. * A method to set or unset the 'disablePictureInPicture' <video> property.
  8562. *
  8563. * @abstract
  8564. */
  8565. ;
  8566. _proto.setDisablePictureInPicture = function setDisablePictureInPicture() {}
  8567. /**
  8568. * A fallback implementation of requestVideoFrameCallback using requestAnimationFrame
  8569. *
  8570. * @param {function} cb
  8571. * @return {number} request id
  8572. */
  8573. ;
  8574. _proto.requestVideoFrameCallback = function requestVideoFrameCallback(cb) {
  8575. var _this8 = this;
  8576. var id = newGUID();
  8577. if (!this.isReady_ || this.paused()) {
  8578. this.queuedHanders_.add(id);
  8579. this.one('playing', function () {
  8580. if (_this8.queuedHanders_.has(id)) {
  8581. _this8.queuedHanders_["delete"](id);
  8582. cb();
  8583. }
  8584. });
  8585. } else {
  8586. this.requestNamedAnimationFrame(id, cb);
  8587. }
  8588. return id;
  8589. }
  8590. /**
  8591. * A fallback implementation of cancelVideoFrameCallback
  8592. *
  8593. * @param {number} id id of callback to be cancelled
  8594. */
  8595. ;
  8596. _proto.cancelVideoFrameCallback = function cancelVideoFrameCallback(id) {
  8597. if (this.queuedHanders_.has(id)) {
  8598. this.queuedHanders_["delete"](id);
  8599. } else {
  8600. this.cancelNamedAnimationFrame(id);
  8601. }
  8602. }
  8603. /**
  8604. * A method to set a poster from a `Tech`.
  8605. *
  8606. * @abstract
  8607. */
  8608. ;
  8609. _proto.setPoster = function setPoster() {}
  8610. /**
  8611. * A method to check for the presence of the 'playsinline' <video> attribute.
  8612. *
  8613. * @abstract
  8614. */
  8615. ;
  8616. _proto.playsinline = function playsinline() {}
  8617. /**
  8618. * A method to set or unset the 'playsinline' <video> attribute.
  8619. *
  8620. * @abstract
  8621. */
  8622. ;
  8623. _proto.setPlaysinline = function setPlaysinline() {}
  8624. /**
  8625. * Attempt to force override of native audio tracks.
  8626. *
  8627. * @param {boolean} override - If set to true native audio will be overridden,
  8628. * otherwise native audio will potentially be used.
  8629. *
  8630. * @abstract
  8631. */
  8632. ;
  8633. _proto.overrideNativeAudioTracks = function overrideNativeAudioTracks() {}
  8634. /**
  8635. * Attempt to force override of native video tracks.
  8636. *
  8637. * @param {boolean} override - If set to true native video will be overridden,
  8638. * otherwise native video will potentially be used.
  8639. *
  8640. * @abstract
  8641. */
  8642. ;
  8643. _proto.overrideNativeVideoTracks = function overrideNativeVideoTracks() {}
  8644. /*
  8645. * Check if the tech can support the given mime-type.
  8646. *
  8647. * The base tech does not support any type, but source handlers might
  8648. * overwrite this.
  8649. *
  8650. * @param {string} type
  8651. * The mimetype to check for support
  8652. *
  8653. * @return {string}
  8654. * 'probably', 'maybe', or empty string
  8655. *
  8656. * @see [Spec]{@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canPlayType}
  8657. *
  8658. * @abstract
  8659. */
  8660. ;
  8661. _proto.canPlayType = function canPlayType() {
  8662. return '';
  8663. }
  8664. /**
  8665. * Check if the type is supported by this tech.
  8666. *
  8667. * The base tech does not support any type, but source handlers might
  8668. * overwrite this.
  8669. *
  8670. * @param {string} type
  8671. * The media type to check
  8672. * @return {string} Returns the native video element's response
  8673. */
  8674. ;
  8675. Tech.canPlayType = function canPlayType() {
  8676. return '';
  8677. }
  8678. /**
  8679. * Check if the tech can support the given source
  8680. *
  8681. * @param {Object} srcObj
  8682. * The source object
  8683. * @param {Object} options
  8684. * The options passed to the tech
  8685. * @return {string} 'probably', 'maybe', or '' (empty string)
  8686. */
  8687. ;
  8688. Tech.canPlaySource = function canPlaySource(srcObj, options) {
  8689. return Tech.canPlayType(srcObj.type);
  8690. }
  8691. /*
  8692. * Return whether the argument is a Tech or not.
  8693. * Can be passed either a Class like `Html5` or a instance like `player.tech_`
  8694. *
  8695. * @param {Object} component
  8696. * The item to check
  8697. *
  8698. * @return {boolean}
  8699. * Whether it is a tech or not
  8700. * - True if it is a tech
  8701. * - False if it is not
  8702. */
  8703. ;
  8704. Tech.isTech = function isTech(component) {
  8705. return component.prototype instanceof Tech || component instanceof Tech || component === Tech;
  8706. }
  8707. /**
  8708. * Registers a `Tech` into a shared list for videojs.
  8709. *
  8710. * @param {string} name
  8711. * Name of the `Tech` to register.
  8712. *
  8713. * @param {Object} tech
  8714. * The `Tech` class to register.
  8715. */
  8716. ;
  8717. Tech.registerTech = function registerTech(name, tech) {
  8718. if (!Tech.techs_) {
  8719. Tech.techs_ = {};
  8720. }
  8721. if (!Tech.isTech(tech)) {
  8722. throw new Error("Tech " + name + " must be a Tech");
  8723. }
  8724. if (!Tech.canPlayType) {
  8725. throw new Error('Techs must have a static canPlayType method on them');
  8726. }
  8727. if (!Tech.canPlaySource) {
  8728. throw new Error('Techs must have a static canPlaySource method on them');
  8729. }
  8730. name = toTitleCase$1(name);
  8731. Tech.techs_[name] = tech;
  8732. Tech.techs_[toLowerCase(name)] = tech;
  8733. if (name !== 'Tech') {
  8734. // camel case the techName for use in techOrder
  8735. Tech.defaultTechOrder_.push(name);
  8736. }
  8737. return tech;
  8738. }
  8739. /**
  8740. * Get a `Tech` from the shared list by name.
  8741. *
  8742. * @param {string} name
  8743. * `camelCase` or `TitleCase` name of the Tech to get
  8744. *
  8745. * @return {Tech|undefined}
  8746. * The `Tech` or undefined if there was no tech with the name requested.
  8747. */
  8748. ;
  8749. Tech.getTech = function getTech(name) {
  8750. if (!name) {
  8751. return;
  8752. }
  8753. if (Tech.techs_ && Tech.techs_[name]) {
  8754. return Tech.techs_[name];
  8755. }
  8756. name = toTitleCase$1(name);
  8757. if (window && window.videojs && window.videojs[name]) {
  8758. log$1.warn("The " + name + " tech was added to the videojs object when it should be registered using videojs.registerTech(name, tech)");
  8759. return window.videojs[name];
  8760. }
  8761. };
  8762. return Tech;
  8763. }(Component$1);
  8764. /**
  8765. * Get the {@link VideoTrackList}
  8766. *
  8767. * @returns {VideoTrackList}
  8768. * @method Tech.prototype.videoTracks
  8769. */
  8770. /**
  8771. * Get the {@link AudioTrackList}
  8772. *
  8773. * @returns {AudioTrackList}
  8774. * @method Tech.prototype.audioTracks
  8775. */
  8776. /**
  8777. * Get the {@link TextTrackList}
  8778. *
  8779. * @returns {TextTrackList}
  8780. * @method Tech.prototype.textTracks
  8781. */
  8782. /**
  8783. * Get the remote element {@link TextTrackList}
  8784. *
  8785. * @returns {TextTrackList}
  8786. * @method Tech.prototype.remoteTextTracks
  8787. */
  8788. /**
  8789. * Get the remote element {@link HtmlTrackElementList}
  8790. *
  8791. * @returns {HtmlTrackElementList}
  8792. * @method Tech.prototype.remoteTextTrackEls
  8793. */
  8794. ALL.names.forEach(function (name) {
  8795. var props = ALL[name];
  8796. Tech.prototype[props.getterName] = function () {
  8797. this[props.privateName] = this[props.privateName] || new props.ListClass();
  8798. return this[props.privateName];
  8799. };
  8800. });
  8801. /**
  8802. * List of associated text tracks
  8803. *
  8804. * @type {TextTrackList}
  8805. * @private
  8806. * @property Tech#textTracks_
  8807. */
  8808. /**
  8809. * List of associated audio tracks.
  8810. *
  8811. * @type {AudioTrackList}
  8812. * @private
  8813. * @property Tech#audioTracks_
  8814. */
  8815. /**
  8816. * List of associated video tracks.
  8817. *
  8818. * @type {VideoTrackList}
  8819. * @private
  8820. * @property Tech#videoTracks_
  8821. */
  8822. /**
  8823. * Boolean indicating whether the `Tech` supports volume control.
  8824. *
  8825. * @type {boolean}
  8826. * @default
  8827. */
  8828. Tech.prototype.featuresVolumeControl = true;
  8829. /**
  8830. * Boolean indicating whether the `Tech` supports muting volume.
  8831. *
  8832. * @type {bolean}
  8833. * @default
  8834. */
  8835. Tech.prototype.featuresMuteControl = true;
  8836. /**
  8837. * Boolean indicating whether the `Tech` supports fullscreen resize control.
  8838. * Resizing plugins using request fullscreen reloads the plugin
  8839. *
  8840. * @type {boolean}
  8841. * @default
  8842. */
  8843. Tech.prototype.featuresFullscreenResize = false;
  8844. /**
  8845. * Boolean indicating whether the `Tech` supports changing the speed at which the video
  8846. * plays. Examples:
  8847. * - Set player to play 2x (twice) as fast
  8848. * - Set player to play 0.5x (half) as fast
  8849. *
  8850. * @type {boolean}
  8851. * @default
  8852. */
  8853. Tech.prototype.featuresPlaybackRate = false;
  8854. /**
  8855. * Boolean indicating whether the `Tech` supports the `progress` event. This is currently
  8856. * not triggered by video-js-swf. This will be used to determine if
  8857. * {@link Tech#manualProgressOn} should be called.
  8858. *
  8859. * @type {boolean}
  8860. * @default
  8861. */
  8862. Tech.prototype.featuresProgressEvents = false;
  8863. /**
  8864. * Boolean indicating whether the `Tech` supports the `sourceset` event.
  8865. *
  8866. * A tech should set this to `true` and then use {@link Tech#triggerSourceset}
  8867. * to trigger a {@link Tech#event:sourceset} at the earliest time after getting
  8868. * a new source.
  8869. *
  8870. * @type {boolean}
  8871. * @default
  8872. */
  8873. Tech.prototype.featuresSourceset = false;
  8874. /**
  8875. * Boolean indicating whether the `Tech` supports the `timeupdate` event. This is currently
  8876. * not triggered by video-js-swf. This will be used to determine if
  8877. * {@link Tech#manualTimeUpdates} should be called.
  8878. *
  8879. * @type {boolean}
  8880. * @default
  8881. */
  8882. Tech.prototype.featuresTimeupdateEvents = false;
  8883. /**
  8884. * Boolean indicating whether the `Tech` supports the native `TextTrack`s.
  8885. * This will help us integrate with native `TextTrack`s if the browser supports them.
  8886. *
  8887. * @type {boolean}
  8888. * @default
  8889. */
  8890. Tech.prototype.featuresNativeTextTracks = false;
  8891. /**
  8892. * Boolean indicating whether the `Tech` supports `requestVideoFrameCallback`.
  8893. *
  8894. * @type {boolean}
  8895. * @default
  8896. */
  8897. Tech.prototype.featuresVideoFrameCallback = false;
  8898. /**
  8899. * A functional mixin for techs that want to use the Source Handler pattern.
  8900. * Source handlers are scripts for handling specific formats.
  8901. * The source handler pattern is used for adaptive formats (HLS, DASH) that
  8902. * manually load video data and feed it into a Source Buffer (Media Source Extensions)
  8903. * Example: `Tech.withSourceHandlers.call(MyTech);`
  8904. *
  8905. * @param {Tech} _Tech
  8906. * The tech to add source handler functions to.
  8907. *
  8908. * @mixes Tech~SourceHandlerAdditions
  8909. */
  8910. Tech.withSourceHandlers = function (_Tech) {
  8911. /**
  8912. * Register a source handler
  8913. *
  8914. * @param {Function} handler
  8915. * The source handler class
  8916. *
  8917. * @param {number} [index]
  8918. * Register it at the following index
  8919. */
  8920. _Tech.registerSourceHandler = function (handler, index) {
  8921. var handlers = _Tech.sourceHandlers;
  8922. if (!handlers) {
  8923. handlers = _Tech.sourceHandlers = [];
  8924. }
  8925. if (index === undefined) {
  8926. // add to the end of the list
  8927. index = handlers.length;
  8928. }
  8929. handlers.splice(index, 0, handler);
  8930. };
  8931. /**
  8932. * Check if the tech can support the given type. Also checks the
  8933. * Techs sourceHandlers.
  8934. *
  8935. * @param {string} type
  8936. * The mimetype to check.
  8937. *
  8938. * @return {string}
  8939. * 'probably', 'maybe', or '' (empty string)
  8940. */
  8941. _Tech.canPlayType = function (type) {
  8942. var handlers = _Tech.sourceHandlers || [];
  8943. var can;
  8944. for (var i = 0; i < handlers.length; i++) {
  8945. can = handlers[i].canPlayType(type);
  8946. if (can) {
  8947. return can;
  8948. }
  8949. }
  8950. return '';
  8951. };
  8952. /**
  8953. * Returns the first source handler that supports the source.
  8954. *
  8955. * TODO: Answer question: should 'probably' be prioritized over 'maybe'
  8956. *
  8957. * @param {Tech~SourceObject} source
  8958. * The source object
  8959. *
  8960. * @param {Object} options
  8961. * The options passed to the tech
  8962. *
  8963. * @return {SourceHandler|null}
  8964. * The first source handler that supports the source or null if
  8965. * no SourceHandler supports the source
  8966. */
  8967. _Tech.selectSourceHandler = function (source, options) {
  8968. var handlers = _Tech.sourceHandlers || [];
  8969. var can;
  8970. for (var i = 0; i < handlers.length; i++) {
  8971. can = handlers[i].canHandleSource(source, options);
  8972. if (can) {
  8973. return handlers[i];
  8974. }
  8975. }
  8976. return null;
  8977. };
  8978. /**
  8979. * Check if the tech can support the given source.
  8980. *
  8981. * @param {Tech~SourceObject} srcObj
  8982. * The source object
  8983. *
  8984. * @param {Object} options
  8985. * The options passed to the tech
  8986. *
  8987. * @return {string}
  8988. * 'probably', 'maybe', or '' (empty string)
  8989. */
  8990. _Tech.canPlaySource = function (srcObj, options) {
  8991. var sh = _Tech.selectSourceHandler(srcObj, options);
  8992. if (sh) {
  8993. return sh.canHandleSource(srcObj, options);
  8994. }
  8995. return '';
  8996. };
  8997. /**
  8998. * When using a source handler, prefer its implementation of
  8999. * any function normally provided by the tech.
  9000. */
  9001. var deferrable = ['seekable', 'seeking', 'duration'];
  9002. /**
  9003. * A wrapper around {@link Tech#seekable} that will call a `SourceHandler`s seekable
  9004. * function if it exists, with a fallback to the Techs seekable function.
  9005. *
  9006. * @method _Tech.seekable
  9007. */
  9008. /**
  9009. * A wrapper around {@link Tech#duration} that will call a `SourceHandler`s duration
  9010. * function if it exists, otherwise it will fallback to the techs duration function.
  9011. *
  9012. * @method _Tech.duration
  9013. */
  9014. deferrable.forEach(function (fnName) {
  9015. var originalFn = this[fnName];
  9016. if (typeof originalFn !== 'function') {
  9017. return;
  9018. }
  9019. this[fnName] = function () {
  9020. if (this.sourceHandler_ && this.sourceHandler_[fnName]) {
  9021. return this.sourceHandler_[fnName].apply(this.sourceHandler_, arguments);
  9022. }
  9023. return originalFn.apply(this, arguments);
  9024. };
  9025. }, _Tech.prototype);
  9026. /**
  9027. * Create a function for setting the source using a source object
  9028. * and source handlers.
  9029. * Should never be called unless a source handler was found.
  9030. *
  9031. * @param {Tech~SourceObject} source
  9032. * A source object with src and type keys
  9033. */
  9034. _Tech.prototype.setSource = function (source) {
  9035. var sh = _Tech.selectSourceHandler(source, this.options_);
  9036. if (!sh) {
  9037. // Fall back to a native source hander when unsupported sources are
  9038. // deliberately set
  9039. if (_Tech.nativeSourceHandler) {
  9040. sh = _Tech.nativeSourceHandler;
  9041. } else {
  9042. log$1.error('No source handler found for the current source.');
  9043. }
  9044. } // Dispose any existing source handler
  9045. this.disposeSourceHandler();
  9046. this.off('dispose', this.disposeSourceHandler_);
  9047. if (sh !== _Tech.nativeSourceHandler) {
  9048. this.currentSource_ = source;
  9049. }
  9050. this.sourceHandler_ = sh.handleSource(source, this, this.options_);
  9051. this.one('dispose', this.disposeSourceHandler_);
  9052. };
  9053. /**
  9054. * Clean up any existing SourceHandlers and listeners when the Tech is disposed.
  9055. *
  9056. * @listens Tech#dispose
  9057. */
  9058. _Tech.prototype.disposeSourceHandler = function () {
  9059. // if we have a source and get another one
  9060. // then we are loading something new
  9061. // than clear all of our current tracks
  9062. if (this.currentSource_) {
  9063. this.clearTracks(['audio', 'video']);
  9064. this.currentSource_ = null;
  9065. } // always clean up auto-text tracks
  9066. this.cleanupAutoTextTracks();
  9067. if (this.sourceHandler_) {
  9068. if (this.sourceHandler_.dispose) {
  9069. this.sourceHandler_.dispose();
  9070. }
  9071. this.sourceHandler_ = null;
  9072. }
  9073. };
  9074. }; // The base Tech class needs to be registered as a Component. It is the only
  9075. // Tech that can be registered as a Component.
  9076. Component$1.registerComponent('Tech', Tech);
  9077. Tech.registerTech('Tech', Tech);
  9078. /**
  9079. * A list of techs that should be added to techOrder on Players
  9080. *
  9081. * @private
  9082. */
  9083. Tech.defaultTechOrder_ = [];
  9084. /**
  9085. * @file middleware.js
  9086. * @module middleware
  9087. */
  9088. var middlewares = {};
  9089. var middlewareInstances = {};
  9090. var TERMINATOR = {};
  9091. /**
  9092. * A middleware object is a plain JavaScript object that has methods that
  9093. * match the {@link Tech} methods found in the lists of allowed
  9094. * {@link module:middleware.allowedGetters|getters},
  9095. * {@link module:middleware.allowedSetters|setters}, and
  9096. * {@link module:middleware.allowedMediators|mediators}.
  9097. *
  9098. * @typedef {Object} MiddlewareObject
  9099. */
  9100. /**
  9101. * A middleware factory function that should return a
  9102. * {@link module:middleware~MiddlewareObject|MiddlewareObject}.
  9103. *
  9104. * This factory will be called for each player when needed, with the player
  9105. * passed in as an argument.
  9106. *
  9107. * @callback MiddlewareFactory
  9108. * @param {Player} player
  9109. * A Video.js player.
  9110. */
  9111. /**
  9112. * Define a middleware that the player should use by way of a factory function
  9113. * that returns a middleware object.
  9114. *
  9115. * @param {string} type
  9116. * The MIME type to match or `"*"` for all MIME types.
  9117. *
  9118. * @param {MiddlewareFactory} middleware
  9119. * A middleware factory function that will be executed for
  9120. * matching types.
  9121. */
  9122. function use(type, middleware) {
  9123. middlewares[type] = middlewares[type] || [];
  9124. middlewares[type].push(middleware);
  9125. }
  9126. /**
  9127. * Asynchronously sets a source using middleware by recursing through any
  9128. * matching middlewares and calling `setSource` on each, passing along the
  9129. * previous returned value each time.
  9130. *
  9131. * @param {Player} player
  9132. * A {@link Player} instance.
  9133. *
  9134. * @param {Tech~SourceObject} src
  9135. * A source object.
  9136. *
  9137. * @param {Function}
  9138. * The next middleware to run.
  9139. */
  9140. function setSource(player, src, next) {
  9141. player.setTimeout(function () {
  9142. return setSourceHelper(src, middlewares[src.type], next, player);
  9143. }, 1);
  9144. }
  9145. /**
  9146. * When the tech is set, passes the tech to each middleware's `setTech` method.
  9147. *
  9148. * @param {Object[]} middleware
  9149. * An array of middleware instances.
  9150. *
  9151. * @param {Tech} tech
  9152. * A Video.js tech.
  9153. */
  9154. function setTech(middleware, tech) {
  9155. middleware.forEach(function (mw) {
  9156. return mw.setTech && mw.setTech(tech);
  9157. });
  9158. }
  9159. /**
  9160. * Calls a getter on the tech first, through each middleware
  9161. * from right to left to the player.
  9162. *
  9163. * @param {Object[]} middleware
  9164. * An array of middleware instances.
  9165. *
  9166. * @param {Tech} tech
  9167. * The current tech.
  9168. *
  9169. * @param {string} method
  9170. * A method name.
  9171. *
  9172. * @return {Mixed}
  9173. * The final value from the tech after middleware has intercepted it.
  9174. */
  9175. function get(middleware, tech, method) {
  9176. return middleware.reduceRight(middlewareIterator(method), tech[method]());
  9177. }
  9178. /**
  9179. * Takes the argument given to the player and calls the setter method on each
  9180. * middleware from left to right to the tech.
  9181. *
  9182. * @param {Object[]} middleware
  9183. * An array of middleware instances.
  9184. *
  9185. * @param {Tech} tech
  9186. * The current tech.
  9187. *
  9188. * @param {string} method
  9189. * A method name.
  9190. *
  9191. * @param {Mixed} arg
  9192. * The value to set on the tech.
  9193. *
  9194. * @return {Mixed}
  9195. * The return value of the `method` of the `tech`.
  9196. */
  9197. function set(middleware, tech, method, arg) {
  9198. return tech[method](middleware.reduce(middlewareIterator(method), arg));
  9199. }
  9200. /**
  9201. * Takes the argument given to the player and calls the `call` version of the
  9202. * method on each middleware from left to right.
  9203. *
  9204. * Then, call the passed in method on the tech and return the result unchanged
  9205. * back to the player, through middleware, this time from right to left.
  9206. *
  9207. * @param {Object[]} middleware
  9208. * An array of middleware instances.
  9209. *
  9210. * @param {Tech} tech
  9211. * The current tech.
  9212. *
  9213. * @param {string} method
  9214. * A method name.
  9215. *
  9216. * @param {Mixed} arg
  9217. * The value to set on the tech.
  9218. *
  9219. * @return {Mixed}
  9220. * The return value of the `method` of the `tech`, regardless of the
  9221. * return values of middlewares.
  9222. */
  9223. function mediate(middleware, tech, method, arg) {
  9224. if (arg === void 0) {
  9225. arg = null;
  9226. }
  9227. var callMethod = 'call' + toTitleCase$1(method);
  9228. var middlewareValue = middleware.reduce(middlewareIterator(callMethod), arg);
  9229. var terminated = middlewareValue === TERMINATOR; // deprecated. The `null` return value should instead return TERMINATOR to
  9230. // prevent confusion if a techs method actually returns null.
  9231. var returnValue = terminated ? null : tech[method](middlewareValue);
  9232. executeRight(middleware, method, returnValue, terminated);
  9233. return returnValue;
  9234. }
  9235. /**
  9236. * Enumeration of allowed getters where the keys are method names.
  9237. *
  9238. * @type {Object}
  9239. */
  9240. var allowedGetters = {
  9241. buffered: 1,
  9242. currentTime: 1,
  9243. duration: 1,
  9244. muted: 1,
  9245. played: 1,
  9246. paused: 1,
  9247. seekable: 1,
  9248. volume: 1,
  9249. ended: 1
  9250. };
  9251. /**
  9252. * Enumeration of allowed setters where the keys are method names.
  9253. *
  9254. * @type {Object}
  9255. */
  9256. var allowedSetters = {
  9257. setCurrentTime: 1,
  9258. setMuted: 1,
  9259. setVolume: 1
  9260. };
  9261. /**
  9262. * Enumeration of allowed mediators where the keys are method names.
  9263. *
  9264. * @type {Object}
  9265. */
  9266. var allowedMediators = {
  9267. play: 1,
  9268. pause: 1
  9269. };
  9270. function middlewareIterator(method) {
  9271. return function (value, mw) {
  9272. // if the previous middleware terminated, pass along the termination
  9273. if (value === TERMINATOR) {
  9274. return TERMINATOR;
  9275. }
  9276. if (mw[method]) {
  9277. return mw[method](value);
  9278. }
  9279. return value;
  9280. };
  9281. }
  9282. function executeRight(mws, method, value, terminated) {
  9283. for (var i = mws.length - 1; i >= 0; i--) {
  9284. var mw = mws[i];
  9285. if (mw[method]) {
  9286. mw[method](terminated, value);
  9287. }
  9288. }
  9289. }
  9290. /**
  9291. * Clear the middleware cache for a player.
  9292. *
  9293. * @param {Player} player
  9294. * A {@link Player} instance.
  9295. */
  9296. function clearCacheForPlayer(player) {
  9297. middlewareInstances[player.id()] = null;
  9298. }
  9299. /**
  9300. * {
  9301. * [playerId]: [[mwFactory, mwInstance], ...]
  9302. * }
  9303. *
  9304. * @private
  9305. */
  9306. function getOrCreateFactory(player, mwFactory) {
  9307. var mws = middlewareInstances[player.id()];
  9308. var mw = null;
  9309. if (mws === undefined || mws === null) {
  9310. mw = mwFactory(player);
  9311. middlewareInstances[player.id()] = [[mwFactory, mw]];
  9312. return mw;
  9313. }
  9314. for (var i = 0; i < mws.length; i++) {
  9315. var _mws$i = mws[i],
  9316. mwf = _mws$i[0],
  9317. mwi = _mws$i[1];
  9318. if (mwf !== mwFactory) {
  9319. continue;
  9320. }
  9321. mw = mwi;
  9322. }
  9323. if (mw === null) {
  9324. mw = mwFactory(player);
  9325. mws.push([mwFactory, mw]);
  9326. }
  9327. return mw;
  9328. }
  9329. function setSourceHelper(src, middleware, next, player, acc, lastRun) {
  9330. if (src === void 0) {
  9331. src = {};
  9332. }
  9333. if (middleware === void 0) {
  9334. middleware = [];
  9335. }
  9336. if (acc === void 0) {
  9337. acc = [];
  9338. }
  9339. if (lastRun === void 0) {
  9340. lastRun = false;
  9341. }
  9342. var _middleware = middleware,
  9343. mwFactory = _middleware[0],
  9344. mwrest = _middleware.slice(1); // if mwFactory is a string, then we're at a fork in the road
  9345. if (typeof mwFactory === 'string') {
  9346. setSourceHelper(src, middlewares[mwFactory], next, player, acc, lastRun); // if we have an mwFactory, call it with the player to get the mw,
  9347. // then call the mw's setSource method
  9348. } else if (mwFactory) {
  9349. var mw = getOrCreateFactory(player, mwFactory); // if setSource isn't present, implicitly select this middleware
  9350. if (!mw.setSource) {
  9351. acc.push(mw);
  9352. return setSourceHelper(src, mwrest, next, player, acc, lastRun);
  9353. }
  9354. mw.setSource(assign$1({}, src), function (err, _src) {
  9355. // something happened, try the next middleware on the current level
  9356. // make sure to use the old src
  9357. if (err) {
  9358. return setSourceHelper(src, mwrest, next, player, acc, lastRun);
  9359. } // we've succeeded, now we need to go deeper
  9360. acc.push(mw); // if it's the same type, continue down the current chain
  9361. // otherwise, we want to go down the new chain
  9362. setSourceHelper(_src, src.type === _src.type ? mwrest : middlewares[_src.type], next, player, acc, lastRun);
  9363. });
  9364. } else if (mwrest.length) {
  9365. setSourceHelper(src, mwrest, next, player, acc, lastRun);
  9366. } else if (lastRun) {
  9367. next(src, acc);
  9368. } else {
  9369. setSourceHelper(src, middlewares['*'], next, player, acc, true);
  9370. }
  9371. }
  9372. /**
  9373. * Mimetypes
  9374. *
  9375. * @see https://www.iana.org/assignments/media-types/media-types.xhtml
  9376. * @typedef Mimetypes~Kind
  9377. * @enum
  9378. */
  9379. var MimetypesKind = {
  9380. opus: 'video/ogg',
  9381. ogv: 'video/ogg',
  9382. mp4: 'video/mp4',
  9383. mov: 'video/mp4',
  9384. m4v: 'video/mp4',
  9385. mkv: 'video/x-matroska',
  9386. m4a: 'audio/mp4',
  9387. mp3: 'audio/mpeg',
  9388. aac: 'audio/aac',
  9389. caf: 'audio/x-caf',
  9390. flac: 'audio/flac',
  9391. oga: 'audio/ogg',
  9392. wav: 'audio/wav',
  9393. m3u8: 'application/x-mpegURL',
  9394. mpd: 'application/dash+xml',
  9395. jpg: 'image/jpeg',
  9396. jpeg: 'image/jpeg',
  9397. gif: 'image/gif',
  9398. png: 'image/png',
  9399. svg: 'image/svg+xml',
  9400. webp: 'image/webp'
  9401. };
  9402. /**
  9403. * Get the mimetype of a given src url if possible
  9404. *
  9405. * @param {string} src
  9406. * The url to the src
  9407. *
  9408. * @return {string}
  9409. * return the mimetype if it was known or empty string otherwise
  9410. */
  9411. var getMimetype = function getMimetype(src) {
  9412. if (src === void 0) {
  9413. src = '';
  9414. }
  9415. var ext = getFileExtension(src);
  9416. var mimetype = MimetypesKind[ext.toLowerCase()];
  9417. return mimetype || '';
  9418. };
  9419. /**
  9420. * Find the mime type of a given source string if possible. Uses the player
  9421. * source cache.
  9422. *
  9423. * @param {Player} player
  9424. * The player object
  9425. *
  9426. * @param {string} src
  9427. * The source string
  9428. *
  9429. * @return {string}
  9430. * The type that was found
  9431. */
  9432. var findMimetype = function findMimetype(player, src) {
  9433. if (!src) {
  9434. return '';
  9435. } // 1. check for the type in the `source` cache
  9436. if (player.cache_.source.src === src && player.cache_.source.type) {
  9437. return player.cache_.source.type;
  9438. } // 2. see if we have this source in our `currentSources` cache
  9439. var matchingSources = player.cache_.sources.filter(function (s) {
  9440. return s.src === src;
  9441. });
  9442. if (matchingSources.length) {
  9443. return matchingSources[0].type;
  9444. } // 3. look for the src url in source elements and use the type there
  9445. var sources = player.$$('source');
  9446. for (var i = 0; i < sources.length; i++) {
  9447. var s = sources[i];
  9448. if (s.type && s.src && s.src === src) {
  9449. return s.type;
  9450. }
  9451. } // 4. finally fallback to our list of mime types based on src url extension
  9452. return getMimetype(src);
  9453. };
  9454. /**
  9455. * @module filter-source
  9456. */
  9457. /**
  9458. * Filter out single bad source objects or multiple source objects in an
  9459. * array. Also flattens nested source object arrays into a 1 dimensional
  9460. * array of source objects.
  9461. *
  9462. * @param {Tech~SourceObject|Tech~SourceObject[]} src
  9463. * The src object to filter
  9464. *
  9465. * @return {Tech~SourceObject[]}
  9466. * An array of sourceobjects containing only valid sources
  9467. *
  9468. * @private
  9469. */
  9470. var filterSource = function filterSource(src) {
  9471. // traverse array
  9472. if (Array.isArray(src)) {
  9473. var newsrc = [];
  9474. src.forEach(function (srcobj) {
  9475. srcobj = filterSource(srcobj);
  9476. if (Array.isArray(srcobj)) {
  9477. newsrc = newsrc.concat(srcobj);
  9478. } else if (isObject$1(srcobj)) {
  9479. newsrc.push(srcobj);
  9480. }
  9481. });
  9482. src = newsrc;
  9483. } else if (typeof src === 'string' && src.trim()) {
  9484. // convert string into object
  9485. src = [fixSource({
  9486. src: src
  9487. })];
  9488. } else if (isObject$1(src) && typeof src.src === 'string' && src.src && src.src.trim()) {
  9489. // src is already valid
  9490. src = [fixSource(src)];
  9491. } else {
  9492. // invalid source, turn it into an empty array
  9493. src = [];
  9494. }
  9495. return src;
  9496. };
  9497. /**
  9498. * Checks src mimetype, adding it when possible
  9499. *
  9500. * @param {Tech~SourceObject} src
  9501. * The src object to check
  9502. * @return {Tech~SourceObject}
  9503. * src Object with known type
  9504. */
  9505. function fixSource(src) {
  9506. if (!src.type) {
  9507. var mimetype = getMimetype(src.src);
  9508. if (mimetype) {
  9509. src.type = mimetype;
  9510. }
  9511. }
  9512. return src;
  9513. }
  9514. /**
  9515. * The `MediaLoader` is the `Component` that decides which playback technology to load
  9516. * when a player is initialized.
  9517. *
  9518. * @extends Component
  9519. */
  9520. var MediaLoader = /*#__PURE__*/function (_Component) {
  9521. inheritsLoose(MediaLoader, _Component);
  9522. /**
  9523. * Create an instance of this class.
  9524. *
  9525. * @param {Player} player
  9526. * The `Player` that this class should attach to.
  9527. *
  9528. * @param {Object} [options]
  9529. * The key/value store of player options.
  9530. *
  9531. * @param {Component~ReadyCallback} [ready]
  9532. * The function that is run when this component is ready.
  9533. */
  9534. function MediaLoader(player, options, ready) {
  9535. var _this;
  9536. // MediaLoader has no element
  9537. var options_ = mergeOptions$3({
  9538. createEl: false
  9539. }, options);
  9540. _this = _Component.call(this, player, options_, ready) || this; // If there are no sources when the player is initialized,
  9541. // load the first supported playback technology.
  9542. if (!options.playerOptions.sources || options.playerOptions.sources.length === 0) {
  9543. for (var i = 0, j = options.playerOptions.techOrder; i < j.length; i++) {
  9544. var techName = toTitleCase$1(j[i]);
  9545. var tech = Tech.getTech(techName); // Support old behavior of techs being registered as components.
  9546. // Remove once that deprecated behavior is removed.
  9547. if (!techName) {
  9548. tech = Component$1.getComponent(techName);
  9549. } // Check if the browser supports this technology
  9550. if (tech && tech.isSupported()) {
  9551. player.loadTech_(techName);
  9552. break;
  9553. }
  9554. }
  9555. } else {
  9556. // Loop through playback technologies (e.g. HTML5) and check for support.
  9557. // Then load the best source.
  9558. // A few assumptions here:
  9559. // All playback technologies respect preload false.
  9560. player.src(options.playerOptions.sources);
  9561. }
  9562. return _this;
  9563. }
  9564. return MediaLoader;
  9565. }(Component$1);
  9566. Component$1.registerComponent('MediaLoader', MediaLoader);
  9567. /**
  9568. * Component which is clickable or keyboard actionable, but is not a
  9569. * native HTML button.
  9570. *
  9571. * @extends Component
  9572. */
  9573. var ClickableComponent = /*#__PURE__*/function (_Component) {
  9574. inheritsLoose(ClickableComponent, _Component);
  9575. /**
  9576. * Creates an instance of this class.
  9577. *
  9578. * @param {Player} player
  9579. * The `Player` that this class should be attached to.
  9580. *
  9581. * @param {Object} [options]
  9582. * The key/value store of component options.
  9583. *
  9584. * @param {function} [options.clickHandler]
  9585. * The function to call when the button is clicked / activated
  9586. *
  9587. * @param {string} [options.controlText]
  9588. * The text to set on the button
  9589. *
  9590. * @param {string} [options.className]
  9591. * A class or space separated list of classes to add the component
  9592. *
  9593. */
  9594. function ClickableComponent(player, options) {
  9595. var _this;
  9596. _this = _Component.call(this, player, options) || this;
  9597. if (_this.options_.controlText) {
  9598. _this.controlText(_this.options_.controlText);
  9599. }
  9600. _this.handleMouseOver_ = function (e) {
  9601. return _this.handleMouseOver(e);
  9602. };
  9603. _this.handleMouseOut_ = function (e) {
  9604. return _this.handleMouseOut(e);
  9605. };
  9606. _this.handleClick_ = function (e) {
  9607. return _this.handleClick(e);
  9608. };
  9609. _this.handleKeyDown_ = function (e) {
  9610. return _this.handleKeyDown(e);
  9611. };
  9612. _this.emitTapEvents();
  9613. _this.enable();
  9614. return _this;
  9615. }
  9616. /**
  9617. * Create the `ClickableComponent`s DOM element.
  9618. *
  9619. * @param {string} [tag=div]
  9620. * The element's node type.
  9621. *
  9622. * @param {Object} [props={}]
  9623. * An object of properties that should be set on the element.
  9624. *
  9625. * @param {Object} [attributes={}]
  9626. * An object of attributes that should be set on the element.
  9627. *
  9628. * @return {Element}
  9629. * The element that gets created.
  9630. */
  9631. var _proto = ClickableComponent.prototype;
  9632. _proto.createEl = function createEl$1(tag, props, attributes) {
  9633. if (tag === void 0) {
  9634. tag = 'div';
  9635. }
  9636. if (props === void 0) {
  9637. props = {};
  9638. }
  9639. if (attributes === void 0) {
  9640. attributes = {};
  9641. }
  9642. props = assign$1({
  9643. className: this.buildCSSClass(),
  9644. tabIndex: 0
  9645. }, props);
  9646. if (tag === 'button') {
  9647. log$1.error("Creating a ClickableComponent with an HTML element of " + tag + " is not supported; use a Button instead.");
  9648. } // Add ARIA attributes for clickable element which is not a native HTML button
  9649. attributes = assign$1({
  9650. role: 'button'
  9651. }, attributes);
  9652. this.tabIndex_ = props.tabIndex;
  9653. var el = createEl(tag, props, attributes);
  9654. el.appendChild(createEl('span', {
  9655. className: 'vjs-icon-placeholder'
  9656. }, {
  9657. 'aria-hidden': true
  9658. }));
  9659. this.createControlTextEl(el);
  9660. return el;
  9661. };
  9662. _proto.dispose = function dispose() {
  9663. // remove controlTextEl_ on dispose
  9664. this.controlTextEl_ = null;
  9665. _Component.prototype.dispose.call(this);
  9666. }
  9667. /**
  9668. * Create a control text element on this `ClickableComponent`
  9669. *
  9670. * @param {Element} [el]
  9671. * Parent element for the control text.
  9672. *
  9673. * @return {Element}
  9674. * The control text element that gets created.
  9675. */
  9676. ;
  9677. _proto.createControlTextEl = function createControlTextEl(el) {
  9678. this.controlTextEl_ = createEl('span', {
  9679. className: 'vjs-control-text'
  9680. }, {
  9681. // let the screen reader user know that the text of the element may change
  9682. 'aria-live': 'polite'
  9683. });
  9684. if (el) {
  9685. el.appendChild(this.controlTextEl_);
  9686. }
  9687. this.controlText(this.controlText_, el);
  9688. return this.controlTextEl_;
  9689. }
  9690. /**
  9691. * Get or set the localize text to use for the controls on the `ClickableComponent`.
  9692. *
  9693. * @param {string} [text]
  9694. * Control text for element.
  9695. *
  9696. * @param {Element} [el=this.el()]
  9697. * Element to set the title on.
  9698. *
  9699. * @return {string}
  9700. * - The control text when getting
  9701. */
  9702. ;
  9703. _proto.controlText = function controlText(text, el) {
  9704. if (el === void 0) {
  9705. el = this.el();
  9706. }
  9707. if (text === undefined) {
  9708. return this.controlText_ || 'Need Text';
  9709. }
  9710. var localizedText = this.localize(text);
  9711. this.controlText_ = text;
  9712. textContent(this.controlTextEl_, localizedText);
  9713. if (!this.nonIconControl && !this.player_.options_.noUITitleAttributes) {
  9714. // Set title attribute if only an icon is shown
  9715. el.setAttribute('title', localizedText);
  9716. }
  9717. }
  9718. /**
  9719. * Builds the default DOM `className`.
  9720. *
  9721. * @return {string}
  9722. * The DOM `className` for this object.
  9723. */
  9724. ;
  9725. _proto.buildCSSClass = function buildCSSClass() {
  9726. return "vjs-control vjs-button " + _Component.prototype.buildCSSClass.call(this);
  9727. }
  9728. /**
  9729. * Enable this `ClickableComponent`
  9730. */
  9731. ;
  9732. _proto.enable = function enable() {
  9733. if (!this.enabled_) {
  9734. this.enabled_ = true;
  9735. this.removeClass('vjs-disabled');
  9736. this.el_.setAttribute('aria-disabled', 'false');
  9737. if (typeof this.tabIndex_ !== 'undefined') {
  9738. this.el_.setAttribute('tabIndex', this.tabIndex_);
  9739. }
  9740. this.on(['tap', 'click'], this.handleClick_);
  9741. this.on('keydown', this.handleKeyDown_);
  9742. }
  9743. }
  9744. /**
  9745. * Disable this `ClickableComponent`
  9746. */
  9747. ;
  9748. _proto.disable = function disable() {
  9749. this.enabled_ = false;
  9750. this.addClass('vjs-disabled');
  9751. this.el_.setAttribute('aria-disabled', 'true');
  9752. if (typeof this.tabIndex_ !== 'undefined') {
  9753. this.el_.removeAttribute('tabIndex');
  9754. }
  9755. this.off('mouseover', this.handleMouseOver_);
  9756. this.off('mouseout', this.handleMouseOut_);
  9757. this.off(['tap', 'click'], this.handleClick_);
  9758. this.off('keydown', this.handleKeyDown_);
  9759. }
  9760. /**
  9761. * Handles language change in ClickableComponent for the player in components
  9762. *
  9763. *
  9764. */
  9765. ;
  9766. _proto.handleLanguagechange = function handleLanguagechange() {
  9767. this.controlText(this.controlText_);
  9768. }
  9769. /**
  9770. * Event handler that is called when a `ClickableComponent` receives a
  9771. * `click` or `tap` event.
  9772. *
  9773. * @param {EventTarget~Event} event
  9774. * The `tap` or `click` event that caused this function to be called.
  9775. *
  9776. * @listens tap
  9777. * @listens click
  9778. * @abstract
  9779. */
  9780. ;
  9781. _proto.handleClick = function handleClick(event) {
  9782. if (this.options_.clickHandler) {
  9783. this.options_.clickHandler.call(this, arguments);
  9784. }
  9785. }
  9786. /**
  9787. * Event handler that is called when a `ClickableComponent` receives a
  9788. * `keydown` event.
  9789. *
  9790. * By default, if the key is Space or Enter, it will trigger a `click` event.
  9791. *
  9792. * @param {EventTarget~Event} event
  9793. * The `keydown` event that caused this function to be called.
  9794. *
  9795. * @listens keydown
  9796. */
  9797. ;
  9798. _proto.handleKeyDown = function handleKeyDown(event) {
  9799. // Support Space or Enter key operation to fire a click event. Also,
  9800. // prevent the event from propagating through the DOM and triggering
  9801. // Player hotkeys.
  9802. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) {
  9803. event.preventDefault();
  9804. event.stopPropagation();
  9805. this.trigger('click');
  9806. } else {
  9807. // Pass keypress handling up for unsupported keys
  9808. _Component.prototype.handleKeyDown.call(this, event);
  9809. }
  9810. };
  9811. return ClickableComponent;
  9812. }(Component$1);
  9813. Component$1.registerComponent('ClickableComponent', ClickableComponent);
  9814. /**
  9815. * A `ClickableComponent` that handles showing the poster image for the player.
  9816. *
  9817. * @extends ClickableComponent
  9818. */
  9819. var PosterImage = /*#__PURE__*/function (_ClickableComponent) {
  9820. inheritsLoose(PosterImage, _ClickableComponent);
  9821. /**
  9822. * Create an instance of this class.
  9823. *
  9824. * @param {Player} player
  9825. * The `Player` that this class should attach to.
  9826. *
  9827. * @param {Object} [options]
  9828. * The key/value store of player options.
  9829. */
  9830. function PosterImage(player, options) {
  9831. var _this;
  9832. _this = _ClickableComponent.call(this, player, options) || this;
  9833. _this.update();
  9834. _this.update_ = function (e) {
  9835. return _this.update(e);
  9836. };
  9837. player.on('posterchange', _this.update_);
  9838. return _this;
  9839. }
  9840. /**
  9841. * Clean up and dispose of the `PosterImage`.
  9842. */
  9843. var _proto = PosterImage.prototype;
  9844. _proto.dispose = function dispose() {
  9845. this.player().off('posterchange', this.update_);
  9846. _ClickableComponent.prototype.dispose.call(this);
  9847. }
  9848. /**
  9849. * Create the `PosterImage`s DOM element.
  9850. *
  9851. * @return {Element}
  9852. * The element that gets created.
  9853. */
  9854. ;
  9855. _proto.createEl = function createEl$1() {
  9856. var el = createEl('div', {
  9857. className: 'vjs-poster',
  9858. // Don't want poster to be tabbable.
  9859. tabIndex: -1
  9860. });
  9861. return el;
  9862. }
  9863. /**
  9864. * An {@link EventTarget~EventListener} for {@link Player#posterchange} events.
  9865. *
  9866. * @listens Player#posterchange
  9867. *
  9868. * @param {EventTarget~Event} [event]
  9869. * The `Player#posterchange` event that triggered this function.
  9870. */
  9871. ;
  9872. _proto.update = function update(event) {
  9873. var url = this.player().poster();
  9874. this.setSrc(url); // If there's no poster source we should display:none on this component
  9875. // so it's not still clickable or right-clickable
  9876. if (url) {
  9877. this.show();
  9878. } else {
  9879. this.hide();
  9880. }
  9881. }
  9882. /**
  9883. * Set the source of the `PosterImage` depending on the display method.
  9884. *
  9885. * @param {string} url
  9886. * The URL to the source for the `PosterImage`.
  9887. */
  9888. ;
  9889. _proto.setSrc = function setSrc(url) {
  9890. var backgroundImage = ''; // Any falsy value should stay as an empty string, otherwise
  9891. // this will throw an extra error
  9892. if (url) {
  9893. backgroundImage = "url(\"" + url + "\")";
  9894. }
  9895. this.el_.style.backgroundImage = backgroundImage;
  9896. }
  9897. /**
  9898. * An {@link EventTarget~EventListener} for clicks on the `PosterImage`. See
  9899. * {@link ClickableComponent#handleClick} for instances where this will be triggered.
  9900. *
  9901. * @listens tap
  9902. * @listens click
  9903. * @listens keydown
  9904. *
  9905. * @param {EventTarget~Event} event
  9906. + The `click`, `tap` or `keydown` event that caused this function to be called.
  9907. */
  9908. ;
  9909. _proto.handleClick = function handleClick(event) {
  9910. // We don't want a click to trigger playback when controls are disabled
  9911. if (!this.player_.controls()) {
  9912. return;
  9913. }
  9914. var sourceIsEncrypted = this.player_.usingPlugin('eme') && this.player_.eme.sessions && this.player_.eme.sessions.length > 0;
  9915. if (this.player_.tech(true) && // We've observed a bug in IE and Edge when playing back DRM content where
  9916. // calling .focus() on the video element causes the video to go black,
  9917. // so we avoid it in that specific case
  9918. !((IE_VERSION || IS_EDGE) && sourceIsEncrypted)) {
  9919. this.player_.tech(true).focus();
  9920. }
  9921. if (this.player_.paused()) {
  9922. silencePromise(this.player_.play());
  9923. } else {
  9924. this.player_.pause();
  9925. }
  9926. };
  9927. return PosterImage;
  9928. }(ClickableComponent);
  9929. Component$1.registerComponent('PosterImage', PosterImage);
  9930. var darkGray = '#222';
  9931. var lightGray = '#ccc';
  9932. var fontMap = {
  9933. monospace: 'monospace',
  9934. sansSerif: 'sans-serif',
  9935. serif: 'serif',
  9936. monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace',
  9937. monospaceSerif: '"Courier New", monospace',
  9938. proportionalSansSerif: 'sans-serif',
  9939. proportionalSerif: 'serif',
  9940. casual: '"Comic Sans MS", Impact, fantasy',
  9941. script: '"Monotype Corsiva", cursive',
  9942. smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif'
  9943. };
  9944. /**
  9945. * Construct an rgba color from a given hex color code.
  9946. *
  9947. * @param {number} color
  9948. * Hex number for color, like #f0e or #f604e2.
  9949. *
  9950. * @param {number} opacity
  9951. * Value for opacity, 0.0 - 1.0.
  9952. *
  9953. * @return {string}
  9954. * The rgba color that was created, like 'rgba(255, 0, 0, 0.3)'.
  9955. */
  9956. function constructColor(color, opacity) {
  9957. var hex;
  9958. if (color.length === 4) {
  9959. // color looks like "#f0e"
  9960. hex = color[1] + color[1] + color[2] + color[2] + color[3] + color[3];
  9961. } else if (color.length === 7) {
  9962. // color looks like "#f604e2"
  9963. hex = color.slice(1);
  9964. } else {
  9965. throw new Error('Invalid color code provided, ' + color + '; must be formatted as e.g. #f0e or #f604e2.');
  9966. }
  9967. return 'rgba(' + parseInt(hex.slice(0, 2), 16) + ',' + parseInt(hex.slice(2, 4), 16) + ',' + parseInt(hex.slice(4, 6), 16) + ',' + opacity + ')';
  9968. }
  9969. /**
  9970. * Try to update the style of a DOM element. Some style changes will throw an error,
  9971. * particularly in IE8. Those should be noops.
  9972. *
  9973. * @param {Element} el
  9974. * The DOM element to be styled.
  9975. *
  9976. * @param {string} style
  9977. * The CSS property on the element that should be styled.
  9978. *
  9979. * @param {string} rule
  9980. * The style rule that should be applied to the property.
  9981. *
  9982. * @private
  9983. */
  9984. function tryUpdateStyle(el, style, rule) {
  9985. try {
  9986. el.style[style] = rule;
  9987. } catch (e) {
  9988. // Satisfies linter.
  9989. return;
  9990. }
  9991. }
  9992. /**
  9993. * The component for displaying text track cues.
  9994. *
  9995. * @extends Component
  9996. */
  9997. var TextTrackDisplay = /*#__PURE__*/function (_Component) {
  9998. inheritsLoose(TextTrackDisplay, _Component);
  9999. /**
  10000. * Creates an instance of this class.
  10001. *
  10002. * @param {Player} player
  10003. * The `Player` that this class should be attached to.
  10004. *
  10005. * @param {Object} [options]
  10006. * The key/value store of player options.
  10007. *
  10008. * @param {Component~ReadyCallback} [ready]
  10009. * The function to call when `TextTrackDisplay` is ready.
  10010. */
  10011. function TextTrackDisplay(player, options, ready) {
  10012. var _this;
  10013. _this = _Component.call(this, player, options, ready) || this;
  10014. var updateDisplayHandler = function updateDisplayHandler(e) {
  10015. return _this.updateDisplay(e);
  10016. };
  10017. player.on('loadstart', function (e) {
  10018. return _this.toggleDisplay(e);
  10019. });
  10020. player.on('texttrackchange', updateDisplayHandler);
  10021. player.on('loadedmetadata', function (e) {
  10022. return _this.preselectTrack(e);
  10023. }); // This used to be called during player init, but was causing an error
  10024. // if a track should show by default and the display hadn't loaded yet.
  10025. // Should probably be moved to an external track loader when we support
  10026. // tracks that don't need a display.
  10027. player.ready(bind(assertThisInitialized(_this), function () {
  10028. if (player.tech_ && player.tech_.featuresNativeTextTracks) {
  10029. this.hide();
  10030. return;
  10031. }
  10032. player.on('fullscreenchange', updateDisplayHandler);
  10033. player.on('playerresize', updateDisplayHandler);
  10034. window.addEventListener('orientationchange', updateDisplayHandler);
  10035. player.on('dispose', function () {
  10036. return window.removeEventListener('orientationchange', updateDisplayHandler);
  10037. });
  10038. var tracks = this.options_.playerOptions.tracks || [];
  10039. for (var i = 0; i < tracks.length; i++) {
  10040. this.player_.addRemoteTextTrack(tracks[i], true);
  10041. }
  10042. this.preselectTrack();
  10043. }));
  10044. return _this;
  10045. }
  10046. /**
  10047. * Preselect a track following this precedence:
  10048. * - matches the previously selected {@link TextTrack}'s language and kind
  10049. * - matches the previously selected {@link TextTrack}'s language only
  10050. * - is the first default captions track
  10051. * - is the first default descriptions track
  10052. *
  10053. * @listens Player#loadstart
  10054. */
  10055. var _proto = TextTrackDisplay.prototype;
  10056. _proto.preselectTrack = function preselectTrack() {
  10057. var modes = {
  10058. captions: 1,
  10059. subtitles: 1
  10060. };
  10061. var trackList = this.player_.textTracks();
  10062. var userPref = this.player_.cache_.selectedLanguage;
  10063. var firstDesc;
  10064. var firstCaptions;
  10065. var preferredTrack;
  10066. for (var i = 0; i < trackList.length; i++) {
  10067. var track = trackList[i];
  10068. if (userPref && userPref.enabled && userPref.language && userPref.language === track.language && track.kind in modes) {
  10069. // Always choose the track that matches both language and kind
  10070. if (track.kind === userPref.kind) {
  10071. preferredTrack = track; // or choose the first track that matches language
  10072. } else if (!preferredTrack) {
  10073. preferredTrack = track;
  10074. } // clear everything if offTextTrackMenuItem was clicked
  10075. } else if (userPref && !userPref.enabled) {
  10076. preferredTrack = null;
  10077. firstDesc = null;
  10078. firstCaptions = null;
  10079. } else if (track["default"]) {
  10080. if (track.kind === 'descriptions' && !firstDesc) {
  10081. firstDesc = track;
  10082. } else if (track.kind in modes && !firstCaptions) {
  10083. firstCaptions = track;
  10084. }
  10085. }
  10086. } // The preferredTrack matches the user preference and takes
  10087. // precedence over all the other tracks.
  10088. // So, display the preferredTrack before the first default track
  10089. // and the subtitles/captions track before the descriptions track
  10090. if (preferredTrack) {
  10091. preferredTrack.mode = 'showing';
  10092. } else if (firstCaptions) {
  10093. firstCaptions.mode = 'showing';
  10094. } else if (firstDesc) {
  10095. firstDesc.mode = 'showing';
  10096. }
  10097. }
  10098. /**
  10099. * Turn display of {@link TextTrack}'s from the current state into the other state.
  10100. * There are only two states:
  10101. * - 'shown'
  10102. * - 'hidden'
  10103. *
  10104. * @listens Player#loadstart
  10105. */
  10106. ;
  10107. _proto.toggleDisplay = function toggleDisplay() {
  10108. if (this.player_.tech_ && this.player_.tech_.featuresNativeTextTracks) {
  10109. this.hide();
  10110. } else {
  10111. this.show();
  10112. }
  10113. }
  10114. /**
  10115. * Create the {@link Component}'s DOM element.
  10116. *
  10117. * @return {Element}
  10118. * The element that was created.
  10119. */
  10120. ;
  10121. _proto.createEl = function createEl() {
  10122. return _Component.prototype.createEl.call(this, 'div', {
  10123. className: 'vjs-text-track-display'
  10124. }, {
  10125. 'translate': 'yes',
  10126. 'aria-live': 'off',
  10127. 'aria-atomic': 'true'
  10128. });
  10129. }
  10130. /**
  10131. * Clear all displayed {@link TextTrack}s.
  10132. */
  10133. ;
  10134. _proto.clearDisplay = function clearDisplay() {
  10135. if (typeof window.WebVTT === 'function') {
  10136. window.WebVTT.processCues(window, [], this.el_);
  10137. }
  10138. }
  10139. /**
  10140. * Update the displayed TextTrack when a either a {@link Player#texttrackchange} or
  10141. * a {@link Player#fullscreenchange} is fired.
  10142. *
  10143. * @listens Player#texttrackchange
  10144. * @listens Player#fullscreenchange
  10145. */
  10146. ;
  10147. _proto.updateDisplay = function updateDisplay() {
  10148. var tracks = this.player_.textTracks();
  10149. var allowMultipleShowingTracks = this.options_.allowMultipleShowingTracks;
  10150. this.clearDisplay();
  10151. if (allowMultipleShowingTracks) {
  10152. var showingTracks = [];
  10153. for (var _i = 0; _i < tracks.length; ++_i) {
  10154. var track = tracks[_i];
  10155. if (track.mode !== 'showing') {
  10156. continue;
  10157. }
  10158. showingTracks.push(track);
  10159. }
  10160. this.updateForTrack(showingTracks);
  10161. return;
  10162. } // Track display prioritization model: if multiple tracks are 'showing',
  10163. // display the first 'subtitles' or 'captions' track which is 'showing',
  10164. // otherwise display the first 'descriptions' track which is 'showing'
  10165. var descriptionsTrack = null;
  10166. var captionsSubtitlesTrack = null;
  10167. var i = tracks.length;
  10168. while (i--) {
  10169. var _track = tracks[i];
  10170. if (_track.mode === 'showing') {
  10171. if (_track.kind === 'descriptions') {
  10172. descriptionsTrack = _track;
  10173. } else {
  10174. captionsSubtitlesTrack = _track;
  10175. }
  10176. }
  10177. }
  10178. if (captionsSubtitlesTrack) {
  10179. if (this.getAttribute('aria-live') !== 'off') {
  10180. this.setAttribute('aria-live', 'off');
  10181. }
  10182. this.updateForTrack(captionsSubtitlesTrack);
  10183. } else if (descriptionsTrack) {
  10184. if (this.getAttribute('aria-live') !== 'assertive') {
  10185. this.setAttribute('aria-live', 'assertive');
  10186. }
  10187. this.updateForTrack(descriptionsTrack);
  10188. }
  10189. }
  10190. /**
  10191. * Style {@Link TextTrack} activeCues according to {@Link TextTrackSettings}.
  10192. *
  10193. * @param {TextTrack} track
  10194. * Text track object containing active cues to style.
  10195. */
  10196. ;
  10197. _proto.updateDisplayState = function updateDisplayState(track) {
  10198. var overrides = this.player_.textTrackSettings.getValues();
  10199. var cues = track.activeCues;
  10200. var i = cues.length;
  10201. while (i--) {
  10202. var cue = cues[i];
  10203. if (!cue) {
  10204. continue;
  10205. }
  10206. var cueDiv = cue.displayState;
  10207. if (overrides.color) {
  10208. cueDiv.firstChild.style.color = overrides.color;
  10209. }
  10210. if (overrides.textOpacity) {
  10211. tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity));
  10212. }
  10213. if (overrides.backgroundColor) {
  10214. cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor;
  10215. }
  10216. if (overrides.backgroundOpacity) {
  10217. tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity));
  10218. }
  10219. if (overrides.windowColor) {
  10220. if (overrides.windowOpacity) {
  10221. tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity));
  10222. } else {
  10223. cueDiv.style.backgroundColor = overrides.windowColor;
  10224. }
  10225. }
  10226. if (overrides.edgeStyle) {
  10227. if (overrides.edgeStyle === 'dropshadow') {
  10228. cueDiv.firstChild.style.textShadow = "2px 2px 3px " + darkGray + ", 2px 2px 4px " + darkGray + ", 2px 2px 5px " + darkGray;
  10229. } else if (overrides.edgeStyle === 'raised') {
  10230. cueDiv.firstChild.style.textShadow = "1px 1px " + darkGray + ", 2px 2px " + darkGray + ", 3px 3px " + darkGray;
  10231. } else if (overrides.edgeStyle === 'depressed') {
  10232. cueDiv.firstChild.style.textShadow = "1px 1px " + lightGray + ", 0 1px " + lightGray + ", -1px -1px " + darkGray + ", 0 -1px " + darkGray;
  10233. } else if (overrides.edgeStyle === 'uniform') {
  10234. cueDiv.firstChild.style.textShadow = "0 0 4px " + darkGray + ", 0 0 4px " + darkGray + ", 0 0 4px " + darkGray + ", 0 0 4px " + darkGray;
  10235. }
  10236. }
  10237. if (overrides.fontPercent && overrides.fontPercent !== 1) {
  10238. var fontSize = window.parseFloat(cueDiv.style.fontSize);
  10239. cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px';
  10240. cueDiv.style.height = 'auto';
  10241. cueDiv.style.top = 'auto';
  10242. }
  10243. if (overrides.fontFamily && overrides.fontFamily !== 'default') {
  10244. if (overrides.fontFamily === 'small-caps') {
  10245. cueDiv.firstChild.style.fontVariant = 'small-caps';
  10246. } else {
  10247. cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily];
  10248. }
  10249. }
  10250. }
  10251. }
  10252. /**
  10253. * Add an {@link TextTrack} to to the {@link Tech}s {@link TextTrackList}.
  10254. *
  10255. * @param {TextTrack|TextTrack[]} tracks
  10256. * Text track object or text track array to be added to the list.
  10257. */
  10258. ;
  10259. _proto.updateForTrack = function updateForTrack(tracks) {
  10260. if (!Array.isArray(tracks)) {
  10261. tracks = [tracks];
  10262. }
  10263. if (typeof window.WebVTT !== 'function' || tracks.every(function (track) {
  10264. return !track.activeCues;
  10265. })) {
  10266. return;
  10267. }
  10268. var cues = []; // push all active track cues
  10269. for (var i = 0; i < tracks.length; ++i) {
  10270. var track = tracks[i];
  10271. for (var j = 0; j < track.activeCues.length; ++j) {
  10272. cues.push(track.activeCues[j]);
  10273. }
  10274. } // removes all cues before it processes new ones
  10275. window.WebVTT.processCues(window, cues, this.el_); // add unique class to each language text track & add settings styling if necessary
  10276. for (var _i2 = 0; _i2 < tracks.length; ++_i2) {
  10277. var _track2 = tracks[_i2];
  10278. for (var _j = 0; _j < _track2.activeCues.length; ++_j) {
  10279. var cueEl = _track2.activeCues[_j].displayState;
  10280. addClass(cueEl, 'vjs-text-track-cue');
  10281. addClass(cueEl, 'vjs-text-track-cue-' + (_track2.language ? _track2.language : _i2));
  10282. if (_track2.language) {
  10283. setAttribute(cueEl, 'lang', _track2.language);
  10284. }
  10285. }
  10286. if (this.player_.textTrackSettings) {
  10287. this.updateDisplayState(_track2);
  10288. }
  10289. }
  10290. };
  10291. return TextTrackDisplay;
  10292. }(Component$1);
  10293. Component$1.registerComponent('TextTrackDisplay', TextTrackDisplay);
  10294. /**
  10295. * A loading spinner for use during waiting/loading events.
  10296. *
  10297. * @extends Component
  10298. */
  10299. var LoadingSpinner = /*#__PURE__*/function (_Component) {
  10300. inheritsLoose(LoadingSpinner, _Component);
  10301. function LoadingSpinner() {
  10302. return _Component.apply(this, arguments) || this;
  10303. }
  10304. var _proto = LoadingSpinner.prototype;
  10305. /**
  10306. * Create the `LoadingSpinner`s DOM element.
  10307. *
  10308. * @return {Element}
  10309. * The dom element that gets created.
  10310. */
  10311. _proto.createEl = function createEl$1() {
  10312. var isAudio = this.player_.isAudio();
  10313. var playerType = this.localize(isAudio ? 'Audio Player' : 'Video Player');
  10314. var controlText = createEl('span', {
  10315. className: 'vjs-control-text',
  10316. textContent: this.localize('{1} is loading.', [playerType])
  10317. });
  10318. var el = _Component.prototype.createEl.call(this, 'div', {
  10319. className: 'vjs-loading-spinner',
  10320. dir: 'ltr'
  10321. });
  10322. el.appendChild(controlText);
  10323. return el;
  10324. };
  10325. return LoadingSpinner;
  10326. }(Component$1);
  10327. Component$1.registerComponent('LoadingSpinner', LoadingSpinner);
  10328. /**
  10329. * Base class for all buttons.
  10330. *
  10331. * @extends ClickableComponent
  10332. */
  10333. var Button = /*#__PURE__*/function (_ClickableComponent) {
  10334. inheritsLoose(Button, _ClickableComponent);
  10335. function Button() {
  10336. return _ClickableComponent.apply(this, arguments) || this;
  10337. }
  10338. var _proto = Button.prototype;
  10339. /**
  10340. * Create the `Button`s DOM element.
  10341. *
  10342. * @param {string} [tag="button"]
  10343. * The element's node type. This argument is IGNORED: no matter what
  10344. * is passed, it will always create a `button` element.
  10345. *
  10346. * @param {Object} [props={}]
  10347. * An object of properties that should be set on the element.
  10348. *
  10349. * @param {Object} [attributes={}]
  10350. * An object of attributes that should be set on the element.
  10351. *
  10352. * @return {Element}
  10353. * The element that gets created.
  10354. */
  10355. _proto.createEl = function createEl$1(tag, props, attributes) {
  10356. if (props === void 0) {
  10357. props = {};
  10358. }
  10359. if (attributes === void 0) {
  10360. attributes = {};
  10361. }
  10362. tag = 'button';
  10363. props = assign$1({
  10364. className: this.buildCSSClass()
  10365. }, props); // Add attributes for button element
  10366. attributes = assign$1({
  10367. // Necessary since the default button type is "submit"
  10368. type: 'button'
  10369. }, attributes);
  10370. var el = createEl(tag, props, attributes);
  10371. el.appendChild(createEl('span', {
  10372. className: 'vjs-icon-placeholder'
  10373. }, {
  10374. 'aria-hidden': true
  10375. }));
  10376. this.createControlTextEl(el);
  10377. return el;
  10378. }
  10379. /**
  10380. * Add a child `Component` inside of this `Button`.
  10381. *
  10382. * @param {string|Component} child
  10383. * The name or instance of a child to add.
  10384. *
  10385. * @param {Object} [options={}]
  10386. * The key/value store of options that will get passed to children of
  10387. * the child.
  10388. *
  10389. * @return {Component}
  10390. * The `Component` that gets added as a child. When using a string the
  10391. * `Component` will get created by this process.
  10392. *
  10393. * @deprecated since version 5
  10394. */
  10395. ;
  10396. _proto.addChild = function addChild(child, options) {
  10397. if (options === void 0) {
  10398. options = {};
  10399. }
  10400. var className = this.constructor.name;
  10401. 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
  10402. return Component$1.prototype.addChild.call(this, child, options);
  10403. }
  10404. /**
  10405. * Enable the `Button` element so that it can be activated or clicked. Use this with
  10406. * {@link Button#disable}.
  10407. */
  10408. ;
  10409. _proto.enable = function enable() {
  10410. _ClickableComponent.prototype.enable.call(this);
  10411. this.el_.removeAttribute('disabled');
  10412. }
  10413. /**
  10414. * Disable the `Button` element so that it cannot be activated or clicked. Use this with
  10415. * {@link Button#enable}.
  10416. */
  10417. ;
  10418. _proto.disable = function disable() {
  10419. _ClickableComponent.prototype.disable.call(this);
  10420. this.el_.setAttribute('disabled', 'disabled');
  10421. }
  10422. /**
  10423. * This gets called when a `Button` has focus and `keydown` is triggered via a key
  10424. * press.
  10425. *
  10426. * @param {EventTarget~Event} event
  10427. * The event that caused this function to get called.
  10428. *
  10429. * @listens keydown
  10430. */
  10431. ;
  10432. _proto.handleKeyDown = function handleKeyDown(event) {
  10433. // Ignore Space or Enter key operation, which is handled by the browser for
  10434. // a button - though not for its super class, ClickableComponent. Also,
  10435. // prevent the event from propagating through the DOM and triggering Player
  10436. // hotkeys. We do not preventDefault here because we _want_ the browser to
  10437. // handle it.
  10438. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) {
  10439. event.stopPropagation();
  10440. return;
  10441. } // Pass keypress handling up for unsupported keys
  10442. _ClickableComponent.prototype.handleKeyDown.call(this, event);
  10443. };
  10444. return Button;
  10445. }(ClickableComponent);
  10446. Component$1.registerComponent('Button', Button);
  10447. /**
  10448. * The initial play button that shows before the video has played. The hiding of the
  10449. * `BigPlayButton` get done via CSS and `Player` states.
  10450. *
  10451. * @extends Button
  10452. */
  10453. var BigPlayButton = /*#__PURE__*/function (_Button) {
  10454. inheritsLoose(BigPlayButton, _Button);
  10455. function BigPlayButton(player, options) {
  10456. var _this;
  10457. _this = _Button.call(this, player, options) || this;
  10458. _this.mouseused_ = false;
  10459. _this.on('mousedown', function (e) {
  10460. return _this.handleMouseDown(e);
  10461. });
  10462. return _this;
  10463. }
  10464. /**
  10465. * Builds the default DOM `className`.
  10466. *
  10467. * @return {string}
  10468. * The DOM `className` for this object. Always returns 'vjs-big-play-button'.
  10469. */
  10470. var _proto = BigPlayButton.prototype;
  10471. _proto.buildCSSClass = function buildCSSClass() {
  10472. return 'vjs-big-play-button';
  10473. }
  10474. /**
  10475. * This gets called when a `BigPlayButton` "clicked". See {@link ClickableComponent}
  10476. * for more detailed information on what a click can be.
  10477. *
  10478. * @param {EventTarget~Event} event
  10479. * The `keydown`, `tap`, or `click` event that caused this function to be
  10480. * called.
  10481. *
  10482. * @listens tap
  10483. * @listens click
  10484. */
  10485. ;
  10486. _proto.handleClick = function handleClick(event) {
  10487. var playPromise = this.player_.play(); // exit early if clicked via the mouse
  10488. if (this.mouseused_ && event.clientX && event.clientY) {
  10489. var sourceIsEncrypted = this.player_.usingPlugin('eme') && this.player_.eme.sessions && this.player_.eme.sessions.length > 0;
  10490. silencePromise(playPromise);
  10491. if (this.player_.tech(true) && // We've observed a bug in IE and Edge when playing back DRM content where
  10492. // calling .focus() on the video element causes the video to go black,
  10493. // so we avoid it in that specific case
  10494. !((IE_VERSION || IS_EDGE) && sourceIsEncrypted)) {
  10495. this.player_.tech(true).focus();
  10496. }
  10497. return;
  10498. }
  10499. var cb = this.player_.getChild('controlBar');
  10500. var playToggle = cb && cb.getChild('playToggle');
  10501. if (!playToggle) {
  10502. this.player_.tech(true).focus();
  10503. return;
  10504. }
  10505. var playFocus = function playFocus() {
  10506. return playToggle.focus();
  10507. };
  10508. if (isPromise(playPromise)) {
  10509. playPromise.then(playFocus, function () {});
  10510. } else {
  10511. this.setTimeout(playFocus, 1);
  10512. }
  10513. };
  10514. _proto.handleKeyDown = function handleKeyDown(event) {
  10515. this.mouseused_ = false;
  10516. _Button.prototype.handleKeyDown.call(this, event);
  10517. };
  10518. _proto.handleMouseDown = function handleMouseDown(event) {
  10519. this.mouseused_ = true;
  10520. };
  10521. return BigPlayButton;
  10522. }(Button);
  10523. /**
  10524. * The text that should display over the `BigPlayButton`s controls. Added to for localization.
  10525. *
  10526. * @type {string}
  10527. * @private
  10528. */
  10529. BigPlayButton.prototype.controlText_ = 'Play Video';
  10530. Component$1.registerComponent('BigPlayButton', BigPlayButton);
  10531. /**
  10532. * The `CloseButton` is a `{@link Button}` that fires a `close` event when
  10533. * it gets clicked.
  10534. *
  10535. * @extends Button
  10536. */
  10537. var CloseButton = /*#__PURE__*/function (_Button) {
  10538. inheritsLoose(CloseButton, _Button);
  10539. /**
  10540. * Creates an instance of the this class.
  10541. *
  10542. * @param {Player} player
  10543. * The `Player` that this class should be attached to.
  10544. *
  10545. * @param {Object} [options]
  10546. * The key/value store of player options.
  10547. */
  10548. function CloseButton(player, options) {
  10549. var _this;
  10550. _this = _Button.call(this, player, options) || this;
  10551. _this.controlText(options && options.controlText || _this.localize('Close'));
  10552. return _this;
  10553. }
  10554. /**
  10555. * Builds the default DOM `className`.
  10556. *
  10557. * @return {string}
  10558. * The DOM `className` for this object.
  10559. */
  10560. var _proto = CloseButton.prototype;
  10561. _proto.buildCSSClass = function buildCSSClass() {
  10562. return "vjs-close-button " + _Button.prototype.buildCSSClass.call(this);
  10563. }
  10564. /**
  10565. * This gets called when a `CloseButton` gets clicked. See
  10566. * {@link ClickableComponent#handleClick} for more information on when
  10567. * this will be triggered
  10568. *
  10569. * @param {EventTarget~Event} event
  10570. * The `keydown`, `tap`, or `click` event that caused this function to be
  10571. * called.
  10572. *
  10573. * @listens tap
  10574. * @listens click
  10575. * @fires CloseButton#close
  10576. */
  10577. ;
  10578. _proto.handleClick = function handleClick(event) {
  10579. /**
  10580. * Triggered when the a `CloseButton` is clicked.
  10581. *
  10582. * @event CloseButton#close
  10583. * @type {EventTarget~Event}
  10584. *
  10585. * @property {boolean} [bubbles=false]
  10586. * set to false so that the close event does not
  10587. * bubble up to parents if there is no listener
  10588. */
  10589. this.trigger({
  10590. type: 'close',
  10591. bubbles: false
  10592. });
  10593. }
  10594. /**
  10595. * Event handler that is called when a `CloseButton` receives a
  10596. * `keydown` event.
  10597. *
  10598. * By default, if the key is Esc, it will trigger a `click` event.
  10599. *
  10600. * @param {EventTarget~Event} event
  10601. * The `keydown` event that caused this function to be called.
  10602. *
  10603. * @listens keydown
  10604. */
  10605. ;
  10606. _proto.handleKeyDown = function handleKeyDown(event) {
  10607. // Esc button will trigger `click` event
  10608. if (keycode.isEventKey(event, 'Esc')) {
  10609. event.preventDefault();
  10610. event.stopPropagation();
  10611. this.trigger('click');
  10612. } else {
  10613. // Pass keypress handling up for unsupported keys
  10614. _Button.prototype.handleKeyDown.call(this, event);
  10615. }
  10616. };
  10617. return CloseButton;
  10618. }(Button);
  10619. Component$1.registerComponent('CloseButton', CloseButton);
  10620. /**
  10621. * Button to toggle between play and pause.
  10622. *
  10623. * @extends Button
  10624. */
  10625. var PlayToggle = /*#__PURE__*/function (_Button) {
  10626. inheritsLoose(PlayToggle, _Button);
  10627. /**
  10628. * Creates an instance of this class.
  10629. *
  10630. * @param {Player} player
  10631. * The `Player` that this class should be attached to.
  10632. *
  10633. * @param {Object} [options={}]
  10634. * The key/value store of player options.
  10635. */
  10636. function PlayToggle(player, options) {
  10637. var _this;
  10638. if (options === void 0) {
  10639. options = {};
  10640. }
  10641. _this = _Button.call(this, player, options) || this; // show or hide replay icon
  10642. options.replay = options.replay === undefined || options.replay;
  10643. _this.on(player, 'play', function (e) {
  10644. return _this.handlePlay(e);
  10645. });
  10646. _this.on(player, 'pause', function (e) {
  10647. return _this.handlePause(e);
  10648. });
  10649. if (options.replay) {
  10650. _this.on(player, 'ended', function (e) {
  10651. return _this.handleEnded(e);
  10652. });
  10653. }
  10654. return _this;
  10655. }
  10656. /**
  10657. * Builds the default DOM `className`.
  10658. *
  10659. * @return {string}
  10660. * The DOM `className` for this object.
  10661. */
  10662. var _proto = PlayToggle.prototype;
  10663. _proto.buildCSSClass = function buildCSSClass() {
  10664. return "vjs-play-control " + _Button.prototype.buildCSSClass.call(this);
  10665. }
  10666. /**
  10667. * This gets called when an `PlayToggle` is "clicked". See
  10668. * {@link ClickableComponent} for more detailed information on what a click can be.
  10669. *
  10670. * @param {EventTarget~Event} [event]
  10671. * The `keydown`, `tap`, or `click` event that caused this function to be
  10672. * called.
  10673. *
  10674. * @listens tap
  10675. * @listens click
  10676. */
  10677. ;
  10678. _proto.handleClick = function handleClick(event) {
  10679. if (this.player_.paused()) {
  10680. silencePromise(this.player_.play());
  10681. } else {
  10682. this.player_.pause();
  10683. }
  10684. }
  10685. /**
  10686. * This gets called once after the video has ended and the user seeks so that
  10687. * we can change the replay button back to a play button.
  10688. *
  10689. * @param {EventTarget~Event} [event]
  10690. * The event that caused this function to run.
  10691. *
  10692. * @listens Player#seeked
  10693. */
  10694. ;
  10695. _proto.handleSeeked = function handleSeeked(event) {
  10696. this.removeClass('vjs-ended');
  10697. if (this.player_.paused()) {
  10698. this.handlePause(event);
  10699. } else {
  10700. this.handlePlay(event);
  10701. }
  10702. }
  10703. /**
  10704. * Add the vjs-playing class to the element so it can change appearance.
  10705. *
  10706. * @param {EventTarget~Event} [event]
  10707. * The event that caused this function to run.
  10708. *
  10709. * @listens Player#play
  10710. */
  10711. ;
  10712. _proto.handlePlay = function handlePlay(event) {
  10713. this.removeClass('vjs-ended');
  10714. this.removeClass('vjs-paused');
  10715. this.addClass('vjs-playing'); // change the button text to "Pause"
  10716. this.controlText('Pause');
  10717. }
  10718. /**
  10719. * Add the vjs-paused class to the element so it can change appearance.
  10720. *
  10721. * @param {EventTarget~Event} [event]
  10722. * The event that caused this function to run.
  10723. *
  10724. * @listens Player#pause
  10725. */
  10726. ;
  10727. _proto.handlePause = function handlePause(event) {
  10728. this.removeClass('vjs-playing');
  10729. this.addClass('vjs-paused'); // change the button text to "Play"
  10730. this.controlText('Play');
  10731. }
  10732. /**
  10733. * Add the vjs-ended class to the element so it can change appearance
  10734. *
  10735. * @param {EventTarget~Event} [event]
  10736. * The event that caused this function to run.
  10737. *
  10738. * @listens Player#ended
  10739. */
  10740. ;
  10741. _proto.handleEnded = function handleEnded(event) {
  10742. var _this2 = this;
  10743. this.removeClass('vjs-playing');
  10744. this.addClass('vjs-ended'); // change the button text to "Replay"
  10745. this.controlText('Replay'); // on the next seek remove the replay button
  10746. this.one(this.player_, 'seeked', function (e) {
  10747. return _this2.handleSeeked(e);
  10748. });
  10749. };
  10750. return PlayToggle;
  10751. }(Button);
  10752. /**
  10753. * The text that should display over the `PlayToggle`s controls. Added for localization.
  10754. *
  10755. * @type {string}
  10756. * @private
  10757. */
  10758. PlayToggle.prototype.controlText_ = 'Play';
  10759. Component$1.registerComponent('PlayToggle', PlayToggle);
  10760. /**
  10761. * @file format-time.js
  10762. * @module format-time
  10763. */
  10764. /**
  10765. * Format seconds as a time string, H:MM:SS or M:SS. Supplying a guide (in
  10766. * seconds) will force a number of leading zeros to cover the length of the
  10767. * guide.
  10768. *
  10769. * @private
  10770. * @param {number} seconds
  10771. * Number of seconds to be turned into a string
  10772. *
  10773. * @param {number} guide
  10774. * Number (in seconds) to model the string after
  10775. *
  10776. * @return {string}
  10777. * Time formatted as H:MM:SS or M:SS
  10778. */
  10779. var defaultImplementation = function defaultImplementation(seconds, guide) {
  10780. seconds = seconds < 0 ? 0 : seconds;
  10781. var s = Math.floor(seconds % 60);
  10782. var m = Math.floor(seconds / 60 % 60);
  10783. var h = Math.floor(seconds / 3600);
  10784. var gm = Math.floor(guide / 60 % 60);
  10785. var gh = Math.floor(guide / 3600); // handle invalid times
  10786. if (isNaN(seconds) || seconds === Infinity) {
  10787. // '-' is false for all relational operators (e.g. <, >=) so this setting
  10788. // will add the minimum number of fields specified by the guide
  10789. h = m = s = '-';
  10790. } // Check if we need to show hours
  10791. h = h > 0 || gh > 0 ? h + ':' : ''; // If hours are showing, we may need to add a leading zero.
  10792. // Always show at least one digit of minutes.
  10793. m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':'; // Check if leading zero is need for seconds
  10794. s = s < 10 ? '0' + s : s;
  10795. return h + m + s;
  10796. }; // Internal pointer to the current implementation.
  10797. var implementation = defaultImplementation;
  10798. /**
  10799. * Replaces the default formatTime implementation with a custom implementation.
  10800. *
  10801. * @param {Function} customImplementation
  10802. * A function which will be used in place of the default formatTime
  10803. * implementation. Will receive the current time in seconds and the
  10804. * guide (in seconds) as arguments.
  10805. */
  10806. function setFormatTime(customImplementation) {
  10807. implementation = customImplementation;
  10808. }
  10809. /**
  10810. * Resets formatTime to the default implementation.
  10811. */
  10812. function resetFormatTime() {
  10813. implementation = defaultImplementation;
  10814. }
  10815. /**
  10816. * Delegates to either the default time formatting function or a custom
  10817. * function supplied via `setFormatTime`.
  10818. *
  10819. * Formats seconds as a time string (H:MM:SS or M:SS). Supplying a
  10820. * guide (in seconds) will force a number of leading zeros to cover the
  10821. * length of the guide.
  10822. *
  10823. * @static
  10824. * @example formatTime(125, 600) === "02:05"
  10825. * @param {number} seconds
  10826. * Number of seconds to be turned into a string
  10827. *
  10828. * @param {number} guide
  10829. * Number (in seconds) to model the string after
  10830. *
  10831. * @return {string}
  10832. * Time formatted as H:MM:SS or M:SS
  10833. */
  10834. function formatTime(seconds, guide) {
  10835. if (guide === void 0) {
  10836. guide = seconds;
  10837. }
  10838. return implementation(seconds, guide);
  10839. }
  10840. /**
  10841. * Displays time information about the video
  10842. *
  10843. * @extends Component
  10844. */
  10845. var TimeDisplay = /*#__PURE__*/function (_Component) {
  10846. inheritsLoose(TimeDisplay, _Component);
  10847. /**
  10848. * Creates an instance of this class.
  10849. *
  10850. * @param {Player} player
  10851. * The `Player` that this class should be attached to.
  10852. *
  10853. * @param {Object} [options]
  10854. * The key/value store of player options.
  10855. */
  10856. function TimeDisplay(player, options) {
  10857. var _this;
  10858. _this = _Component.call(this, player, options) || this;
  10859. _this.on(player, ['timeupdate', 'ended'], function (e) {
  10860. return _this.updateContent(e);
  10861. });
  10862. _this.updateTextNode_();
  10863. return _this;
  10864. }
  10865. /**
  10866. * Create the `Component`'s DOM element
  10867. *
  10868. * @return {Element}
  10869. * The element that was created.
  10870. */
  10871. var _proto = TimeDisplay.prototype;
  10872. _proto.createEl = function createEl$1() {
  10873. var className = this.buildCSSClass();
  10874. var el = _Component.prototype.createEl.call(this, 'div', {
  10875. className: className + " vjs-time-control vjs-control"
  10876. });
  10877. var span = createEl('span', {
  10878. className: 'vjs-control-text',
  10879. textContent: this.localize(this.labelText_) + "\xA0"
  10880. }, {
  10881. role: 'presentation'
  10882. });
  10883. el.appendChild(span);
  10884. this.contentEl_ = createEl('span', {
  10885. className: className + "-display"
  10886. }, {
  10887. // tell screen readers not to automatically read the time as it changes
  10888. 'aria-live': 'off',
  10889. // span elements have no implicit role, but some screen readers (notably VoiceOver)
  10890. // treat them as a break between items in the DOM when using arrow keys
  10891. // (or left-to-right swipes on iOS) to read contents of a page. Using
  10892. // role='presentation' causes VoiceOver to NOT treat this span as a break.
  10893. 'role': 'presentation'
  10894. });
  10895. el.appendChild(this.contentEl_);
  10896. return el;
  10897. };
  10898. _proto.dispose = function dispose() {
  10899. this.contentEl_ = null;
  10900. this.textNode_ = null;
  10901. _Component.prototype.dispose.call(this);
  10902. }
  10903. /**
  10904. * Updates the time display text node with a new time
  10905. *
  10906. * @param {number} [time=0] the time to update to
  10907. *
  10908. * @private
  10909. */
  10910. ;
  10911. _proto.updateTextNode_ = function updateTextNode_(time) {
  10912. var _this2 = this;
  10913. if (time === void 0) {
  10914. time = 0;
  10915. }
  10916. time = formatTime(time);
  10917. if (this.formattedTime_ === time) {
  10918. return;
  10919. }
  10920. this.formattedTime_ = time;
  10921. this.requestNamedAnimationFrame('TimeDisplay#updateTextNode_', function () {
  10922. if (!_this2.contentEl_) {
  10923. return;
  10924. }
  10925. var oldNode = _this2.textNode_;
  10926. if (oldNode && _this2.contentEl_.firstChild !== oldNode) {
  10927. oldNode = null;
  10928. 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.');
  10929. }
  10930. _this2.textNode_ = document.createTextNode(_this2.formattedTime_);
  10931. if (!_this2.textNode_) {
  10932. return;
  10933. }
  10934. if (oldNode) {
  10935. _this2.contentEl_.replaceChild(_this2.textNode_, oldNode);
  10936. } else {
  10937. _this2.contentEl_.appendChild(_this2.textNode_);
  10938. }
  10939. });
  10940. }
  10941. /**
  10942. * To be filled out in the child class, should update the displayed time
  10943. * in accordance with the fact that the current time has changed.
  10944. *
  10945. * @param {EventTarget~Event} [event]
  10946. * The `timeupdate` event that caused this to run.
  10947. *
  10948. * @listens Player#timeupdate
  10949. */
  10950. ;
  10951. _proto.updateContent = function updateContent(event) {};
  10952. return TimeDisplay;
  10953. }(Component$1);
  10954. /**
  10955. * The text that is added to the `TimeDisplay` for screen reader users.
  10956. *
  10957. * @type {string}
  10958. * @private
  10959. */
  10960. TimeDisplay.prototype.labelText_ = 'Time';
  10961. /**
  10962. * The text that should display over the `TimeDisplay`s controls. Added to for localization.
  10963. *
  10964. * @type {string}
  10965. * @private
  10966. *
  10967. * @deprecated in v7; controlText_ is not used in non-active display Components
  10968. */
  10969. TimeDisplay.prototype.controlText_ = 'Time';
  10970. Component$1.registerComponent('TimeDisplay', TimeDisplay);
  10971. /**
  10972. * Displays the current time
  10973. *
  10974. * @extends Component
  10975. */
  10976. var CurrentTimeDisplay = /*#__PURE__*/function (_TimeDisplay) {
  10977. inheritsLoose(CurrentTimeDisplay, _TimeDisplay);
  10978. function CurrentTimeDisplay() {
  10979. return _TimeDisplay.apply(this, arguments) || this;
  10980. }
  10981. var _proto = CurrentTimeDisplay.prototype;
  10982. /**
  10983. * Builds the default DOM `className`.
  10984. *
  10985. * @return {string}
  10986. * The DOM `className` for this object.
  10987. */
  10988. _proto.buildCSSClass = function buildCSSClass() {
  10989. return 'vjs-current-time';
  10990. }
  10991. /**
  10992. * Update current time display
  10993. *
  10994. * @param {EventTarget~Event} [event]
  10995. * The `timeupdate` event that caused this function to run.
  10996. *
  10997. * @listens Player#timeupdate
  10998. */
  10999. ;
  11000. _proto.updateContent = function updateContent(event) {
  11001. // Allows for smooth scrubbing, when player can't keep up.
  11002. var time;
  11003. if (this.player_.ended()) {
  11004. time = this.player_.duration();
  11005. } else {
  11006. time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  11007. }
  11008. this.updateTextNode_(time);
  11009. };
  11010. return CurrentTimeDisplay;
  11011. }(TimeDisplay);
  11012. /**
  11013. * The text that is added to the `CurrentTimeDisplay` for screen reader users.
  11014. *
  11015. * @type {string}
  11016. * @private
  11017. */
  11018. CurrentTimeDisplay.prototype.labelText_ = 'Current Time';
  11019. /**
  11020. * The text that should display over the `CurrentTimeDisplay`s controls. Added to for localization.
  11021. *
  11022. * @type {string}
  11023. * @private
  11024. *
  11025. * @deprecated in v7; controlText_ is not used in non-active display Components
  11026. */
  11027. CurrentTimeDisplay.prototype.controlText_ = 'Current Time';
  11028. Component$1.registerComponent('CurrentTimeDisplay', CurrentTimeDisplay);
  11029. /**
  11030. * Displays the duration
  11031. *
  11032. * @extends Component
  11033. */
  11034. var DurationDisplay = /*#__PURE__*/function (_TimeDisplay) {
  11035. inheritsLoose(DurationDisplay, _TimeDisplay);
  11036. /**
  11037. * Creates an instance of this class.
  11038. *
  11039. * @param {Player} player
  11040. * The `Player` that this class should be attached to.
  11041. *
  11042. * @param {Object} [options]
  11043. * The key/value store of player options.
  11044. */
  11045. function DurationDisplay(player, options) {
  11046. var _this;
  11047. _this = _TimeDisplay.call(this, player, options) || this;
  11048. var updateContent = function updateContent(e) {
  11049. return _this.updateContent(e);
  11050. }; // we do not want to/need to throttle duration changes,
  11051. // as they should always display the changed duration as
  11052. // it has changed
  11053. _this.on(player, 'durationchange', updateContent); // Listen to loadstart because the player duration is reset when a new media element is loaded,
  11054. // but the durationchange on the user agent will not fire.
  11055. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}
  11056. _this.on(player, 'loadstart', updateContent); // Also listen for timeupdate (in the parent) and loadedmetadata because removing those
  11057. // listeners could have broken dependent applications/libraries. These
  11058. // can likely be removed for 7.0.
  11059. _this.on(player, 'loadedmetadata', updateContent);
  11060. return _this;
  11061. }
  11062. /**
  11063. * Builds the default DOM `className`.
  11064. *
  11065. * @return {string}
  11066. * The DOM `className` for this object.
  11067. */
  11068. var _proto = DurationDisplay.prototype;
  11069. _proto.buildCSSClass = function buildCSSClass() {
  11070. return 'vjs-duration';
  11071. }
  11072. /**
  11073. * Update duration time display.
  11074. *
  11075. * @param {EventTarget~Event} [event]
  11076. * The `durationchange`, `timeupdate`, or `loadedmetadata` event that caused
  11077. * this function to be called.
  11078. *
  11079. * @listens Player#durationchange
  11080. * @listens Player#timeupdate
  11081. * @listens Player#loadedmetadata
  11082. */
  11083. ;
  11084. _proto.updateContent = function updateContent(event) {
  11085. var duration = this.player_.duration();
  11086. this.updateTextNode_(duration);
  11087. };
  11088. return DurationDisplay;
  11089. }(TimeDisplay);
  11090. /**
  11091. * The text that is added to the `DurationDisplay` for screen reader users.
  11092. *
  11093. * @type {string}
  11094. * @private
  11095. */
  11096. DurationDisplay.prototype.labelText_ = 'Duration';
  11097. /**
  11098. * The text that should display over the `DurationDisplay`s controls. Added to for localization.
  11099. *
  11100. * @type {string}
  11101. * @private
  11102. *
  11103. * @deprecated in v7; controlText_ is not used in non-active display Components
  11104. */
  11105. DurationDisplay.prototype.controlText_ = 'Duration';
  11106. Component$1.registerComponent('DurationDisplay', DurationDisplay);
  11107. /**
  11108. * The separator between the current time and duration.
  11109. * Can be hidden if it's not needed in the design.
  11110. *
  11111. * @extends Component
  11112. */
  11113. var TimeDivider = /*#__PURE__*/function (_Component) {
  11114. inheritsLoose(TimeDivider, _Component);
  11115. function TimeDivider() {
  11116. return _Component.apply(this, arguments) || this;
  11117. }
  11118. var _proto = TimeDivider.prototype;
  11119. /**
  11120. * Create the component's DOM element
  11121. *
  11122. * @return {Element}
  11123. * The element that was created.
  11124. */
  11125. _proto.createEl = function createEl() {
  11126. var el = _Component.prototype.createEl.call(this, 'div', {
  11127. className: 'vjs-time-control vjs-time-divider'
  11128. }, {
  11129. // this element and its contents can be hidden from assistive techs since
  11130. // it is made extraneous by the announcement of the control text
  11131. // for the current time and duration displays
  11132. 'aria-hidden': true
  11133. });
  11134. var div = _Component.prototype.createEl.call(this, 'div');
  11135. var span = _Component.prototype.createEl.call(this, 'span', {
  11136. textContent: '/'
  11137. });
  11138. div.appendChild(span);
  11139. el.appendChild(div);
  11140. return el;
  11141. };
  11142. return TimeDivider;
  11143. }(Component$1);
  11144. Component$1.registerComponent('TimeDivider', TimeDivider);
  11145. /**
  11146. * Displays the time left in the video
  11147. *
  11148. * @extends Component
  11149. */
  11150. var RemainingTimeDisplay = /*#__PURE__*/function (_TimeDisplay) {
  11151. inheritsLoose(RemainingTimeDisplay, _TimeDisplay);
  11152. /**
  11153. * Creates an instance of this class.
  11154. *
  11155. * @param {Player} player
  11156. * The `Player` that this class should be attached to.
  11157. *
  11158. * @param {Object} [options]
  11159. * The key/value store of player options.
  11160. */
  11161. function RemainingTimeDisplay(player, options) {
  11162. var _this;
  11163. _this = _TimeDisplay.call(this, player, options) || this;
  11164. _this.on(player, 'durationchange', function (e) {
  11165. return _this.updateContent(e);
  11166. });
  11167. return _this;
  11168. }
  11169. /**
  11170. * Builds the default DOM `className`.
  11171. *
  11172. * @return {string}
  11173. * The DOM `className` for this object.
  11174. */
  11175. var _proto = RemainingTimeDisplay.prototype;
  11176. _proto.buildCSSClass = function buildCSSClass() {
  11177. return 'vjs-remaining-time';
  11178. }
  11179. /**
  11180. * Create the `Component`'s DOM element with the "minus" characted prepend to the time
  11181. *
  11182. * @return {Element}
  11183. * The element that was created.
  11184. */
  11185. ;
  11186. _proto.createEl = function createEl$1() {
  11187. var el = _TimeDisplay.prototype.createEl.call(this);
  11188. if (this.options_.displayNegative !== false) {
  11189. el.insertBefore(createEl('span', {}, {
  11190. 'aria-hidden': true
  11191. }, '-'), this.contentEl_);
  11192. }
  11193. return el;
  11194. }
  11195. /**
  11196. * Update remaining time display.
  11197. *
  11198. * @param {EventTarget~Event} [event]
  11199. * The `timeupdate` or `durationchange` event that caused this to run.
  11200. *
  11201. * @listens Player#timeupdate
  11202. * @listens Player#durationchange
  11203. */
  11204. ;
  11205. _proto.updateContent = function updateContent(event) {
  11206. if (typeof this.player_.duration() !== 'number') {
  11207. return;
  11208. }
  11209. var time; // @deprecated We should only use remainingTimeDisplay
  11210. // as of video.js 7
  11211. if (this.player_.ended()) {
  11212. time = 0;
  11213. } else if (this.player_.remainingTimeDisplay) {
  11214. time = this.player_.remainingTimeDisplay();
  11215. } else {
  11216. time = this.player_.remainingTime();
  11217. }
  11218. this.updateTextNode_(time);
  11219. };
  11220. return RemainingTimeDisplay;
  11221. }(TimeDisplay);
  11222. /**
  11223. * The text that is added to the `RemainingTimeDisplay` for screen reader users.
  11224. *
  11225. * @type {string}
  11226. * @private
  11227. */
  11228. RemainingTimeDisplay.prototype.labelText_ = 'Remaining Time';
  11229. /**
  11230. * The text that should display over the `RemainingTimeDisplay`s controls. Added to for localization.
  11231. *
  11232. * @type {string}
  11233. * @private
  11234. *
  11235. * @deprecated in v7; controlText_ is not used in non-active display Components
  11236. */
  11237. RemainingTimeDisplay.prototype.controlText_ = 'Remaining Time';
  11238. Component$1.registerComponent('RemainingTimeDisplay', RemainingTimeDisplay);
  11239. /**
  11240. * Displays the live indicator when duration is Infinity.
  11241. *
  11242. * @extends Component
  11243. */
  11244. var LiveDisplay = /*#__PURE__*/function (_Component) {
  11245. inheritsLoose(LiveDisplay, _Component);
  11246. /**
  11247. * Creates an instance of this class.
  11248. *
  11249. * @param {Player} player
  11250. * The `Player` that this class should be attached to.
  11251. *
  11252. * @param {Object} [options]
  11253. * The key/value store of player options.
  11254. */
  11255. function LiveDisplay(player, options) {
  11256. var _this;
  11257. _this = _Component.call(this, player, options) || this;
  11258. _this.updateShowing();
  11259. _this.on(_this.player(), 'durationchange', function (e) {
  11260. return _this.updateShowing(e);
  11261. });
  11262. return _this;
  11263. }
  11264. /**
  11265. * Create the `Component`'s DOM element
  11266. *
  11267. * @return {Element}
  11268. * The element that was created.
  11269. */
  11270. var _proto = LiveDisplay.prototype;
  11271. _proto.createEl = function createEl$1() {
  11272. var el = _Component.prototype.createEl.call(this, 'div', {
  11273. className: 'vjs-live-control vjs-control'
  11274. });
  11275. this.contentEl_ = createEl('div', {
  11276. className: 'vjs-live-display'
  11277. }, {
  11278. 'aria-live': 'off'
  11279. });
  11280. this.contentEl_.appendChild(createEl('span', {
  11281. className: 'vjs-control-text',
  11282. textContent: this.localize('Stream Type') + "\xA0"
  11283. }));
  11284. this.contentEl_.appendChild(document.createTextNode(this.localize('LIVE')));
  11285. el.appendChild(this.contentEl_);
  11286. return el;
  11287. };
  11288. _proto.dispose = function dispose() {
  11289. this.contentEl_ = null;
  11290. _Component.prototype.dispose.call(this);
  11291. }
  11292. /**
  11293. * Check the duration to see if the LiveDisplay should be showing or not. Then show/hide
  11294. * it accordingly
  11295. *
  11296. * @param {EventTarget~Event} [event]
  11297. * The {@link Player#durationchange} event that caused this function to run.
  11298. *
  11299. * @listens Player#durationchange
  11300. */
  11301. ;
  11302. _proto.updateShowing = function updateShowing(event) {
  11303. if (this.player().duration() === Infinity) {
  11304. this.show();
  11305. } else {
  11306. this.hide();
  11307. }
  11308. };
  11309. return LiveDisplay;
  11310. }(Component$1);
  11311. Component$1.registerComponent('LiveDisplay', LiveDisplay);
  11312. /**
  11313. * Displays the live indicator when duration is Infinity.
  11314. *
  11315. * @extends Component
  11316. */
  11317. var SeekToLive = /*#__PURE__*/function (_Button) {
  11318. inheritsLoose(SeekToLive, _Button);
  11319. /**
  11320. * Creates an instance of this class.
  11321. *
  11322. * @param {Player} player
  11323. * The `Player` that this class should be attached to.
  11324. *
  11325. * @param {Object} [options]
  11326. * The key/value store of player options.
  11327. */
  11328. function SeekToLive(player, options) {
  11329. var _this;
  11330. _this = _Button.call(this, player, options) || this;
  11331. _this.updateLiveEdgeStatus();
  11332. if (_this.player_.liveTracker) {
  11333. _this.updateLiveEdgeStatusHandler_ = function (e) {
  11334. return _this.updateLiveEdgeStatus(e);
  11335. };
  11336. _this.on(_this.player_.liveTracker, 'liveedgechange', _this.updateLiveEdgeStatusHandler_);
  11337. }
  11338. return _this;
  11339. }
  11340. /**
  11341. * Create the `Component`'s DOM element
  11342. *
  11343. * @return {Element}
  11344. * The element that was created.
  11345. */
  11346. var _proto = SeekToLive.prototype;
  11347. _proto.createEl = function createEl$1() {
  11348. var el = _Button.prototype.createEl.call(this, 'button', {
  11349. className: 'vjs-seek-to-live-control vjs-control'
  11350. });
  11351. this.textEl_ = createEl('span', {
  11352. className: 'vjs-seek-to-live-text',
  11353. textContent: this.localize('LIVE')
  11354. }, {
  11355. 'aria-hidden': 'true'
  11356. });
  11357. el.appendChild(this.textEl_);
  11358. return el;
  11359. }
  11360. /**
  11361. * Update the state of this button if we are at the live edge
  11362. * or not
  11363. */
  11364. ;
  11365. _proto.updateLiveEdgeStatus = function updateLiveEdgeStatus() {
  11366. // default to live edge
  11367. if (!this.player_.liveTracker || this.player_.liveTracker.atLiveEdge()) {
  11368. this.setAttribute('aria-disabled', true);
  11369. this.addClass('vjs-at-live-edge');
  11370. this.controlText('Seek to live, currently playing live');
  11371. } else {
  11372. this.setAttribute('aria-disabled', false);
  11373. this.removeClass('vjs-at-live-edge');
  11374. this.controlText('Seek to live, currently behind live');
  11375. }
  11376. }
  11377. /**
  11378. * On click bring us as near to the live point as possible.
  11379. * This requires that we wait for the next `live-seekable-change`
  11380. * event which will happen every segment length seconds.
  11381. */
  11382. ;
  11383. _proto.handleClick = function handleClick() {
  11384. this.player_.liveTracker.seekToLiveEdge();
  11385. }
  11386. /**
  11387. * Dispose of the element and stop tracking
  11388. */
  11389. ;
  11390. _proto.dispose = function dispose() {
  11391. if (this.player_.liveTracker) {
  11392. this.off(this.player_.liveTracker, 'liveedgechange', this.updateLiveEdgeStatusHandler_);
  11393. }
  11394. this.textEl_ = null;
  11395. _Button.prototype.dispose.call(this);
  11396. };
  11397. return SeekToLive;
  11398. }(Button);
  11399. SeekToLive.prototype.controlText_ = 'Seek to live, currently playing live';
  11400. Component$1.registerComponent('SeekToLive', SeekToLive);
  11401. /**
  11402. * Keep a number between a min and a max value
  11403. *
  11404. * @param {number} number
  11405. * The number to clamp
  11406. *
  11407. * @param {number} min
  11408. * The minimum value
  11409. * @param {number} max
  11410. * The maximum value
  11411. *
  11412. * @return {number}
  11413. * the clamped number
  11414. */
  11415. var clamp = function clamp(number, min, max) {
  11416. number = Number(number);
  11417. return Math.min(max, Math.max(min, isNaN(number) ? min : number));
  11418. };
  11419. /**
  11420. * The base functionality for a slider. Can be vertical or horizontal.
  11421. * For instance the volume bar or the seek bar on a video is a slider.
  11422. *
  11423. * @extends Component
  11424. */
  11425. var Slider = /*#__PURE__*/function (_Component) {
  11426. inheritsLoose(Slider, _Component);
  11427. /**
  11428. * Create an instance of this class
  11429. *
  11430. * @param {Player} player
  11431. * The `Player` that this class should be attached to.
  11432. *
  11433. * @param {Object} [options]
  11434. * The key/value store of player options.
  11435. */
  11436. function Slider(player, options) {
  11437. var _this;
  11438. _this = _Component.call(this, player, options) || this;
  11439. _this.handleMouseDown_ = function (e) {
  11440. return _this.handleMouseDown(e);
  11441. };
  11442. _this.handleMouseUp_ = function (e) {
  11443. return _this.handleMouseUp(e);
  11444. };
  11445. _this.handleKeyDown_ = function (e) {
  11446. return _this.handleKeyDown(e);
  11447. };
  11448. _this.handleClick_ = function (e) {
  11449. return _this.handleClick(e);
  11450. };
  11451. _this.handleMouseMove_ = function (e) {
  11452. return _this.handleMouseMove(e);
  11453. };
  11454. _this.update_ = function (e) {
  11455. return _this.update(e);
  11456. }; // Set property names to bar to match with the child Slider class is looking for
  11457. _this.bar = _this.getChild(_this.options_.barName); // Set a horizontal or vertical class on the slider depending on the slider type
  11458. _this.vertical(!!_this.options_.vertical);
  11459. _this.enable();
  11460. return _this;
  11461. }
  11462. /**
  11463. * Are controls are currently enabled for this slider or not.
  11464. *
  11465. * @return {boolean}
  11466. * true if controls are enabled, false otherwise
  11467. */
  11468. var _proto = Slider.prototype;
  11469. _proto.enabled = function enabled() {
  11470. return this.enabled_;
  11471. }
  11472. /**
  11473. * Enable controls for this slider if they are disabled
  11474. */
  11475. ;
  11476. _proto.enable = function enable() {
  11477. if (this.enabled()) {
  11478. return;
  11479. }
  11480. this.on('mousedown', this.handleMouseDown_);
  11481. this.on('touchstart', this.handleMouseDown_);
  11482. this.on('keydown', this.handleKeyDown_);
  11483. this.on('click', this.handleClick_); // TODO: deprecated, controlsvisible does not seem to be fired
  11484. this.on(this.player_, 'controlsvisible', this.update);
  11485. if (this.playerEvent) {
  11486. this.on(this.player_, this.playerEvent, this.update);
  11487. }
  11488. this.removeClass('disabled');
  11489. this.setAttribute('tabindex', 0);
  11490. this.enabled_ = true;
  11491. }
  11492. /**
  11493. * Disable controls for this slider if they are enabled
  11494. */
  11495. ;
  11496. _proto.disable = function disable() {
  11497. if (!this.enabled()) {
  11498. return;
  11499. }
  11500. var doc = this.bar.el_.ownerDocument;
  11501. this.off('mousedown', this.handleMouseDown_);
  11502. this.off('touchstart', this.handleMouseDown_);
  11503. this.off('keydown', this.handleKeyDown_);
  11504. this.off('click', this.handleClick_);
  11505. this.off(this.player_, 'controlsvisible', this.update_);
  11506. this.off(doc, 'mousemove', this.handleMouseMove_);
  11507. this.off(doc, 'mouseup', this.handleMouseUp_);
  11508. this.off(doc, 'touchmove', this.handleMouseMove_);
  11509. this.off(doc, 'touchend', this.handleMouseUp_);
  11510. this.removeAttribute('tabindex');
  11511. this.addClass('disabled');
  11512. if (this.playerEvent) {
  11513. this.off(this.player_, this.playerEvent, this.update);
  11514. }
  11515. this.enabled_ = false;
  11516. }
  11517. /**
  11518. * Create the `Slider`s DOM element.
  11519. *
  11520. * @param {string} type
  11521. * Type of element to create.
  11522. *
  11523. * @param {Object} [props={}]
  11524. * List of properties in Object form.
  11525. *
  11526. * @param {Object} [attributes={}]
  11527. * list of attributes in Object form.
  11528. *
  11529. * @return {Element}
  11530. * The element that gets created.
  11531. */
  11532. ;
  11533. _proto.createEl = function createEl(type, props, attributes) {
  11534. if (props === void 0) {
  11535. props = {};
  11536. }
  11537. if (attributes === void 0) {
  11538. attributes = {};
  11539. }
  11540. // Add the slider element class to all sub classes
  11541. props.className = props.className + ' vjs-slider';
  11542. props = assign$1({
  11543. tabIndex: 0
  11544. }, props);
  11545. attributes = assign$1({
  11546. 'role': 'slider',
  11547. 'aria-valuenow': 0,
  11548. 'aria-valuemin': 0,
  11549. 'aria-valuemax': 100,
  11550. 'tabIndex': 0
  11551. }, attributes);
  11552. return _Component.prototype.createEl.call(this, type, props, attributes);
  11553. }
  11554. /**
  11555. * Handle `mousedown` or `touchstart` events on the `Slider`.
  11556. *
  11557. * @param {EventTarget~Event} event
  11558. * `mousedown` or `touchstart` event that triggered this function
  11559. *
  11560. * @listens mousedown
  11561. * @listens touchstart
  11562. * @fires Slider#slideractive
  11563. */
  11564. ;
  11565. _proto.handleMouseDown = function handleMouseDown(event) {
  11566. var doc = this.bar.el_.ownerDocument;
  11567. if (event.type === 'mousedown') {
  11568. event.preventDefault();
  11569. } // Do not call preventDefault() on touchstart in Chrome
  11570. // to avoid console warnings. Use a 'touch-action: none' style
  11571. // instead to prevent unintented scrolling.
  11572. // https://developers.google.com/web/updates/2017/01/scrolling-intervention
  11573. if (event.type === 'touchstart' && !IS_CHROME) {
  11574. event.preventDefault();
  11575. }
  11576. blockTextSelection();
  11577. this.addClass('vjs-sliding');
  11578. /**
  11579. * Triggered when the slider is in an active state
  11580. *
  11581. * @event Slider#slideractive
  11582. * @type {EventTarget~Event}
  11583. */
  11584. this.trigger('slideractive');
  11585. this.on(doc, 'mousemove', this.handleMouseMove_);
  11586. this.on(doc, 'mouseup', this.handleMouseUp_);
  11587. this.on(doc, 'touchmove', this.handleMouseMove_);
  11588. this.on(doc, 'touchend', this.handleMouseUp_);
  11589. this.handleMouseMove(event, true);
  11590. }
  11591. /**
  11592. * Handle the `mousemove`, `touchmove`, and `mousedown` events on this `Slider`.
  11593. * The `mousemove` and `touchmove` events will only only trigger this function during
  11594. * `mousedown` and `touchstart`. This is due to {@link Slider#handleMouseDown} and
  11595. * {@link Slider#handleMouseUp}.
  11596. *
  11597. * @param {EventTarget~Event} event
  11598. * `mousedown`, `mousemove`, `touchstart`, or `touchmove` event that triggered
  11599. * this function
  11600. * @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.
  11601. *
  11602. * @listens mousemove
  11603. * @listens touchmove
  11604. */
  11605. ;
  11606. _proto.handleMouseMove = function handleMouseMove(event) {}
  11607. /**
  11608. * Handle `mouseup` or `touchend` events on the `Slider`.
  11609. *
  11610. * @param {EventTarget~Event} event
  11611. * `mouseup` or `touchend` event that triggered this function.
  11612. *
  11613. * @listens touchend
  11614. * @listens mouseup
  11615. * @fires Slider#sliderinactive
  11616. */
  11617. ;
  11618. _proto.handleMouseUp = function handleMouseUp() {
  11619. var doc = this.bar.el_.ownerDocument;
  11620. unblockTextSelection();
  11621. this.removeClass('vjs-sliding');
  11622. /**
  11623. * Triggered when the slider is no longer in an active state.
  11624. *
  11625. * @event Slider#sliderinactive
  11626. * @type {EventTarget~Event}
  11627. */
  11628. this.trigger('sliderinactive');
  11629. this.off(doc, 'mousemove', this.handleMouseMove_);
  11630. this.off(doc, 'mouseup', this.handleMouseUp_);
  11631. this.off(doc, 'touchmove', this.handleMouseMove_);
  11632. this.off(doc, 'touchend', this.handleMouseUp_);
  11633. this.update();
  11634. }
  11635. /**
  11636. * Update the progress bar of the `Slider`.
  11637. *
  11638. * @return {number}
  11639. * The percentage of progress the progress bar represents as a
  11640. * number from 0 to 1.
  11641. */
  11642. ;
  11643. _proto.update = function update() {
  11644. var _this2 = this;
  11645. // In VolumeBar init we have a setTimeout for update that pops and update
  11646. // to the end of the execution stack. The player is destroyed before then
  11647. // update will cause an error
  11648. // If there's no bar...
  11649. if (!this.el_ || !this.bar) {
  11650. return;
  11651. } // clamp progress between 0 and 1
  11652. // and only round to four decimal places, as we round to two below
  11653. var progress = this.getProgress();
  11654. if (progress === this.progress_) {
  11655. return progress;
  11656. }
  11657. this.progress_ = progress;
  11658. this.requestNamedAnimationFrame('Slider#update', function () {
  11659. // Set the new bar width or height
  11660. var sizeKey = _this2.vertical() ? 'height' : 'width'; // Convert to a percentage for css value
  11661. _this2.bar.el().style[sizeKey] = (progress * 100).toFixed(2) + '%';
  11662. });
  11663. return progress;
  11664. }
  11665. /**
  11666. * Get the percentage of the bar that should be filled
  11667. * but clamped and rounded.
  11668. *
  11669. * @return {number}
  11670. * percentage filled that the slider is
  11671. */
  11672. ;
  11673. _proto.getProgress = function getProgress() {
  11674. return Number(clamp(this.getPercent(), 0, 1).toFixed(4));
  11675. }
  11676. /**
  11677. * Calculate distance for slider
  11678. *
  11679. * @param {EventTarget~Event} event
  11680. * The event that caused this function to run.
  11681. *
  11682. * @return {number}
  11683. * The current position of the Slider.
  11684. * - position.x for vertical `Slider`s
  11685. * - position.y for horizontal `Slider`s
  11686. */
  11687. ;
  11688. _proto.calculateDistance = function calculateDistance(event) {
  11689. var position = getPointerPosition(this.el_, event);
  11690. if (this.vertical()) {
  11691. return position.y;
  11692. }
  11693. return position.x;
  11694. }
  11695. /**
  11696. * Handle a `keydown` event on the `Slider`. Watches for left, rigth, up, and down
  11697. * arrow keys. This function will only be called when the slider has focus. See
  11698. * {@link Slider#handleFocus} and {@link Slider#handleBlur}.
  11699. *
  11700. * @param {EventTarget~Event} event
  11701. * the `keydown` event that caused this function to run.
  11702. *
  11703. * @listens keydown
  11704. */
  11705. ;
  11706. _proto.handleKeyDown = function handleKeyDown(event) {
  11707. // Left and Down Arrows
  11708. if (keycode.isEventKey(event, 'Left') || keycode.isEventKey(event, 'Down')) {
  11709. event.preventDefault();
  11710. event.stopPropagation();
  11711. this.stepBack(); // Up and Right Arrows
  11712. } else if (keycode.isEventKey(event, 'Right') || keycode.isEventKey(event, 'Up')) {
  11713. event.preventDefault();
  11714. event.stopPropagation();
  11715. this.stepForward();
  11716. } else {
  11717. // Pass keydown handling up for unsupported keys
  11718. _Component.prototype.handleKeyDown.call(this, event);
  11719. }
  11720. }
  11721. /**
  11722. * Listener for click events on slider, used to prevent clicks
  11723. * from bubbling up to parent elements like button menus.
  11724. *
  11725. * @param {Object} event
  11726. * Event that caused this object to run
  11727. */
  11728. ;
  11729. _proto.handleClick = function handleClick(event) {
  11730. event.stopPropagation();
  11731. event.preventDefault();
  11732. }
  11733. /**
  11734. * Get/set if slider is horizontal for vertical
  11735. *
  11736. * @param {boolean} [bool]
  11737. * - true if slider is vertical,
  11738. * - false is horizontal
  11739. *
  11740. * @return {boolean}
  11741. * - true if slider is vertical, and getting
  11742. * - false if the slider is horizontal, and getting
  11743. */
  11744. ;
  11745. _proto.vertical = function vertical(bool) {
  11746. if (bool === undefined) {
  11747. return this.vertical_ || false;
  11748. }
  11749. this.vertical_ = !!bool;
  11750. if (this.vertical_) {
  11751. this.addClass('vjs-slider-vertical');
  11752. } else {
  11753. this.addClass('vjs-slider-horizontal');
  11754. }
  11755. };
  11756. return Slider;
  11757. }(Component$1);
  11758. Component$1.registerComponent('Slider', Slider);
  11759. var percentify = function percentify(time, end) {
  11760. return clamp(time / end * 100, 0, 100).toFixed(2) + '%';
  11761. };
  11762. /**
  11763. * Shows loading progress
  11764. *
  11765. * @extends Component
  11766. */
  11767. var LoadProgressBar = /*#__PURE__*/function (_Component) {
  11768. inheritsLoose(LoadProgressBar, _Component);
  11769. /**
  11770. * Creates an instance of this class.
  11771. *
  11772. * @param {Player} player
  11773. * The `Player` that this class should be attached to.
  11774. *
  11775. * @param {Object} [options]
  11776. * The key/value store of player options.
  11777. */
  11778. function LoadProgressBar(player, options) {
  11779. var _this;
  11780. _this = _Component.call(this, player, options) || this;
  11781. _this.partEls_ = [];
  11782. _this.on(player, 'progress', function (e) {
  11783. return _this.update(e);
  11784. });
  11785. return _this;
  11786. }
  11787. /**
  11788. * Create the `Component`'s DOM element
  11789. *
  11790. * @return {Element}
  11791. * The element that was created.
  11792. */
  11793. var _proto = LoadProgressBar.prototype;
  11794. _proto.createEl = function createEl$1() {
  11795. var el = _Component.prototype.createEl.call(this, 'div', {
  11796. className: 'vjs-load-progress'
  11797. });
  11798. var wrapper = createEl('span', {
  11799. className: 'vjs-control-text'
  11800. });
  11801. var loadedText = createEl('span', {
  11802. textContent: this.localize('Loaded')
  11803. });
  11804. var separator = document.createTextNode(': ');
  11805. this.percentageEl_ = createEl('span', {
  11806. className: 'vjs-control-text-loaded-percentage',
  11807. textContent: '0%'
  11808. });
  11809. el.appendChild(wrapper);
  11810. wrapper.appendChild(loadedText);
  11811. wrapper.appendChild(separator);
  11812. wrapper.appendChild(this.percentageEl_);
  11813. return el;
  11814. };
  11815. _proto.dispose = function dispose() {
  11816. this.partEls_ = null;
  11817. this.percentageEl_ = null;
  11818. _Component.prototype.dispose.call(this);
  11819. }
  11820. /**
  11821. * Update progress bar
  11822. *
  11823. * @param {EventTarget~Event} [event]
  11824. * The `progress` event that caused this function to run.
  11825. *
  11826. * @listens Player#progress
  11827. */
  11828. ;
  11829. _proto.update = function update(event) {
  11830. var _this2 = this;
  11831. this.requestNamedAnimationFrame('LoadProgressBar#update', function () {
  11832. var liveTracker = _this2.player_.liveTracker;
  11833. var buffered = _this2.player_.buffered();
  11834. var duration = liveTracker && liveTracker.isLive() ? liveTracker.seekableEnd() : _this2.player_.duration();
  11835. var bufferedEnd = _this2.player_.bufferedEnd();
  11836. var children = _this2.partEls_;
  11837. var percent = percentify(bufferedEnd, duration);
  11838. if (_this2.percent_ !== percent) {
  11839. // update the width of the progress bar
  11840. _this2.el_.style.width = percent; // update the control-text
  11841. textContent(_this2.percentageEl_, percent);
  11842. _this2.percent_ = percent;
  11843. } // add child elements to represent the individual buffered time ranges
  11844. for (var i = 0; i < buffered.length; i++) {
  11845. var start = buffered.start(i);
  11846. var end = buffered.end(i);
  11847. var part = children[i];
  11848. if (!part) {
  11849. part = _this2.el_.appendChild(createEl());
  11850. children[i] = part;
  11851. } // only update if changed
  11852. if (part.dataset.start === start && part.dataset.end === end) {
  11853. continue;
  11854. }
  11855. part.dataset.start = start;
  11856. part.dataset.end = end; // set the percent based on the width of the progress bar (bufferedEnd)
  11857. part.style.left = percentify(start, bufferedEnd);
  11858. part.style.width = percentify(end - start, bufferedEnd);
  11859. } // remove unused buffered range elements
  11860. for (var _i = children.length; _i > buffered.length; _i--) {
  11861. _this2.el_.removeChild(children[_i - 1]);
  11862. }
  11863. children.length = buffered.length;
  11864. });
  11865. };
  11866. return LoadProgressBar;
  11867. }(Component$1);
  11868. Component$1.registerComponent('LoadProgressBar', LoadProgressBar);
  11869. /**
  11870. * Time tooltips display a time above the progress bar.
  11871. *
  11872. * @extends Component
  11873. */
  11874. var TimeTooltip = /*#__PURE__*/function (_Component) {
  11875. inheritsLoose(TimeTooltip, _Component);
  11876. /**
  11877. * Creates an instance of this class.
  11878. *
  11879. * @param {Player} player
  11880. * The {@link Player} that this class should be attached to.
  11881. *
  11882. * @param {Object} [options]
  11883. * The key/value store of player options.
  11884. */
  11885. function TimeTooltip(player, options) {
  11886. var _this;
  11887. _this = _Component.call(this, player, options) || this;
  11888. _this.update = throttle(bind(assertThisInitialized(_this), _this.update), UPDATE_REFRESH_INTERVAL);
  11889. return _this;
  11890. }
  11891. /**
  11892. * Create the time tooltip DOM element
  11893. *
  11894. * @return {Element}
  11895. * The element that was created.
  11896. */
  11897. var _proto = TimeTooltip.prototype;
  11898. _proto.createEl = function createEl() {
  11899. return _Component.prototype.createEl.call(this, 'div', {
  11900. className: 'vjs-time-tooltip'
  11901. }, {
  11902. 'aria-hidden': 'true'
  11903. });
  11904. }
  11905. /**
  11906. * Updates the position of the time tooltip relative to the `SeekBar`.
  11907. *
  11908. * @param {Object} seekBarRect
  11909. * The `ClientRect` for the {@link SeekBar} element.
  11910. *
  11911. * @param {number} seekBarPoint
  11912. * A number from 0 to 1, representing a horizontal reference point
  11913. * from the left edge of the {@link SeekBar}
  11914. */
  11915. ;
  11916. _proto.update = function update(seekBarRect, seekBarPoint, content) {
  11917. var tooltipRect = findPosition(this.el_);
  11918. var playerRect = getBoundingClientRect(this.player_.el());
  11919. var seekBarPointPx = seekBarRect.width * seekBarPoint; // do nothing if either rect isn't available
  11920. // for example, if the player isn't in the DOM for testing
  11921. if (!playerRect || !tooltipRect) {
  11922. return;
  11923. } // This is the space left of the `seekBarPoint` available within the bounds
  11924. // of the player. We calculate any gap between the left edge of the player
  11925. // and the left edge of the `SeekBar` and add the number of pixels in the
  11926. // `SeekBar` before hitting the `seekBarPoint`
  11927. var spaceLeftOfPoint = seekBarRect.left - playerRect.left + seekBarPointPx; // This is the space right of the `seekBarPoint` available within the bounds
  11928. // of the player. We calculate the number of pixels from the `seekBarPoint`
  11929. // to the right edge of the `SeekBar` and add to that any gap between the
  11930. // right edge of the `SeekBar` and the player.
  11931. var spaceRightOfPoint = seekBarRect.width - seekBarPointPx + (playerRect.right - seekBarRect.right); // This is the number of pixels by which the tooltip will need to be pulled
  11932. // further to the right to center it over the `seekBarPoint`.
  11933. var pullTooltipBy = tooltipRect.width / 2; // Adjust the `pullTooltipBy` distance to the left or right depending on
  11934. // the results of the space calculations above.
  11935. if (spaceLeftOfPoint < pullTooltipBy) {
  11936. pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
  11937. } else if (spaceRightOfPoint < pullTooltipBy) {
  11938. pullTooltipBy = spaceRightOfPoint;
  11939. } // Due to the imprecision of decimal/ratio based calculations and varying
  11940. // rounding behaviors, there are cases where the spacing adjustment is off
  11941. // by a pixel or two. This adds insurance to these calculations.
  11942. if (pullTooltipBy < 0) {
  11943. pullTooltipBy = 0;
  11944. } else if (pullTooltipBy > tooltipRect.width) {
  11945. pullTooltipBy = tooltipRect.width;
  11946. } // prevent small width fluctuations within 0.4px from
  11947. // changing the value below.
  11948. // This really helps for live to prevent the play
  11949. // progress time tooltip from jittering
  11950. pullTooltipBy = Math.round(pullTooltipBy);
  11951. this.el_.style.right = "-" + pullTooltipBy + "px";
  11952. this.write(content);
  11953. }
  11954. /**
  11955. * Write the time to the tooltip DOM element.
  11956. *
  11957. * @param {string} content
  11958. * The formatted time for the tooltip.
  11959. */
  11960. ;
  11961. _proto.write = function write(content) {
  11962. textContent(this.el_, content);
  11963. }
  11964. /**
  11965. * Updates the position of the time tooltip relative to the `SeekBar`.
  11966. *
  11967. * @param {Object} seekBarRect
  11968. * The `ClientRect` for the {@link SeekBar} element.
  11969. *
  11970. * @param {number} seekBarPoint
  11971. * A number from 0 to 1, representing a horizontal reference point
  11972. * from the left edge of the {@link SeekBar}
  11973. *
  11974. * @param {number} time
  11975. * The time to update the tooltip to, not used during live playback
  11976. *
  11977. * @param {Function} cb
  11978. * A function that will be called during the request animation frame
  11979. * for tooltips that need to do additional animations from the default
  11980. */
  11981. ;
  11982. _proto.updateTime = function updateTime(seekBarRect, seekBarPoint, time, cb) {
  11983. var _this2 = this;
  11984. this.requestNamedAnimationFrame('TimeTooltip#updateTime', function () {
  11985. var content;
  11986. var duration = _this2.player_.duration();
  11987. if (_this2.player_.liveTracker && _this2.player_.liveTracker.isLive()) {
  11988. var liveWindow = _this2.player_.liveTracker.liveWindow();
  11989. var secondsBehind = liveWindow - seekBarPoint * liveWindow;
  11990. content = (secondsBehind < 1 ? '' : '-') + formatTime(secondsBehind, liveWindow);
  11991. } else {
  11992. content = formatTime(time, duration);
  11993. }
  11994. _this2.update(seekBarRect, seekBarPoint, content);
  11995. if (cb) {
  11996. cb();
  11997. }
  11998. });
  11999. };
  12000. return TimeTooltip;
  12001. }(Component$1);
  12002. Component$1.registerComponent('TimeTooltip', TimeTooltip);
  12003. /**
  12004. * Used by {@link SeekBar} to display media playback progress as part of the
  12005. * {@link ProgressControl}.
  12006. *
  12007. * @extends Component
  12008. */
  12009. var PlayProgressBar = /*#__PURE__*/function (_Component) {
  12010. inheritsLoose(PlayProgressBar, _Component);
  12011. /**
  12012. * Creates an instance of this class.
  12013. *
  12014. * @param {Player} player
  12015. * The {@link Player} that this class should be attached to.
  12016. *
  12017. * @param {Object} [options]
  12018. * The key/value store of player options.
  12019. */
  12020. function PlayProgressBar(player, options) {
  12021. var _this;
  12022. _this = _Component.call(this, player, options) || this;
  12023. _this.update = throttle(bind(assertThisInitialized(_this), _this.update), UPDATE_REFRESH_INTERVAL);
  12024. return _this;
  12025. }
  12026. /**
  12027. * Create the the DOM element for this class.
  12028. *
  12029. * @return {Element}
  12030. * The element that was created.
  12031. */
  12032. var _proto = PlayProgressBar.prototype;
  12033. _proto.createEl = function createEl() {
  12034. return _Component.prototype.createEl.call(this, 'div', {
  12035. className: 'vjs-play-progress vjs-slider-bar'
  12036. }, {
  12037. 'aria-hidden': 'true'
  12038. });
  12039. }
  12040. /**
  12041. * Enqueues updates to its own DOM as well as the DOM of its
  12042. * {@link TimeTooltip} child.
  12043. *
  12044. * @param {Object} seekBarRect
  12045. * The `ClientRect` for the {@link SeekBar} element.
  12046. *
  12047. * @param {number} seekBarPoint
  12048. * A number from 0 to 1, representing a horizontal reference point
  12049. * from the left edge of the {@link SeekBar}
  12050. */
  12051. ;
  12052. _proto.update = function update(seekBarRect, seekBarPoint) {
  12053. var timeTooltip = this.getChild('timeTooltip');
  12054. if (!timeTooltip) {
  12055. return;
  12056. }
  12057. var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  12058. timeTooltip.updateTime(seekBarRect, seekBarPoint, time);
  12059. };
  12060. return PlayProgressBar;
  12061. }(Component$1);
  12062. /**
  12063. * Default options for {@link PlayProgressBar}.
  12064. *
  12065. * @type {Object}
  12066. * @private
  12067. */
  12068. PlayProgressBar.prototype.options_ = {
  12069. children: []
  12070. }; // Time tooltips should not be added to a player on mobile devices
  12071. if (!IS_IOS && !IS_ANDROID) {
  12072. PlayProgressBar.prototype.options_.children.push('timeTooltip');
  12073. }
  12074. Component$1.registerComponent('PlayProgressBar', PlayProgressBar);
  12075. /**
  12076. * The {@link MouseTimeDisplay} component tracks mouse movement over the
  12077. * {@link ProgressControl}. It displays an indicator and a {@link TimeTooltip}
  12078. * indicating the time which is represented by a given point in the
  12079. * {@link ProgressControl}.
  12080. *
  12081. * @extends Component
  12082. */
  12083. var MouseTimeDisplay = /*#__PURE__*/function (_Component) {
  12084. inheritsLoose(MouseTimeDisplay, _Component);
  12085. /**
  12086. * Creates an instance of this class.
  12087. *
  12088. * @param {Player} player
  12089. * The {@link Player} that this class should be attached to.
  12090. *
  12091. * @param {Object} [options]
  12092. * The key/value store of player options.
  12093. */
  12094. function MouseTimeDisplay(player, options) {
  12095. var _this;
  12096. _this = _Component.call(this, player, options) || this;
  12097. _this.update = throttle(bind(assertThisInitialized(_this), _this.update), UPDATE_REFRESH_INTERVAL);
  12098. return _this;
  12099. }
  12100. /**
  12101. * Create the DOM element for this class.
  12102. *
  12103. * @return {Element}
  12104. * The element that was created.
  12105. */
  12106. var _proto = MouseTimeDisplay.prototype;
  12107. _proto.createEl = function createEl() {
  12108. return _Component.prototype.createEl.call(this, 'div', {
  12109. className: 'vjs-mouse-display'
  12110. });
  12111. }
  12112. /**
  12113. * Enqueues updates to its own DOM as well as the DOM of its
  12114. * {@link TimeTooltip} child.
  12115. *
  12116. * @param {Object} seekBarRect
  12117. * The `ClientRect` for the {@link SeekBar} element.
  12118. *
  12119. * @param {number} seekBarPoint
  12120. * A number from 0 to 1, representing a horizontal reference point
  12121. * from the left edge of the {@link SeekBar}
  12122. */
  12123. ;
  12124. _proto.update = function update(seekBarRect, seekBarPoint) {
  12125. var _this2 = this;
  12126. var time = seekBarPoint * this.player_.duration();
  12127. this.getChild('timeTooltip').updateTime(seekBarRect, seekBarPoint, time, function () {
  12128. _this2.el_.style.left = seekBarRect.width * seekBarPoint + "px";
  12129. });
  12130. };
  12131. return MouseTimeDisplay;
  12132. }(Component$1);
  12133. /**
  12134. * Default options for `MouseTimeDisplay`
  12135. *
  12136. * @type {Object}
  12137. * @private
  12138. */
  12139. MouseTimeDisplay.prototype.options_ = {
  12140. children: ['timeTooltip']
  12141. };
  12142. Component$1.registerComponent('MouseTimeDisplay', MouseTimeDisplay);
  12143. var STEP_SECONDS = 5; // The multiplier of STEP_SECONDS that PgUp/PgDown move the timeline.
  12144. var PAGE_KEY_MULTIPLIER = 12;
  12145. /**
  12146. * Seek bar and container for the progress bars. Uses {@link PlayProgressBar}
  12147. * as its `bar`.
  12148. *
  12149. * @extends Slider
  12150. */
  12151. var SeekBar = /*#__PURE__*/function (_Slider) {
  12152. inheritsLoose(SeekBar, _Slider);
  12153. /**
  12154. * Creates an instance of this class.
  12155. *
  12156. * @param {Player} player
  12157. * The `Player` that this class should be attached to.
  12158. *
  12159. * @param {Object} [options]
  12160. * The key/value store of player options.
  12161. */
  12162. function SeekBar(player, options) {
  12163. var _this;
  12164. _this = _Slider.call(this, player, options) || this;
  12165. _this.setEventHandlers_();
  12166. return _this;
  12167. }
  12168. /**
  12169. * Sets the event handlers
  12170. *
  12171. * @private
  12172. */
  12173. var _proto = SeekBar.prototype;
  12174. _proto.setEventHandlers_ = function setEventHandlers_() {
  12175. var _this2 = this;
  12176. this.update_ = bind(this, this.update);
  12177. this.update = throttle(this.update_, UPDATE_REFRESH_INTERVAL);
  12178. this.on(this.player_, ['ended', 'durationchange', 'timeupdate'], this.update);
  12179. if (this.player_.liveTracker) {
  12180. this.on(this.player_.liveTracker, 'liveedgechange', this.update);
  12181. } // when playing, let's ensure we smoothly update the play progress bar
  12182. // via an interval
  12183. this.updateInterval = null;
  12184. this.enableIntervalHandler_ = function (e) {
  12185. return _this2.enableInterval_(e);
  12186. };
  12187. this.disableIntervalHandler_ = function (e) {
  12188. return _this2.disableInterval_(e);
  12189. };
  12190. this.on(this.player_, ['playing'], this.enableIntervalHandler_);
  12191. this.on(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_); // we don't need to update the play progress if the document is hidden,
  12192. // also, this causes the CPU to spike and eventually crash the page on IE11.
  12193. if ('hidden' in document && 'visibilityState' in document) {
  12194. this.on(document, 'visibilitychange', this.toggleVisibility_);
  12195. }
  12196. };
  12197. _proto.toggleVisibility_ = function toggleVisibility_(e) {
  12198. if (document.visibilityState === 'hidden') {
  12199. this.cancelNamedAnimationFrame('SeekBar#update');
  12200. this.cancelNamedAnimationFrame('Slider#update');
  12201. this.disableInterval_(e);
  12202. } else {
  12203. if (!this.player_.ended() && !this.player_.paused()) {
  12204. this.enableInterval_();
  12205. } // we just switched back to the page and someone may be looking, so, update ASAP
  12206. this.update();
  12207. }
  12208. };
  12209. _proto.enableInterval_ = function enableInterval_() {
  12210. if (this.updateInterval) {
  12211. return;
  12212. }
  12213. this.updateInterval = this.setInterval(this.update, UPDATE_REFRESH_INTERVAL);
  12214. };
  12215. _proto.disableInterval_ = function disableInterval_(e) {
  12216. if (this.player_.liveTracker && this.player_.liveTracker.isLive() && e && e.type !== 'ended') {
  12217. return;
  12218. }
  12219. if (!this.updateInterval) {
  12220. return;
  12221. }
  12222. this.clearInterval(this.updateInterval);
  12223. this.updateInterval = null;
  12224. }
  12225. /**
  12226. * Create the `Component`'s DOM element
  12227. *
  12228. * @return {Element}
  12229. * The element that was created.
  12230. */
  12231. ;
  12232. _proto.createEl = function createEl() {
  12233. return _Slider.prototype.createEl.call(this, 'div', {
  12234. className: 'vjs-progress-holder'
  12235. }, {
  12236. 'aria-label': this.localize('Progress Bar')
  12237. });
  12238. }
  12239. /**
  12240. * This function updates the play progress bar and accessibility
  12241. * attributes to whatever is passed in.
  12242. *
  12243. * @param {EventTarget~Event} [event]
  12244. * The `timeupdate` or `ended` event that caused this to run.
  12245. *
  12246. * @listens Player#timeupdate
  12247. *
  12248. * @return {number}
  12249. * The current percent at a number from 0-1
  12250. */
  12251. ;
  12252. _proto.update = function update(event) {
  12253. var _this3 = this;
  12254. // ignore updates while the tab is hidden
  12255. if (document.visibilityState === 'hidden') {
  12256. return;
  12257. }
  12258. var percent = _Slider.prototype.update.call(this);
  12259. this.requestNamedAnimationFrame('SeekBar#update', function () {
  12260. var currentTime = _this3.player_.ended() ? _this3.player_.duration() : _this3.getCurrentTime_();
  12261. var liveTracker = _this3.player_.liveTracker;
  12262. var duration = _this3.player_.duration();
  12263. if (liveTracker && liveTracker.isLive()) {
  12264. duration = _this3.player_.liveTracker.liveCurrentTime();
  12265. }
  12266. if (_this3.percent_ !== percent) {
  12267. // machine readable value of progress bar (percentage complete)
  12268. _this3.el_.setAttribute('aria-valuenow', (percent * 100).toFixed(2));
  12269. _this3.percent_ = percent;
  12270. }
  12271. if (_this3.currentTime_ !== currentTime || _this3.duration_ !== duration) {
  12272. // human readable value of progress bar (time complete)
  12273. _this3.el_.setAttribute('aria-valuetext', _this3.localize('progress bar timing: currentTime={1} duration={2}', [formatTime(currentTime, duration), formatTime(duration, duration)], '{1} of {2}'));
  12274. _this3.currentTime_ = currentTime;
  12275. _this3.duration_ = duration;
  12276. } // update the progress bar time tooltip with the current time
  12277. if (_this3.bar) {
  12278. _this3.bar.update(getBoundingClientRect(_this3.el()), _this3.getProgress());
  12279. }
  12280. });
  12281. return percent;
  12282. }
  12283. /**
  12284. * Prevent liveThreshold from causing seeks to seem like they
  12285. * are not happening from a user perspective.
  12286. *
  12287. * @param {number} ct
  12288. * current time to seek to
  12289. */
  12290. ;
  12291. _proto.userSeek_ = function userSeek_(ct) {
  12292. if (this.player_.liveTracker && this.player_.liveTracker.isLive()) {
  12293. this.player_.liveTracker.nextSeekedFromUser();
  12294. }
  12295. this.player_.currentTime(ct);
  12296. }
  12297. /**
  12298. * Get the value of current time but allows for smooth scrubbing,
  12299. * when player can't keep up.
  12300. *
  12301. * @return {number}
  12302. * The current time value to display
  12303. *
  12304. * @private
  12305. */
  12306. ;
  12307. _proto.getCurrentTime_ = function getCurrentTime_() {
  12308. return this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
  12309. }
  12310. /**
  12311. * Get the percentage of media played so far.
  12312. *
  12313. * @return {number}
  12314. * The percentage of media played so far (0 to 1).
  12315. */
  12316. ;
  12317. _proto.getPercent = function getPercent() {
  12318. var currentTime = this.getCurrentTime_();
  12319. var percent;
  12320. var liveTracker = this.player_.liveTracker;
  12321. if (liveTracker && liveTracker.isLive()) {
  12322. percent = (currentTime - liveTracker.seekableStart()) / liveTracker.liveWindow(); // prevent the percent from changing at the live edge
  12323. if (liveTracker.atLiveEdge()) {
  12324. percent = 1;
  12325. }
  12326. } else {
  12327. percent = currentTime / this.player_.duration();
  12328. }
  12329. return percent;
  12330. }
  12331. /**
  12332. * Handle mouse down on seek bar
  12333. *
  12334. * @param {EventTarget~Event} event
  12335. * The `mousedown` event that caused this to run.
  12336. *
  12337. * @listens mousedown
  12338. */
  12339. ;
  12340. _proto.handleMouseDown = function handleMouseDown(event) {
  12341. if (!isSingleLeftClick(event)) {
  12342. return;
  12343. } // Stop event propagation to prevent double fire in progress-control.js
  12344. event.stopPropagation();
  12345. this.videoWasPlaying = !this.player_.paused();
  12346. this.player_.pause();
  12347. _Slider.prototype.handleMouseDown.call(this, event);
  12348. }
  12349. /**
  12350. * Handle mouse move on seek bar
  12351. *
  12352. * @param {EventTarget~Event} event
  12353. * The `mousemove` event that caused this to run.
  12354. * @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
  12355. *
  12356. * @listens mousemove
  12357. */
  12358. ;
  12359. _proto.handleMouseMove = function handleMouseMove(event, mouseDown) {
  12360. if (mouseDown === void 0) {
  12361. mouseDown = false;
  12362. }
  12363. if (!isSingleLeftClick(event)) {
  12364. return;
  12365. }
  12366. if (!mouseDown && !this.player_.scrubbing()) {
  12367. this.player_.scrubbing(true);
  12368. }
  12369. var newTime;
  12370. var distance = this.calculateDistance(event);
  12371. var liveTracker = this.player_.liveTracker;
  12372. if (!liveTracker || !liveTracker.isLive()) {
  12373. newTime = distance * this.player_.duration(); // Don't let video end while scrubbing.
  12374. if (newTime === this.player_.duration()) {
  12375. newTime = newTime - 0.1;
  12376. }
  12377. } else {
  12378. if (distance >= 0.99) {
  12379. liveTracker.seekToLiveEdge();
  12380. return;
  12381. }
  12382. var seekableStart = liveTracker.seekableStart();
  12383. var seekableEnd = liveTracker.liveCurrentTime();
  12384. newTime = seekableStart + distance * liveTracker.liveWindow(); // Don't let video end while scrubbing.
  12385. if (newTime >= seekableEnd) {
  12386. newTime = seekableEnd;
  12387. } // Compensate for precision differences so that currentTime is not less
  12388. // than seekable start
  12389. if (newTime <= seekableStart) {
  12390. newTime = seekableStart + 0.1;
  12391. } // On android seekableEnd can be Infinity sometimes,
  12392. // this will cause newTime to be Infinity, which is
  12393. // not a valid currentTime.
  12394. if (newTime === Infinity) {
  12395. return;
  12396. }
  12397. } // Set new time (tell player to seek to new time)
  12398. this.userSeek_(newTime);
  12399. };
  12400. _proto.enable = function enable() {
  12401. _Slider.prototype.enable.call(this);
  12402. var mouseTimeDisplay = this.getChild('mouseTimeDisplay');
  12403. if (!mouseTimeDisplay) {
  12404. return;
  12405. }
  12406. mouseTimeDisplay.show();
  12407. };
  12408. _proto.disable = function disable() {
  12409. _Slider.prototype.disable.call(this);
  12410. var mouseTimeDisplay = this.getChild('mouseTimeDisplay');
  12411. if (!mouseTimeDisplay) {
  12412. return;
  12413. }
  12414. mouseTimeDisplay.hide();
  12415. }
  12416. /**
  12417. * Handle mouse up on seek bar
  12418. *
  12419. * @param {EventTarget~Event} event
  12420. * The `mouseup` event that caused this to run.
  12421. *
  12422. * @listens mouseup
  12423. */
  12424. ;
  12425. _proto.handleMouseUp = function handleMouseUp(event) {
  12426. _Slider.prototype.handleMouseUp.call(this, event); // Stop event propagation to prevent double fire in progress-control.js
  12427. if (event) {
  12428. event.stopPropagation();
  12429. }
  12430. this.player_.scrubbing(false);
  12431. /**
  12432. * Trigger timeupdate because we're done seeking and the time has changed.
  12433. * This is particularly useful for if the player is paused to time the time displays.
  12434. *
  12435. * @event Tech#timeupdate
  12436. * @type {EventTarget~Event}
  12437. */
  12438. this.player_.trigger({
  12439. type: 'timeupdate',
  12440. target: this,
  12441. manuallyTriggered: true
  12442. });
  12443. if (this.videoWasPlaying) {
  12444. silencePromise(this.player_.play());
  12445. } else {
  12446. // We're done seeking and the time has changed.
  12447. // If the player is paused, make sure we display the correct time on the seek bar.
  12448. this.update_();
  12449. }
  12450. }
  12451. /**
  12452. * Move more quickly fast forward for keyboard-only users
  12453. */
  12454. ;
  12455. _proto.stepForward = function stepForward() {
  12456. this.userSeek_(this.player_.currentTime() + STEP_SECONDS);
  12457. }
  12458. /**
  12459. * Move more quickly rewind for keyboard-only users
  12460. */
  12461. ;
  12462. _proto.stepBack = function stepBack() {
  12463. this.userSeek_(this.player_.currentTime() - STEP_SECONDS);
  12464. }
  12465. /**
  12466. * Toggles the playback state of the player
  12467. * This gets called when enter or space is used on the seekbar
  12468. *
  12469. * @param {EventTarget~Event} event
  12470. * The `keydown` event that caused this function to be called
  12471. *
  12472. */
  12473. ;
  12474. _proto.handleAction = function handleAction(event) {
  12475. if (this.player_.paused()) {
  12476. this.player_.play();
  12477. } else {
  12478. this.player_.pause();
  12479. }
  12480. }
  12481. /**
  12482. * Called when this SeekBar has focus and a key gets pressed down.
  12483. * Supports the following keys:
  12484. *
  12485. * Space or Enter key fire a click event
  12486. * Home key moves to start of the timeline
  12487. * End key moves to end of the timeline
  12488. * Digit "0" through "9" keys move to 0%, 10% ... 80%, 90% of the timeline
  12489. * PageDown key moves back a larger step than ArrowDown
  12490. * PageUp key moves forward a large step
  12491. *
  12492. * @param {EventTarget~Event} event
  12493. * The `keydown` event that caused this function to be called.
  12494. *
  12495. * @listens keydown
  12496. */
  12497. ;
  12498. _proto.handleKeyDown = function handleKeyDown(event) {
  12499. var liveTracker = this.player_.liveTracker;
  12500. if (keycode.isEventKey(event, 'Space') || keycode.isEventKey(event, 'Enter')) {
  12501. event.preventDefault();
  12502. event.stopPropagation();
  12503. this.handleAction(event);
  12504. } else if (keycode.isEventKey(event, 'Home')) {
  12505. event.preventDefault();
  12506. event.stopPropagation();
  12507. this.userSeek_(0);
  12508. } else if (keycode.isEventKey(event, 'End')) {
  12509. event.preventDefault();
  12510. event.stopPropagation();
  12511. if (liveTracker && liveTracker.isLive()) {
  12512. this.userSeek_(liveTracker.liveCurrentTime());
  12513. } else {
  12514. this.userSeek_(this.player_.duration());
  12515. }
  12516. } else if (/^[0-9]$/.test(keycode(event))) {
  12517. event.preventDefault();
  12518. event.stopPropagation();
  12519. var gotoFraction = (keycode.codes[keycode(event)] - keycode.codes['0']) * 10.0 / 100.0;
  12520. if (liveTracker && liveTracker.isLive()) {
  12521. this.userSeek_(liveTracker.seekableStart() + liveTracker.liveWindow() * gotoFraction);
  12522. } else {
  12523. this.userSeek_(this.player_.duration() * gotoFraction);
  12524. }
  12525. } else if (keycode.isEventKey(event, 'PgDn')) {
  12526. event.preventDefault();
  12527. event.stopPropagation();
  12528. this.userSeek_(this.player_.currentTime() - STEP_SECONDS * PAGE_KEY_MULTIPLIER);
  12529. } else if (keycode.isEventKey(event, 'PgUp')) {
  12530. event.preventDefault();
  12531. event.stopPropagation();
  12532. this.userSeek_(this.player_.currentTime() + STEP_SECONDS * PAGE_KEY_MULTIPLIER);
  12533. } else {
  12534. // Pass keydown handling up for unsupported keys
  12535. _Slider.prototype.handleKeyDown.call(this, event);
  12536. }
  12537. };
  12538. _proto.dispose = function dispose() {
  12539. this.disableInterval_();
  12540. this.off(this.player_, ['ended', 'durationchange', 'timeupdate'], this.update);
  12541. if (this.player_.liveTracker) {
  12542. this.off(this.player_.liveTracker, 'liveedgechange', this.update);
  12543. }
  12544. this.off(this.player_, ['playing'], this.enableIntervalHandler_);
  12545. this.off(this.player_, ['ended', 'pause', 'waiting'], this.disableIntervalHandler_); // we don't need to update the play progress if the document is hidden,
  12546. // also, this causes the CPU to spike and eventually crash the page on IE11.
  12547. if ('hidden' in document && 'visibilityState' in document) {
  12548. this.off(document, 'visibilitychange', this.toggleVisibility_);
  12549. }
  12550. _Slider.prototype.dispose.call(this);
  12551. };
  12552. return SeekBar;
  12553. }(Slider);
  12554. /**
  12555. * Default options for the `SeekBar`
  12556. *
  12557. * @type {Object}
  12558. * @private
  12559. */
  12560. SeekBar.prototype.options_ = {
  12561. children: ['loadProgressBar', 'playProgressBar'],
  12562. barName: 'playProgressBar'
  12563. }; // MouseTimeDisplay tooltips should not be added to a player on mobile devices
  12564. if (!IS_IOS && !IS_ANDROID) {
  12565. SeekBar.prototype.options_.children.splice(1, 0, 'mouseTimeDisplay');
  12566. }
  12567. Component$1.registerComponent('SeekBar', SeekBar);
  12568. /**
  12569. * The Progress Control component contains the seek bar, load progress,
  12570. * and play progress.
  12571. *
  12572. * @extends Component
  12573. */
  12574. var ProgressControl = /*#__PURE__*/function (_Component) {
  12575. inheritsLoose(ProgressControl, _Component);
  12576. /**
  12577. * Creates an instance of this class.
  12578. *
  12579. * @param {Player} player
  12580. * The `Player` that this class should be attached to.
  12581. *
  12582. * @param {Object} [options]
  12583. * The key/value store of player options.
  12584. */
  12585. function ProgressControl(player, options) {
  12586. var _this;
  12587. _this = _Component.call(this, player, options) || this;
  12588. _this.handleMouseMove = throttle(bind(assertThisInitialized(_this), _this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
  12589. _this.throttledHandleMouseSeek = throttle(bind(assertThisInitialized(_this), _this.handleMouseSeek), UPDATE_REFRESH_INTERVAL);
  12590. _this.handleMouseUpHandler_ = function (e) {
  12591. return _this.handleMouseUp(e);
  12592. };
  12593. _this.handleMouseDownHandler_ = function (e) {
  12594. return _this.handleMouseDown(e);
  12595. };
  12596. _this.enable();
  12597. return _this;
  12598. }
  12599. /**
  12600. * Create the `Component`'s DOM element
  12601. *
  12602. * @return {Element}
  12603. * The element that was created.
  12604. */
  12605. var _proto = ProgressControl.prototype;
  12606. _proto.createEl = function createEl() {
  12607. return _Component.prototype.createEl.call(this, 'div', {
  12608. className: 'vjs-progress-control vjs-control'
  12609. });
  12610. }
  12611. /**
  12612. * When the mouse moves over the `ProgressControl`, the pointer position
  12613. * gets passed down to the `MouseTimeDisplay` component.
  12614. *
  12615. * @param {EventTarget~Event} event
  12616. * The `mousemove` event that caused this function to run.
  12617. *
  12618. * @listen mousemove
  12619. */
  12620. ;
  12621. _proto.handleMouseMove = function handleMouseMove(event) {
  12622. var seekBar = this.getChild('seekBar');
  12623. if (!seekBar) {
  12624. return;
  12625. }
  12626. var playProgressBar = seekBar.getChild('playProgressBar');
  12627. var mouseTimeDisplay = seekBar.getChild('mouseTimeDisplay');
  12628. if (!playProgressBar && !mouseTimeDisplay) {
  12629. return;
  12630. }
  12631. var seekBarEl = seekBar.el();
  12632. var seekBarRect = findPosition(seekBarEl);
  12633. var seekBarPoint = getPointerPosition(seekBarEl, event).x; // The default skin has a gap on either side of the `SeekBar`. This means
  12634. // that it's possible to trigger this behavior outside the boundaries of
  12635. // the `SeekBar`. This ensures we stay within it at all times.
  12636. seekBarPoint = clamp(seekBarPoint, 0, 1);
  12637. if (mouseTimeDisplay) {
  12638. mouseTimeDisplay.update(seekBarRect, seekBarPoint);
  12639. }
  12640. if (playProgressBar) {
  12641. playProgressBar.update(seekBarRect, seekBar.getProgress());
  12642. }
  12643. }
  12644. /**
  12645. * A throttled version of the {@link ProgressControl#handleMouseSeek} listener.
  12646. *
  12647. * @method ProgressControl#throttledHandleMouseSeek
  12648. * @param {EventTarget~Event} event
  12649. * The `mousemove` event that caused this function to run.
  12650. *
  12651. * @listen mousemove
  12652. * @listen touchmove
  12653. */
  12654. /**
  12655. * Handle `mousemove` or `touchmove` events on the `ProgressControl`.
  12656. *
  12657. * @param {EventTarget~Event} event
  12658. * `mousedown` or `touchstart` event that triggered this function
  12659. *
  12660. * @listens mousemove
  12661. * @listens touchmove
  12662. */
  12663. ;
  12664. _proto.handleMouseSeek = function handleMouseSeek(event) {
  12665. var seekBar = this.getChild('seekBar');
  12666. if (seekBar) {
  12667. seekBar.handleMouseMove(event);
  12668. }
  12669. }
  12670. /**
  12671. * Are controls are currently enabled for this progress control.
  12672. *
  12673. * @return {boolean}
  12674. * true if controls are enabled, false otherwise
  12675. */
  12676. ;
  12677. _proto.enabled = function enabled() {
  12678. return this.enabled_;
  12679. }
  12680. /**
  12681. * Disable all controls on the progress control and its children
  12682. */
  12683. ;
  12684. _proto.disable = function disable() {
  12685. this.children().forEach(function (child) {
  12686. return child.disable && child.disable();
  12687. });
  12688. if (!this.enabled()) {
  12689. return;
  12690. }
  12691. this.off(['mousedown', 'touchstart'], this.handleMouseDownHandler_);
  12692. this.off(this.el_, 'mousemove', this.handleMouseMove);
  12693. this.removeListenersAddedOnMousedownAndTouchstart();
  12694. this.addClass('disabled');
  12695. this.enabled_ = false; // Restore normal playback state if controls are disabled while scrubbing
  12696. if (this.player_.scrubbing()) {
  12697. var seekBar = this.getChild('seekBar');
  12698. this.player_.scrubbing(false);
  12699. if (seekBar.videoWasPlaying) {
  12700. silencePromise(this.player_.play());
  12701. }
  12702. }
  12703. }
  12704. /**
  12705. * Enable all controls on the progress control and its children
  12706. */
  12707. ;
  12708. _proto.enable = function enable() {
  12709. this.children().forEach(function (child) {
  12710. return child.enable && child.enable();
  12711. });
  12712. if (this.enabled()) {
  12713. return;
  12714. }
  12715. this.on(['mousedown', 'touchstart'], this.handleMouseDownHandler_);
  12716. this.on(this.el_, 'mousemove', this.handleMouseMove);
  12717. this.removeClass('disabled');
  12718. this.enabled_ = true;
  12719. }
  12720. /**
  12721. * Cleanup listeners after the user finishes interacting with the progress controls
  12722. */
  12723. ;
  12724. _proto.removeListenersAddedOnMousedownAndTouchstart = function removeListenersAddedOnMousedownAndTouchstart() {
  12725. var doc = this.el_.ownerDocument;
  12726. this.off(doc, 'mousemove', this.throttledHandleMouseSeek);
  12727. this.off(doc, 'touchmove', this.throttledHandleMouseSeek);
  12728. this.off(doc, 'mouseup', this.handleMouseUpHandler_);
  12729. this.off(doc, 'touchend', this.handleMouseUpHandler_);
  12730. }
  12731. /**
  12732. * Handle `mousedown` or `touchstart` events on the `ProgressControl`.
  12733. *
  12734. * @param {EventTarget~Event} event
  12735. * `mousedown` or `touchstart` event that triggered this function
  12736. *
  12737. * @listens mousedown
  12738. * @listens touchstart
  12739. */
  12740. ;
  12741. _proto.handleMouseDown = function handleMouseDown(event) {
  12742. var doc = this.el_.ownerDocument;
  12743. var seekBar = this.getChild('seekBar');
  12744. if (seekBar) {
  12745. seekBar.handleMouseDown(event);
  12746. }
  12747. this.on(doc, 'mousemove', this.throttledHandleMouseSeek);
  12748. this.on(doc, 'touchmove', this.throttledHandleMouseSeek);
  12749. this.on(doc, 'mouseup', this.handleMouseUpHandler_);
  12750. this.on(doc, 'touchend', this.handleMouseUpHandler_);
  12751. }
  12752. /**
  12753. * Handle `mouseup` or `touchend` events on the `ProgressControl`.
  12754. *
  12755. * @param {EventTarget~Event} event
  12756. * `mouseup` or `touchend` event that triggered this function.
  12757. *
  12758. * @listens touchend
  12759. * @listens mouseup
  12760. */
  12761. ;
  12762. _proto.handleMouseUp = function handleMouseUp(event) {
  12763. var seekBar = this.getChild('seekBar');
  12764. if (seekBar) {
  12765. seekBar.handleMouseUp(event);
  12766. }
  12767. this.removeListenersAddedOnMousedownAndTouchstart();
  12768. };
  12769. return ProgressControl;
  12770. }(Component$1);
  12771. /**
  12772. * Default options for `ProgressControl`
  12773. *
  12774. * @type {Object}
  12775. * @private
  12776. */
  12777. ProgressControl.prototype.options_ = {
  12778. children: ['seekBar']
  12779. };
  12780. Component$1.registerComponent('ProgressControl', ProgressControl);
  12781. /**
  12782. * Toggle Picture-in-Picture mode
  12783. *
  12784. * @extends Button
  12785. */
  12786. var PictureInPictureToggle = /*#__PURE__*/function (_Button) {
  12787. inheritsLoose(PictureInPictureToggle, _Button);
  12788. /**
  12789. * Creates an instance of this class.
  12790. *
  12791. * @param {Player} player
  12792. * The `Player` that this class should be attached to.
  12793. *
  12794. * @param {Object} [options]
  12795. * The key/value store of player options.
  12796. *
  12797. * @listens Player#enterpictureinpicture
  12798. * @listens Player#leavepictureinpicture
  12799. */
  12800. function PictureInPictureToggle(player, options) {
  12801. var _this;
  12802. _this = _Button.call(this, player, options) || this;
  12803. _this.on(player, ['enterpictureinpicture', 'leavepictureinpicture'], function (e) {
  12804. return _this.handlePictureInPictureChange(e);
  12805. });
  12806. _this.on(player, ['disablepictureinpicturechanged', 'loadedmetadata'], function (e) {
  12807. return _this.handlePictureInPictureEnabledChange(e);
  12808. });
  12809. _this.on(player, ['loadedmetadata', 'audioonlymodechange', 'audiopostermodechange'], function () {
  12810. // This audio detection will not detect HLS or DASH audio-only streams because there was no reliable way to detect them at the time
  12811. var isSourceAudio = player.currentType().substring(0, 5) === 'audio';
  12812. if (isSourceAudio || player.audioPosterMode() || player.audioOnlyMode()) {
  12813. if (player.isInPictureInPicture()) {
  12814. player.exitPictureInPicture();
  12815. }
  12816. _this.hide();
  12817. } else {
  12818. _this.show();
  12819. }
  12820. }); // TODO: Deactivate button on player emptied event.
  12821. _this.disable();
  12822. return _this;
  12823. }
  12824. /**
  12825. * Builds the default DOM `className`.
  12826. *
  12827. * @return {string}
  12828. * The DOM `className` for this object.
  12829. */
  12830. var _proto = PictureInPictureToggle.prototype;
  12831. _proto.buildCSSClass = function buildCSSClass() {
  12832. return "vjs-picture-in-picture-control " + _Button.prototype.buildCSSClass.call(this);
  12833. }
  12834. /**
  12835. * Enables or disables button based on document.pictureInPictureEnabled property value
  12836. * or on value returned by player.disablePictureInPicture() method.
  12837. */
  12838. ;
  12839. _proto.handlePictureInPictureEnabledChange = function handlePictureInPictureEnabledChange() {
  12840. if (document.pictureInPictureEnabled && this.player_.disablePictureInPicture() === false) {
  12841. this.enable();
  12842. } else {
  12843. this.disable();
  12844. }
  12845. }
  12846. /**
  12847. * Handles enterpictureinpicture and leavepictureinpicture on the player and change control text accordingly.
  12848. *
  12849. * @param {EventTarget~Event} [event]
  12850. * The {@link Player#enterpictureinpicture} or {@link Player#leavepictureinpicture} event that caused this function to be
  12851. * called.
  12852. *
  12853. * @listens Player#enterpictureinpicture
  12854. * @listens Player#leavepictureinpicture
  12855. */
  12856. ;
  12857. _proto.handlePictureInPictureChange = function handlePictureInPictureChange(event) {
  12858. if (this.player_.isInPictureInPicture()) {
  12859. this.controlText('Exit Picture-in-Picture');
  12860. } else {
  12861. this.controlText('Picture-in-Picture');
  12862. }
  12863. this.handlePictureInPictureEnabledChange();
  12864. }
  12865. /**
  12866. * This gets called when an `PictureInPictureToggle` is "clicked". See
  12867. * {@link ClickableComponent} for more detailed information on what a click can be.
  12868. *
  12869. * @param {EventTarget~Event} [event]
  12870. * The `keydown`, `tap`, or `click` event that caused this function to be
  12871. * called.
  12872. *
  12873. * @listens tap
  12874. * @listens click
  12875. */
  12876. ;
  12877. _proto.handleClick = function handleClick(event) {
  12878. if (!this.player_.isInPictureInPicture()) {
  12879. this.player_.requestPictureInPicture();
  12880. } else {
  12881. this.player_.exitPictureInPicture();
  12882. }
  12883. };
  12884. return PictureInPictureToggle;
  12885. }(Button);
  12886. /**
  12887. * The text that should display over the `PictureInPictureToggle`s controls. Added for localization.
  12888. *
  12889. * @type {string}
  12890. * @private
  12891. */
  12892. PictureInPictureToggle.prototype.controlText_ = 'Picture-in-Picture';
  12893. Component$1.registerComponent('PictureInPictureToggle', PictureInPictureToggle);
  12894. /**
  12895. * Toggle fullscreen video
  12896. *
  12897. * @extends Button
  12898. */
  12899. var FullscreenToggle = /*#__PURE__*/function (_Button) {
  12900. inheritsLoose(FullscreenToggle, _Button);
  12901. /**
  12902. * Creates an instance of this class.
  12903. *
  12904. * @param {Player} player
  12905. * The `Player` that this class should be attached to.
  12906. *
  12907. * @param {Object} [options]
  12908. * The key/value store of player options.
  12909. */
  12910. function FullscreenToggle(player, options) {
  12911. var _this;
  12912. _this = _Button.call(this, player, options) || this;
  12913. _this.on(player, 'fullscreenchange', function (e) {
  12914. return _this.handleFullscreenChange(e);
  12915. });
  12916. if (document[player.fsApi_.fullscreenEnabled] === false) {
  12917. _this.disable();
  12918. }
  12919. return _this;
  12920. }
  12921. /**
  12922. * Builds the default DOM `className`.
  12923. *
  12924. * @return {string}
  12925. * The DOM `className` for this object.
  12926. */
  12927. var _proto = FullscreenToggle.prototype;
  12928. _proto.buildCSSClass = function buildCSSClass() {
  12929. return "vjs-fullscreen-control " + _Button.prototype.buildCSSClass.call(this);
  12930. }
  12931. /**
  12932. * Handles fullscreenchange on the player and change control text accordingly.
  12933. *
  12934. * @param {EventTarget~Event} [event]
  12935. * The {@link Player#fullscreenchange} event that caused this function to be
  12936. * called.
  12937. *
  12938. * @listens Player#fullscreenchange
  12939. */
  12940. ;
  12941. _proto.handleFullscreenChange = function handleFullscreenChange(event) {
  12942. if (this.player_.isFullscreen()) {
  12943. this.controlText('Non-Fullscreen');
  12944. } else {
  12945. this.controlText('Fullscreen');
  12946. }
  12947. }
  12948. /**
  12949. * This gets called when an `FullscreenToggle` is "clicked". See
  12950. * {@link ClickableComponent} for more detailed information on what a click can be.
  12951. *
  12952. * @param {EventTarget~Event} [event]
  12953. * The `keydown`, `tap`, or `click` event that caused this function to be
  12954. * called.
  12955. *
  12956. * @listens tap
  12957. * @listens click
  12958. */
  12959. ;
  12960. _proto.handleClick = function handleClick(event) {
  12961. if (!this.player_.isFullscreen()) {
  12962. this.player_.requestFullscreen();
  12963. } else {
  12964. this.player_.exitFullscreen();
  12965. }
  12966. };
  12967. return FullscreenToggle;
  12968. }(Button);
  12969. /**
  12970. * The text that should display over the `FullscreenToggle`s controls. Added for localization.
  12971. *
  12972. * @type {string}
  12973. * @private
  12974. */
  12975. FullscreenToggle.prototype.controlText_ = 'Fullscreen';
  12976. Component$1.registerComponent('FullscreenToggle', FullscreenToggle);
  12977. /**
  12978. * Check if volume control is supported and if it isn't hide the
  12979. * `Component` that was passed using the `vjs-hidden` class.
  12980. *
  12981. * @param {Component} self
  12982. * The component that should be hidden if volume is unsupported
  12983. *
  12984. * @param {Player} player
  12985. * A reference to the player
  12986. *
  12987. * @private
  12988. */
  12989. var checkVolumeSupport = function checkVolumeSupport(self, player) {
  12990. // hide volume controls when they're not supported by the current tech
  12991. if (player.tech_ && !player.tech_.featuresVolumeControl) {
  12992. self.addClass('vjs-hidden');
  12993. }
  12994. self.on(player, 'loadstart', function () {
  12995. if (!player.tech_.featuresVolumeControl) {
  12996. self.addClass('vjs-hidden');
  12997. } else {
  12998. self.removeClass('vjs-hidden');
  12999. }
  13000. });
  13001. };
  13002. /**
  13003. * Shows volume level
  13004. *
  13005. * @extends Component
  13006. */
  13007. var VolumeLevel = /*#__PURE__*/function (_Component) {
  13008. inheritsLoose(VolumeLevel, _Component);
  13009. function VolumeLevel() {
  13010. return _Component.apply(this, arguments) || this;
  13011. }
  13012. var _proto = VolumeLevel.prototype;
  13013. /**
  13014. * Create the `Component`'s DOM element
  13015. *
  13016. * @return {Element}
  13017. * The element that was created.
  13018. */
  13019. _proto.createEl = function createEl() {
  13020. var el = _Component.prototype.createEl.call(this, 'div', {
  13021. className: 'vjs-volume-level'
  13022. });
  13023. el.appendChild(_Component.prototype.createEl.call(this, 'span', {
  13024. className: 'vjs-control-text'
  13025. }));
  13026. return el;
  13027. };
  13028. return VolumeLevel;
  13029. }(Component$1);
  13030. Component$1.registerComponent('VolumeLevel', VolumeLevel);
  13031. /**
  13032. * Volume level tooltips display a volume above or side by side the volume bar.
  13033. *
  13034. * @extends Component
  13035. */
  13036. var VolumeLevelTooltip = /*#__PURE__*/function (_Component) {
  13037. inheritsLoose(VolumeLevelTooltip, _Component);
  13038. /**
  13039. * Creates an instance of this class.
  13040. *
  13041. * @param {Player} player
  13042. * The {@link Player} that this class should be attached to.
  13043. *
  13044. * @param {Object} [options]
  13045. * The key/value store of player options.
  13046. */
  13047. function VolumeLevelTooltip(player, options) {
  13048. var _this;
  13049. _this = _Component.call(this, player, options) || this;
  13050. _this.update = throttle(bind(assertThisInitialized(_this), _this.update), UPDATE_REFRESH_INTERVAL);
  13051. return _this;
  13052. }
  13053. /**
  13054. * Create the volume tooltip DOM element
  13055. *
  13056. * @return {Element}
  13057. * The element that was created.
  13058. */
  13059. var _proto = VolumeLevelTooltip.prototype;
  13060. _proto.createEl = function createEl() {
  13061. return _Component.prototype.createEl.call(this, 'div', {
  13062. className: 'vjs-volume-tooltip'
  13063. }, {
  13064. 'aria-hidden': 'true'
  13065. });
  13066. }
  13067. /**
  13068. * Updates the position of the tooltip relative to the `VolumeBar` and
  13069. * its content text.
  13070. *
  13071. * @param {Object} rangeBarRect
  13072. * The `ClientRect` for the {@link VolumeBar} element.
  13073. *
  13074. * @param {number} rangeBarPoint
  13075. * A number from 0 to 1, representing a horizontal/vertical reference point
  13076. * from the left edge of the {@link VolumeBar}
  13077. *
  13078. * @param {boolean} vertical
  13079. * Referees to the Volume control position
  13080. * in the control bar{@link VolumeControl}
  13081. *
  13082. */
  13083. ;
  13084. _proto.update = function update(rangeBarRect, rangeBarPoint, vertical, content) {
  13085. if (!vertical) {
  13086. var tooltipRect = getBoundingClientRect(this.el_);
  13087. var playerRect = getBoundingClientRect(this.player_.el());
  13088. var volumeBarPointPx = rangeBarRect.width * rangeBarPoint;
  13089. if (!playerRect || !tooltipRect) {
  13090. return;
  13091. }
  13092. var spaceLeftOfPoint = rangeBarRect.left - playerRect.left + volumeBarPointPx;
  13093. var spaceRightOfPoint = rangeBarRect.width - volumeBarPointPx + (playerRect.right - rangeBarRect.right);
  13094. var pullTooltipBy = tooltipRect.width / 2;
  13095. if (spaceLeftOfPoint < pullTooltipBy) {
  13096. pullTooltipBy += pullTooltipBy - spaceLeftOfPoint;
  13097. } else if (spaceRightOfPoint < pullTooltipBy) {
  13098. pullTooltipBy = spaceRightOfPoint;
  13099. }
  13100. if (pullTooltipBy < 0) {
  13101. pullTooltipBy = 0;
  13102. } else if (pullTooltipBy > tooltipRect.width) {
  13103. pullTooltipBy = tooltipRect.width;
  13104. }
  13105. this.el_.style.right = "-" + pullTooltipBy + "px";
  13106. }
  13107. this.write(content + "%");
  13108. }
  13109. /**
  13110. * Write the volume to the tooltip DOM element.
  13111. *
  13112. * @param {string} content
  13113. * The formatted volume for the tooltip.
  13114. */
  13115. ;
  13116. _proto.write = function write(content) {
  13117. textContent(this.el_, content);
  13118. }
  13119. /**
  13120. * Updates the position of the volume tooltip relative to the `VolumeBar`.
  13121. *
  13122. * @param {Object} rangeBarRect
  13123. * The `ClientRect` for the {@link VolumeBar} element.
  13124. *
  13125. * @param {number} rangeBarPoint
  13126. * A number from 0 to 1, representing a horizontal/vertical reference point
  13127. * from the left edge of the {@link VolumeBar}
  13128. *
  13129. * @param {boolean} vertical
  13130. * Referees to the Volume control position
  13131. * in the control bar{@link VolumeControl}
  13132. *
  13133. * @param {number} volume
  13134. * The volume level to update the tooltip to
  13135. *
  13136. * @param {Function} cb
  13137. * A function that will be called during the request animation frame
  13138. * for tooltips that need to do additional animations from the default
  13139. */
  13140. ;
  13141. _proto.updateVolume = function updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, cb) {
  13142. var _this2 = this;
  13143. this.requestNamedAnimationFrame('VolumeLevelTooltip#updateVolume', function () {
  13144. _this2.update(rangeBarRect, rangeBarPoint, vertical, volume.toFixed(0));
  13145. if (cb) {
  13146. cb();
  13147. }
  13148. });
  13149. };
  13150. return VolumeLevelTooltip;
  13151. }(Component$1);
  13152. Component$1.registerComponent('VolumeLevelTooltip', VolumeLevelTooltip);
  13153. /**
  13154. * The {@link MouseVolumeLevelDisplay} component tracks mouse movement over the
  13155. * {@link VolumeControl}. It displays an indicator and a {@link VolumeLevelTooltip}
  13156. * indicating the volume level which is represented by a given point in the
  13157. * {@link VolumeBar}.
  13158. *
  13159. * @extends Component
  13160. */
  13161. var MouseVolumeLevelDisplay = /*#__PURE__*/function (_Component) {
  13162. inheritsLoose(MouseVolumeLevelDisplay, _Component);
  13163. /**
  13164. * Creates an instance of this class.
  13165. *
  13166. * @param {Player} player
  13167. * The {@link Player} that this class should be attached to.
  13168. *
  13169. * @param {Object} [options]
  13170. * The key/value store of player options.
  13171. */
  13172. function MouseVolumeLevelDisplay(player, options) {
  13173. var _this;
  13174. _this = _Component.call(this, player, options) || this;
  13175. _this.update = throttle(bind(assertThisInitialized(_this), _this.update), UPDATE_REFRESH_INTERVAL);
  13176. return _this;
  13177. }
  13178. /**
  13179. * Create the DOM element for this class.
  13180. *
  13181. * @return {Element}
  13182. * The element that was created.
  13183. */
  13184. var _proto = MouseVolumeLevelDisplay.prototype;
  13185. _proto.createEl = function createEl() {
  13186. return _Component.prototype.createEl.call(this, 'div', {
  13187. className: 'vjs-mouse-display'
  13188. });
  13189. }
  13190. /**
  13191. * Enquires updates to its own DOM as well as the DOM of its
  13192. * {@link VolumeLevelTooltip} child.
  13193. *
  13194. * @param {Object} rangeBarRect
  13195. * The `ClientRect` for the {@link VolumeBar} element.
  13196. *
  13197. * @param {number} rangeBarPoint
  13198. * A number from 0 to 1, representing a horizontal/vertical reference point
  13199. * from the left edge of the {@link VolumeBar}
  13200. *
  13201. * @param {boolean} vertical
  13202. * Referees to the Volume control position
  13203. * in the control bar{@link VolumeControl}
  13204. *
  13205. */
  13206. ;
  13207. _proto.update = function update(rangeBarRect, rangeBarPoint, vertical) {
  13208. var _this2 = this;
  13209. var volume = 100 * rangeBarPoint;
  13210. this.getChild('volumeLevelTooltip').updateVolume(rangeBarRect, rangeBarPoint, vertical, volume, function () {
  13211. if (vertical) {
  13212. _this2.el_.style.bottom = rangeBarRect.height * rangeBarPoint + "px";
  13213. } else {
  13214. _this2.el_.style.left = rangeBarRect.width * rangeBarPoint + "px";
  13215. }
  13216. });
  13217. };
  13218. return MouseVolumeLevelDisplay;
  13219. }(Component$1);
  13220. /**
  13221. * Default options for `MouseVolumeLevelDisplay`
  13222. *
  13223. * @type {Object}
  13224. * @private
  13225. */
  13226. MouseVolumeLevelDisplay.prototype.options_ = {
  13227. children: ['volumeLevelTooltip']
  13228. };
  13229. Component$1.registerComponent('MouseVolumeLevelDisplay', MouseVolumeLevelDisplay);
  13230. /**
  13231. * The bar that contains the volume level and can be clicked on to adjust the level
  13232. *
  13233. * @extends Slider
  13234. */
  13235. var VolumeBar = /*#__PURE__*/function (_Slider) {
  13236. inheritsLoose(VolumeBar, _Slider);
  13237. /**
  13238. * Creates an instance of this class.
  13239. *
  13240. * @param {Player} player
  13241. * The `Player` that this class should be attached to.
  13242. *
  13243. * @param {Object} [options]
  13244. * The key/value store of player options.
  13245. */
  13246. function VolumeBar(player, options) {
  13247. var _this;
  13248. _this = _Slider.call(this, player, options) || this;
  13249. _this.on('slideractive', function (e) {
  13250. return _this.updateLastVolume_(e);
  13251. });
  13252. _this.on(player, 'volumechange', function (e) {
  13253. return _this.updateARIAAttributes(e);
  13254. });
  13255. player.ready(function () {
  13256. return _this.updateARIAAttributes();
  13257. });
  13258. return _this;
  13259. }
  13260. /**
  13261. * Create the `Component`'s DOM element
  13262. *
  13263. * @return {Element}
  13264. * The element that was created.
  13265. */
  13266. var _proto = VolumeBar.prototype;
  13267. _proto.createEl = function createEl() {
  13268. return _Slider.prototype.createEl.call(this, 'div', {
  13269. className: 'vjs-volume-bar vjs-slider-bar'
  13270. }, {
  13271. 'aria-label': this.localize('Volume Level'),
  13272. 'aria-live': 'polite'
  13273. });
  13274. }
  13275. /**
  13276. * Handle mouse down on volume bar
  13277. *
  13278. * @param {EventTarget~Event} event
  13279. * The `mousedown` event that caused this to run.
  13280. *
  13281. * @listens mousedown
  13282. */
  13283. ;
  13284. _proto.handleMouseDown = function handleMouseDown(event) {
  13285. if (!isSingleLeftClick(event)) {
  13286. return;
  13287. }
  13288. _Slider.prototype.handleMouseDown.call(this, event);
  13289. }
  13290. /**
  13291. * Handle movement events on the {@link VolumeMenuButton}.
  13292. *
  13293. * @param {EventTarget~Event} event
  13294. * The event that caused this function to run.
  13295. *
  13296. * @listens mousemove
  13297. */
  13298. ;
  13299. _proto.handleMouseMove = function handleMouseMove(event) {
  13300. var mouseVolumeLevelDisplay = this.getChild('mouseVolumeLevelDisplay');
  13301. if (mouseVolumeLevelDisplay) {
  13302. var volumeBarEl = this.el();
  13303. var volumeBarRect = getBoundingClientRect(volumeBarEl);
  13304. var vertical = this.vertical();
  13305. var volumeBarPoint = getPointerPosition(volumeBarEl, event);
  13306. volumeBarPoint = vertical ? volumeBarPoint.y : volumeBarPoint.x; // The default skin has a gap on either side of the `VolumeBar`. This means
  13307. // that it's possible to trigger this behavior outside the boundaries of
  13308. // the `VolumeBar`. This ensures we stay within it at all times.
  13309. volumeBarPoint = clamp(volumeBarPoint, 0, 1);
  13310. mouseVolumeLevelDisplay.update(volumeBarRect, volumeBarPoint, vertical);
  13311. }
  13312. if (!isSingleLeftClick(event)) {
  13313. return;
  13314. }
  13315. this.checkMuted();
  13316. this.player_.volume(this.calculateDistance(event));
  13317. }
  13318. /**
  13319. * If the player is muted unmute it.
  13320. */
  13321. ;
  13322. _proto.checkMuted = function checkMuted() {
  13323. if (this.player_.muted()) {
  13324. this.player_.muted(false);
  13325. }
  13326. }
  13327. /**
  13328. * Get percent of volume level
  13329. *
  13330. * @return {number}
  13331. * Volume level percent as a decimal number.
  13332. */
  13333. ;
  13334. _proto.getPercent = function getPercent() {
  13335. if (this.player_.muted()) {
  13336. return 0;
  13337. }
  13338. return this.player_.volume();
  13339. }
  13340. /**
  13341. * Increase volume level for keyboard users
  13342. */
  13343. ;
  13344. _proto.stepForward = function stepForward() {
  13345. this.checkMuted();
  13346. this.player_.volume(this.player_.volume() + 0.1);
  13347. }
  13348. /**
  13349. * Decrease volume level for keyboard users
  13350. */
  13351. ;
  13352. _proto.stepBack = function stepBack() {
  13353. this.checkMuted();
  13354. this.player_.volume(this.player_.volume() - 0.1);
  13355. }
  13356. /**
  13357. * Update ARIA accessibility attributes
  13358. *
  13359. * @param {EventTarget~Event} [event]
  13360. * The `volumechange` event that caused this function to run.
  13361. *
  13362. * @listens Player#volumechange
  13363. */
  13364. ;
  13365. _proto.updateARIAAttributes = function updateARIAAttributes(event) {
  13366. var ariaValue = this.player_.muted() ? 0 : this.volumeAsPercentage_();
  13367. this.el_.setAttribute('aria-valuenow', ariaValue);
  13368. this.el_.setAttribute('aria-valuetext', ariaValue + '%');
  13369. }
  13370. /**
  13371. * Returns the current value of the player volume as a percentage
  13372. *
  13373. * @private
  13374. */
  13375. ;
  13376. _proto.volumeAsPercentage_ = function volumeAsPercentage_() {
  13377. return Math.round(this.player_.volume() * 100);
  13378. }
  13379. /**
  13380. * When user starts dragging the VolumeBar, store the volume and listen for
  13381. * the end of the drag. When the drag ends, if the volume was set to zero,
  13382. * set lastVolume to the stored volume.
  13383. *
  13384. * @listens slideractive
  13385. * @private
  13386. */
  13387. ;
  13388. _proto.updateLastVolume_ = function updateLastVolume_() {
  13389. var _this2 = this;
  13390. var volumeBeforeDrag = this.player_.volume();
  13391. this.one('sliderinactive', function () {
  13392. if (_this2.player_.volume() === 0) {
  13393. _this2.player_.lastVolume_(volumeBeforeDrag);
  13394. }
  13395. });
  13396. };
  13397. return VolumeBar;
  13398. }(Slider);
  13399. /**
  13400. * Default options for the `VolumeBar`
  13401. *
  13402. * @type {Object}
  13403. * @private
  13404. */
  13405. VolumeBar.prototype.options_ = {
  13406. children: ['volumeLevel'],
  13407. barName: 'volumeLevel'
  13408. }; // MouseVolumeLevelDisplay tooltip should not be added to a player on mobile devices
  13409. if (!IS_IOS && !IS_ANDROID) {
  13410. VolumeBar.prototype.options_.children.splice(0, 0, 'mouseVolumeLevelDisplay');
  13411. }
  13412. /**
  13413. * Call the update event for this Slider when this event happens on the player.
  13414. *
  13415. * @type {string}
  13416. */
  13417. VolumeBar.prototype.playerEvent = 'volumechange';
  13418. Component$1.registerComponent('VolumeBar', VolumeBar);
  13419. /**
  13420. * The component for controlling the volume level
  13421. *
  13422. * @extends Component
  13423. */
  13424. var VolumeControl = /*#__PURE__*/function (_Component) {
  13425. inheritsLoose(VolumeControl, _Component);
  13426. /**
  13427. * Creates an instance of this class.
  13428. *
  13429. * @param {Player} player
  13430. * The `Player` that this class should be attached to.
  13431. *
  13432. * @param {Object} [options={}]
  13433. * The key/value store of player options.
  13434. */
  13435. function VolumeControl(player, options) {
  13436. var _this;
  13437. if (options === void 0) {
  13438. options = {};
  13439. }
  13440. options.vertical = options.vertical || false; // Pass the vertical option down to the VolumeBar if
  13441. // the VolumeBar is turned on.
  13442. if (typeof options.volumeBar === 'undefined' || isPlain(options.volumeBar)) {
  13443. options.volumeBar = options.volumeBar || {};
  13444. options.volumeBar.vertical = options.vertical;
  13445. }
  13446. _this = _Component.call(this, player, options) || this; // hide this control if volume support is missing
  13447. checkVolumeSupport(assertThisInitialized(_this), player);
  13448. _this.throttledHandleMouseMove = throttle(bind(assertThisInitialized(_this), _this.handleMouseMove), UPDATE_REFRESH_INTERVAL);
  13449. _this.handleMouseUpHandler_ = function (e) {
  13450. return _this.handleMouseUp(e);
  13451. };
  13452. _this.on('mousedown', function (e) {
  13453. return _this.handleMouseDown(e);
  13454. });
  13455. _this.on('touchstart', function (e) {
  13456. return _this.handleMouseDown(e);
  13457. });
  13458. _this.on('mousemove', function (e) {
  13459. return _this.handleMouseMove(e);
  13460. }); // while the slider is active (the mouse has been pressed down and
  13461. // is dragging) or in focus we do not want to hide the VolumeBar
  13462. _this.on(_this.volumeBar, ['focus', 'slideractive'], function () {
  13463. _this.volumeBar.addClass('vjs-slider-active');
  13464. _this.addClass('vjs-slider-active');
  13465. _this.trigger('slideractive');
  13466. });
  13467. _this.on(_this.volumeBar, ['blur', 'sliderinactive'], function () {
  13468. _this.volumeBar.removeClass('vjs-slider-active');
  13469. _this.removeClass('vjs-slider-active');
  13470. _this.trigger('sliderinactive');
  13471. });
  13472. return _this;
  13473. }
  13474. /**
  13475. * Create the `Component`'s DOM element
  13476. *
  13477. * @return {Element}
  13478. * The element that was created.
  13479. */
  13480. var _proto = VolumeControl.prototype;
  13481. _proto.createEl = function createEl() {
  13482. var orientationClass = 'vjs-volume-horizontal';
  13483. if (this.options_.vertical) {
  13484. orientationClass = 'vjs-volume-vertical';
  13485. }
  13486. return _Component.prototype.createEl.call(this, 'div', {
  13487. className: "vjs-volume-control vjs-control " + orientationClass
  13488. });
  13489. }
  13490. /**
  13491. * Handle `mousedown` or `touchstart` events on the `VolumeControl`.
  13492. *
  13493. * @param {EventTarget~Event} event
  13494. * `mousedown` or `touchstart` event that triggered this function
  13495. *
  13496. * @listens mousedown
  13497. * @listens touchstart
  13498. */
  13499. ;
  13500. _proto.handleMouseDown = function handleMouseDown(event) {
  13501. var doc = this.el_.ownerDocument;
  13502. this.on(doc, 'mousemove', this.throttledHandleMouseMove);
  13503. this.on(doc, 'touchmove', this.throttledHandleMouseMove);
  13504. this.on(doc, 'mouseup', this.handleMouseUpHandler_);
  13505. this.on(doc, 'touchend', this.handleMouseUpHandler_);
  13506. }
  13507. /**
  13508. * Handle `mouseup` or `touchend` events on the `VolumeControl`.
  13509. *
  13510. * @param {EventTarget~Event} event
  13511. * `mouseup` or `touchend` event that triggered this function.
  13512. *
  13513. * @listens touchend
  13514. * @listens mouseup
  13515. */
  13516. ;
  13517. _proto.handleMouseUp = function handleMouseUp(event) {
  13518. var doc = this.el_.ownerDocument;
  13519. this.off(doc, 'mousemove', this.throttledHandleMouseMove);
  13520. this.off(doc, 'touchmove', this.throttledHandleMouseMove);
  13521. this.off(doc, 'mouseup', this.handleMouseUpHandler_);
  13522. this.off(doc, 'touchend', this.handleMouseUpHandler_);
  13523. }
  13524. /**
  13525. * Handle `mousedown` or `touchstart` events on the `VolumeControl`.
  13526. *
  13527. * @param {EventTarget~Event} event
  13528. * `mousedown` or `touchstart` event that triggered this function
  13529. *
  13530. * @listens mousedown
  13531. * @listens touchstart
  13532. */
  13533. ;
  13534. _proto.handleMouseMove = function handleMouseMove(event) {
  13535. this.volumeBar.handleMouseMove(event);
  13536. };
  13537. return VolumeControl;
  13538. }(Component$1);
  13539. /**
  13540. * Default options for the `VolumeControl`
  13541. *
  13542. * @type {Object}
  13543. * @private
  13544. */
  13545. VolumeControl.prototype.options_ = {
  13546. children: ['volumeBar']
  13547. };
  13548. Component$1.registerComponent('VolumeControl', VolumeControl);
  13549. /**
  13550. * Check if muting volume is supported and if it isn't hide the mute toggle
  13551. * button.
  13552. *
  13553. * @param {Component} self
  13554. * A reference to the mute toggle button
  13555. *
  13556. * @param {Player} player
  13557. * A reference to the player
  13558. *
  13559. * @private
  13560. */
  13561. var checkMuteSupport = function checkMuteSupport(self, player) {
  13562. // hide mute toggle button if it's not supported by the current tech
  13563. if (player.tech_ && !player.tech_.featuresMuteControl) {
  13564. self.addClass('vjs-hidden');
  13565. }
  13566. self.on(player, 'loadstart', function () {
  13567. if (!player.tech_.featuresMuteControl) {
  13568. self.addClass('vjs-hidden');
  13569. } else {
  13570. self.removeClass('vjs-hidden');
  13571. }
  13572. });
  13573. };
  13574. /**
  13575. * A button component for muting the audio.
  13576. *
  13577. * @extends Button
  13578. */
  13579. var MuteToggle = /*#__PURE__*/function (_Button) {
  13580. inheritsLoose(MuteToggle, _Button);
  13581. /**
  13582. * Creates an instance of this class.
  13583. *
  13584. * @param {Player} player
  13585. * The `Player` that this class should be attached to.
  13586. *
  13587. * @param {Object} [options]
  13588. * The key/value store of player options.
  13589. */
  13590. function MuteToggle(player, options) {
  13591. var _this;
  13592. _this = _Button.call(this, player, options) || this; // hide this control if volume support is missing
  13593. checkMuteSupport(assertThisInitialized(_this), player);
  13594. _this.on(player, ['loadstart', 'volumechange'], function (e) {
  13595. return _this.update(e);
  13596. });
  13597. return _this;
  13598. }
  13599. /**
  13600. * Builds the default DOM `className`.
  13601. *
  13602. * @return {string}
  13603. * The DOM `className` for this object.
  13604. */
  13605. var _proto = MuteToggle.prototype;
  13606. _proto.buildCSSClass = function buildCSSClass() {
  13607. return "vjs-mute-control " + _Button.prototype.buildCSSClass.call(this);
  13608. }
  13609. /**
  13610. * This gets called when an `MuteToggle` is "clicked". See
  13611. * {@link ClickableComponent} for more detailed information on what a click can be.
  13612. *
  13613. * @param {EventTarget~Event} [event]
  13614. * The `keydown`, `tap`, or `click` event that caused this function to be
  13615. * called.
  13616. *
  13617. * @listens tap
  13618. * @listens click
  13619. */
  13620. ;
  13621. _proto.handleClick = function handleClick(event) {
  13622. var vol = this.player_.volume();
  13623. var lastVolume = this.player_.lastVolume_();
  13624. if (vol === 0) {
  13625. var volumeToSet = lastVolume < 0.1 ? 0.1 : lastVolume;
  13626. this.player_.volume(volumeToSet);
  13627. this.player_.muted(false);
  13628. } else {
  13629. this.player_.muted(this.player_.muted() ? false : true);
  13630. }
  13631. }
  13632. /**
  13633. * Update the `MuteToggle` button based on the state of `volume` and `muted`
  13634. * on the player.
  13635. *
  13636. * @param {EventTarget~Event} [event]
  13637. * The {@link Player#loadstart} event if this function was called
  13638. * through an event.
  13639. *
  13640. * @listens Player#loadstart
  13641. * @listens Player#volumechange
  13642. */
  13643. ;
  13644. _proto.update = function update(event) {
  13645. this.updateIcon_();
  13646. this.updateControlText_();
  13647. }
  13648. /**
  13649. * Update the appearance of the `MuteToggle` icon.
  13650. *
  13651. * Possible states (given `level` variable below):
  13652. * - 0: crossed out
  13653. * - 1: zero bars of volume
  13654. * - 2: one bar of volume
  13655. * - 3: two bars of volume
  13656. *
  13657. * @private
  13658. */
  13659. ;
  13660. _proto.updateIcon_ = function updateIcon_() {
  13661. var vol = this.player_.volume();
  13662. var level = 3; // in iOS when a player is loaded with muted attribute
  13663. // and volume is changed with a native mute button
  13664. // we want to make sure muted state is updated
  13665. if (IS_IOS && this.player_.tech_ && this.player_.tech_.el_) {
  13666. this.player_.muted(this.player_.tech_.el_.muted);
  13667. }
  13668. if (vol === 0 || this.player_.muted()) {
  13669. level = 0;
  13670. } else if (vol < 0.33) {
  13671. level = 1;
  13672. } else if (vol < 0.67) {
  13673. level = 2;
  13674. } // TODO improve muted icon classes
  13675. for (var i = 0; i < 4; i++) {
  13676. removeClass(this.el_, "vjs-vol-" + i);
  13677. }
  13678. addClass(this.el_, "vjs-vol-" + level);
  13679. }
  13680. /**
  13681. * If `muted` has changed on the player, update the control text
  13682. * (`title` attribute on `vjs-mute-control` element and content of
  13683. * `vjs-control-text` element).
  13684. *
  13685. * @private
  13686. */
  13687. ;
  13688. _proto.updateControlText_ = function updateControlText_() {
  13689. var soundOff = this.player_.muted() || this.player_.volume() === 0;
  13690. var text = soundOff ? 'Unmute' : 'Mute';
  13691. if (this.controlText() !== text) {
  13692. this.controlText(text);
  13693. }
  13694. };
  13695. return MuteToggle;
  13696. }(Button);
  13697. /**
  13698. * The text that should display over the `MuteToggle`s controls. Added for localization.
  13699. *
  13700. * @type {string}
  13701. * @private
  13702. */
  13703. MuteToggle.prototype.controlText_ = 'Mute';
  13704. Component$1.registerComponent('MuteToggle', MuteToggle);
  13705. /**
  13706. * A Component to contain the MuteToggle and VolumeControl so that
  13707. * they can work together.
  13708. *
  13709. * @extends Component
  13710. */
  13711. var VolumePanel = /*#__PURE__*/function (_Component) {
  13712. inheritsLoose(VolumePanel, _Component);
  13713. /**
  13714. * Creates an instance of this class.
  13715. *
  13716. * @param {Player} player
  13717. * The `Player` that this class should be attached to.
  13718. *
  13719. * @param {Object} [options={}]
  13720. * The key/value store of player options.
  13721. */
  13722. function VolumePanel(player, options) {
  13723. var _this;
  13724. if (options === void 0) {
  13725. options = {};
  13726. }
  13727. if (typeof options.inline !== 'undefined') {
  13728. options.inline = options.inline;
  13729. } else {
  13730. options.inline = true;
  13731. } // pass the inline option down to the VolumeControl as vertical if
  13732. // the VolumeControl is on.
  13733. if (typeof options.volumeControl === 'undefined' || isPlain(options.volumeControl)) {
  13734. options.volumeControl = options.volumeControl || {};
  13735. options.volumeControl.vertical = !options.inline;
  13736. }
  13737. _this = _Component.call(this, player, options) || this; // this handler is used by mouse handler methods below
  13738. _this.handleKeyPressHandler_ = function (e) {
  13739. return _this.handleKeyPress(e);
  13740. };
  13741. _this.on(player, ['loadstart'], function (e) {
  13742. return _this.volumePanelState_(e);
  13743. });
  13744. _this.on(_this.muteToggle, 'keyup', function (e) {
  13745. return _this.handleKeyPress(e);
  13746. });
  13747. _this.on(_this.volumeControl, 'keyup', function (e) {
  13748. return _this.handleVolumeControlKeyUp(e);
  13749. });
  13750. _this.on('keydown', function (e) {
  13751. return _this.handleKeyPress(e);
  13752. });
  13753. _this.on('mouseover', function (e) {
  13754. return _this.handleMouseOver(e);
  13755. });
  13756. _this.on('mouseout', function (e) {
  13757. return _this.handleMouseOut(e);
  13758. }); // while the slider is active (the mouse has been pressed down and
  13759. // is dragging) we do not want to hide the VolumeBar
  13760. _this.on(_this.volumeControl, ['slideractive'], _this.sliderActive_);
  13761. _this.on(_this.volumeControl, ['sliderinactive'], _this.sliderInactive_);
  13762. return _this;
  13763. }
  13764. /**
  13765. * Add vjs-slider-active class to the VolumePanel
  13766. *
  13767. * @listens VolumeControl#slideractive
  13768. * @private
  13769. */
  13770. var _proto = VolumePanel.prototype;
  13771. _proto.sliderActive_ = function sliderActive_() {
  13772. this.addClass('vjs-slider-active');
  13773. }
  13774. /**
  13775. * Removes vjs-slider-active class to the VolumePanel
  13776. *
  13777. * @listens VolumeControl#sliderinactive
  13778. * @private
  13779. */
  13780. ;
  13781. _proto.sliderInactive_ = function sliderInactive_() {
  13782. this.removeClass('vjs-slider-active');
  13783. }
  13784. /**
  13785. * Adds vjs-hidden or vjs-mute-toggle-only to the VolumePanel
  13786. * depending on MuteToggle and VolumeControl state
  13787. *
  13788. * @listens Player#loadstart
  13789. * @private
  13790. */
  13791. ;
  13792. _proto.volumePanelState_ = function volumePanelState_() {
  13793. // hide volume panel if neither volume control or mute toggle
  13794. // are displayed
  13795. if (this.volumeControl.hasClass('vjs-hidden') && this.muteToggle.hasClass('vjs-hidden')) {
  13796. this.addClass('vjs-hidden');
  13797. } // if only mute toggle is visible we don't want
  13798. // volume panel expanding when hovered or active
  13799. if (this.volumeControl.hasClass('vjs-hidden') && !this.muteToggle.hasClass('vjs-hidden')) {
  13800. this.addClass('vjs-mute-toggle-only');
  13801. }
  13802. }
  13803. /**
  13804. * Create the `Component`'s DOM element
  13805. *
  13806. * @return {Element}
  13807. * The element that was created.
  13808. */
  13809. ;
  13810. _proto.createEl = function createEl() {
  13811. var orientationClass = 'vjs-volume-panel-horizontal';
  13812. if (!this.options_.inline) {
  13813. orientationClass = 'vjs-volume-panel-vertical';
  13814. }
  13815. return _Component.prototype.createEl.call(this, 'div', {
  13816. className: "vjs-volume-panel vjs-control " + orientationClass
  13817. });
  13818. }
  13819. /**
  13820. * Dispose of the `volume-panel` and all child components.
  13821. */
  13822. ;
  13823. _proto.dispose = function dispose() {
  13824. this.handleMouseOut();
  13825. _Component.prototype.dispose.call(this);
  13826. }
  13827. /**
  13828. * Handles `keyup` events on the `VolumeControl`, looking for ESC, which closes
  13829. * the volume panel and sets focus on `MuteToggle`.
  13830. *
  13831. * @param {EventTarget~Event} event
  13832. * The `keyup` event that caused this function to be called.
  13833. *
  13834. * @listens keyup
  13835. */
  13836. ;
  13837. _proto.handleVolumeControlKeyUp = function handleVolumeControlKeyUp(event) {
  13838. if (keycode.isEventKey(event, 'Esc')) {
  13839. this.muteToggle.focus();
  13840. }
  13841. }
  13842. /**
  13843. * This gets called when a `VolumePanel` gains hover via a `mouseover` event.
  13844. * Turns on listening for `mouseover` event. When they happen it
  13845. * calls `this.handleMouseOver`.
  13846. *
  13847. * @param {EventTarget~Event} event
  13848. * The `mouseover` event that caused this function to be called.
  13849. *
  13850. * @listens mouseover
  13851. */
  13852. ;
  13853. _proto.handleMouseOver = function handleMouseOver(event) {
  13854. this.addClass('vjs-hover');
  13855. on(document, 'keyup', this.handleKeyPressHandler_);
  13856. }
  13857. /**
  13858. * This gets called when a `VolumePanel` gains hover via a `mouseout` event.
  13859. * Turns on listening for `mouseout` event. When they happen it
  13860. * calls `this.handleMouseOut`.
  13861. *
  13862. * @param {EventTarget~Event} event
  13863. * The `mouseout` event that caused this function to be called.
  13864. *
  13865. * @listens mouseout
  13866. */
  13867. ;
  13868. _proto.handleMouseOut = function handleMouseOut(event) {
  13869. this.removeClass('vjs-hover');
  13870. off(document, 'keyup', this.handleKeyPressHandler_);
  13871. }
  13872. /**
  13873. * Handles `keyup` event on the document or `keydown` event on the `VolumePanel`,
  13874. * looking for ESC, which hides the `VolumeControl`.
  13875. *
  13876. * @param {EventTarget~Event} event
  13877. * The keypress that triggered this event.
  13878. *
  13879. * @listens keydown | keyup
  13880. */
  13881. ;
  13882. _proto.handleKeyPress = function handleKeyPress(event) {
  13883. if (keycode.isEventKey(event, 'Esc')) {
  13884. this.handleMouseOut();
  13885. }
  13886. };
  13887. return VolumePanel;
  13888. }(Component$1);
  13889. /**
  13890. * Default options for the `VolumeControl`
  13891. *
  13892. * @type {Object}
  13893. * @private
  13894. */
  13895. VolumePanel.prototype.options_ = {
  13896. children: ['muteToggle', 'volumeControl']
  13897. };
  13898. Component$1.registerComponent('VolumePanel', VolumePanel);
  13899. /**
  13900. * The Menu component is used to build popup menus, including subtitle and
  13901. * captions selection menus.
  13902. *
  13903. * @extends Component
  13904. */
  13905. var Menu = /*#__PURE__*/function (_Component) {
  13906. inheritsLoose(Menu, _Component);
  13907. /**
  13908. * Create an instance of this class.
  13909. *
  13910. * @param {Player} player
  13911. * the player that this component should attach to
  13912. *
  13913. * @param {Object} [options]
  13914. * Object of option names and values
  13915. *
  13916. */
  13917. function Menu(player, options) {
  13918. var _this;
  13919. _this = _Component.call(this, player, options) || this;
  13920. if (options) {
  13921. _this.menuButton_ = options.menuButton;
  13922. }
  13923. _this.focusedChild_ = -1;
  13924. _this.on('keydown', function (e) {
  13925. return _this.handleKeyDown(e);
  13926. }); // All the menu item instances share the same blur handler provided by the menu container.
  13927. _this.boundHandleBlur_ = function (e) {
  13928. return _this.handleBlur(e);
  13929. };
  13930. _this.boundHandleTapClick_ = function (e) {
  13931. return _this.handleTapClick(e);
  13932. };
  13933. return _this;
  13934. }
  13935. /**
  13936. * Add event listeners to the {@link MenuItem}.
  13937. *
  13938. * @param {Object} component
  13939. * The instance of the `MenuItem` to add listeners to.
  13940. *
  13941. */
  13942. var _proto = Menu.prototype;
  13943. _proto.addEventListenerForItem = function addEventListenerForItem(component) {
  13944. if (!(component instanceof Component$1)) {
  13945. return;
  13946. }
  13947. this.on(component, 'blur', this.boundHandleBlur_);
  13948. this.on(component, ['tap', 'click'], this.boundHandleTapClick_);
  13949. }
  13950. /**
  13951. * Remove event listeners from the {@link MenuItem}.
  13952. *
  13953. * @param {Object} component
  13954. * The instance of the `MenuItem` to remove listeners.
  13955. *
  13956. */
  13957. ;
  13958. _proto.removeEventListenerForItem = function removeEventListenerForItem(component) {
  13959. if (!(component instanceof Component$1)) {
  13960. return;
  13961. }
  13962. this.off(component, 'blur', this.boundHandleBlur_);
  13963. this.off(component, ['tap', 'click'], this.boundHandleTapClick_);
  13964. }
  13965. /**
  13966. * This method will be called indirectly when the component has been added
  13967. * before the component adds to the new menu instance by `addItem`.
  13968. * In this case, the original menu instance will remove the component
  13969. * by calling `removeChild`.
  13970. *
  13971. * @param {Object} component
  13972. * The instance of the `MenuItem`
  13973. */
  13974. ;
  13975. _proto.removeChild = function removeChild(component) {
  13976. if (typeof component === 'string') {
  13977. component = this.getChild(component);
  13978. }
  13979. this.removeEventListenerForItem(component);
  13980. _Component.prototype.removeChild.call(this, component);
  13981. }
  13982. /**
  13983. * Add a {@link MenuItem} to the menu.
  13984. *
  13985. * @param {Object|string} component
  13986. * The name or instance of the `MenuItem` to add.
  13987. *
  13988. */
  13989. ;
  13990. _proto.addItem = function addItem(component) {
  13991. var childComponent = this.addChild(component);
  13992. if (childComponent) {
  13993. this.addEventListenerForItem(childComponent);
  13994. }
  13995. }
  13996. /**
  13997. * Create the `Menu`s DOM element.
  13998. *
  13999. * @return {Element}
  14000. * the element that was created
  14001. */
  14002. ;
  14003. _proto.createEl = function createEl$1() {
  14004. var contentElType = this.options_.contentElType || 'ul';
  14005. this.contentEl_ = createEl(contentElType, {
  14006. className: 'vjs-menu-content'
  14007. });
  14008. this.contentEl_.setAttribute('role', 'menu');
  14009. var el = _Component.prototype.createEl.call(this, 'div', {
  14010. append: this.contentEl_,
  14011. className: 'vjs-menu'
  14012. });
  14013. el.appendChild(this.contentEl_); // Prevent clicks from bubbling up. Needed for Menu Buttons,
  14014. // where a click on the parent is significant
  14015. on(el, 'click', function (event) {
  14016. event.preventDefault();
  14017. event.stopImmediatePropagation();
  14018. });
  14019. return el;
  14020. };
  14021. _proto.dispose = function dispose() {
  14022. this.contentEl_ = null;
  14023. this.boundHandleBlur_ = null;
  14024. this.boundHandleTapClick_ = null;
  14025. _Component.prototype.dispose.call(this);
  14026. }
  14027. /**
  14028. * Called when a `MenuItem` loses focus.
  14029. *
  14030. * @param {EventTarget~Event} event
  14031. * The `blur` event that caused this function to be called.
  14032. *
  14033. * @listens blur
  14034. */
  14035. ;
  14036. _proto.handleBlur = function handleBlur(event) {
  14037. var relatedTarget = event.relatedTarget || document.activeElement; // Close menu popup when a user clicks outside the menu
  14038. if (!this.children().some(function (element) {
  14039. return element.el() === relatedTarget;
  14040. })) {
  14041. var btn = this.menuButton_;
  14042. if (btn && btn.buttonPressed_ && relatedTarget !== btn.el().firstChild) {
  14043. btn.unpressButton();
  14044. }
  14045. }
  14046. }
  14047. /**
  14048. * Called when a `MenuItem` gets clicked or tapped.
  14049. *
  14050. * @param {EventTarget~Event} event
  14051. * The `click` or `tap` event that caused this function to be called.
  14052. *
  14053. * @listens click,tap
  14054. */
  14055. ;
  14056. _proto.handleTapClick = function handleTapClick(event) {
  14057. // Unpress the associated MenuButton, and move focus back to it
  14058. if (this.menuButton_) {
  14059. this.menuButton_.unpressButton();
  14060. var childComponents = this.children();
  14061. if (!Array.isArray(childComponents)) {
  14062. return;
  14063. }
  14064. var foundComponent = childComponents.filter(function (component) {
  14065. return component.el() === event.target;
  14066. })[0];
  14067. if (!foundComponent) {
  14068. return;
  14069. } // don't focus menu button if item is a caption settings item
  14070. // because focus will move elsewhere
  14071. if (foundComponent.name() !== 'CaptionSettingsMenuItem') {
  14072. this.menuButton_.focus();
  14073. }
  14074. }
  14075. }
  14076. /**
  14077. * Handle a `keydown` event on this menu. This listener is added in the constructor.
  14078. *
  14079. * @param {EventTarget~Event} event
  14080. * A `keydown` event that happened on the menu.
  14081. *
  14082. * @listens keydown
  14083. */
  14084. ;
  14085. _proto.handleKeyDown = function handleKeyDown(event) {
  14086. // Left and Down Arrows
  14087. if (keycode.isEventKey(event, 'Left') || keycode.isEventKey(event, 'Down')) {
  14088. event.preventDefault();
  14089. event.stopPropagation();
  14090. this.stepForward(); // Up and Right Arrows
  14091. } else if (keycode.isEventKey(event, 'Right') || keycode.isEventKey(event, 'Up')) {
  14092. event.preventDefault();
  14093. event.stopPropagation();
  14094. this.stepBack();
  14095. }
  14096. }
  14097. /**
  14098. * Move to next (lower) menu item for keyboard users.
  14099. */
  14100. ;
  14101. _proto.stepForward = function stepForward() {
  14102. var stepChild = 0;
  14103. if (this.focusedChild_ !== undefined) {
  14104. stepChild = this.focusedChild_ + 1;
  14105. }
  14106. this.focus(stepChild);
  14107. }
  14108. /**
  14109. * Move to previous (higher) menu item for keyboard users.
  14110. */
  14111. ;
  14112. _proto.stepBack = function stepBack() {
  14113. var stepChild = 0;
  14114. if (this.focusedChild_ !== undefined) {
  14115. stepChild = this.focusedChild_ - 1;
  14116. }
  14117. this.focus(stepChild);
  14118. }
  14119. /**
  14120. * Set focus on a {@link MenuItem} in the `Menu`.
  14121. *
  14122. * @param {Object|string} [item=0]
  14123. * Index of child item set focus on.
  14124. */
  14125. ;
  14126. _proto.focus = function focus(item) {
  14127. if (item === void 0) {
  14128. item = 0;
  14129. }
  14130. var children = this.children().slice();
  14131. var haveTitle = children.length && children[0].hasClass('vjs-menu-title');
  14132. if (haveTitle) {
  14133. children.shift();
  14134. }
  14135. if (children.length > 0) {
  14136. if (item < 0) {
  14137. item = 0;
  14138. } else if (item >= children.length) {
  14139. item = children.length - 1;
  14140. }
  14141. this.focusedChild_ = item;
  14142. children[item].el_.focus();
  14143. }
  14144. };
  14145. return Menu;
  14146. }(Component$1);
  14147. Component$1.registerComponent('Menu', Menu);
  14148. /**
  14149. * A `MenuButton` class for any popup {@link Menu}.
  14150. *
  14151. * @extends Component
  14152. */
  14153. var MenuButton = /*#__PURE__*/function (_Component) {
  14154. inheritsLoose(MenuButton, _Component);
  14155. /**
  14156. * Creates an instance of this class.
  14157. *
  14158. * @param {Player} player
  14159. * The `Player` that this class should be attached to.
  14160. *
  14161. * @param {Object} [options={}]
  14162. * The key/value store of player options.
  14163. */
  14164. function MenuButton(player, options) {
  14165. var _this;
  14166. if (options === void 0) {
  14167. options = {};
  14168. }
  14169. _this = _Component.call(this, player, options) || this;
  14170. _this.menuButton_ = new Button(player, options);
  14171. _this.menuButton_.controlText(_this.controlText_);
  14172. _this.menuButton_.el_.setAttribute('aria-haspopup', 'true'); // Add buildCSSClass values to the button, not the wrapper
  14173. var buttonClass = Button.prototype.buildCSSClass();
  14174. _this.menuButton_.el_.className = _this.buildCSSClass() + ' ' + buttonClass;
  14175. _this.menuButton_.removeClass('vjs-control');
  14176. _this.addChild(_this.menuButton_);
  14177. _this.update();
  14178. _this.enabled_ = true;
  14179. var handleClick = function handleClick(e) {
  14180. return _this.handleClick(e);
  14181. };
  14182. _this.handleMenuKeyUp_ = function (e) {
  14183. return _this.handleMenuKeyUp(e);
  14184. };
  14185. _this.on(_this.menuButton_, 'tap', handleClick);
  14186. _this.on(_this.menuButton_, 'click', handleClick);
  14187. _this.on(_this.menuButton_, 'keydown', function (e) {
  14188. return _this.handleKeyDown(e);
  14189. });
  14190. _this.on(_this.menuButton_, 'mouseenter', function () {
  14191. _this.addClass('vjs-hover');
  14192. _this.menu.show();
  14193. on(document, 'keyup', _this.handleMenuKeyUp_);
  14194. });
  14195. _this.on('mouseleave', function (e) {
  14196. return _this.handleMouseLeave(e);
  14197. });
  14198. _this.on('keydown', function (e) {
  14199. return _this.handleSubmenuKeyDown(e);
  14200. });
  14201. return _this;
  14202. }
  14203. /**
  14204. * Update the menu based on the current state of its items.
  14205. */
  14206. var _proto = MenuButton.prototype;
  14207. _proto.update = function update() {
  14208. var menu = this.createMenu();
  14209. if (this.menu) {
  14210. this.menu.dispose();
  14211. this.removeChild(this.menu);
  14212. }
  14213. this.menu = menu;
  14214. this.addChild(menu);
  14215. /**
  14216. * Track the state of the menu button
  14217. *
  14218. * @type {Boolean}
  14219. * @private
  14220. */
  14221. this.buttonPressed_ = false;
  14222. this.menuButton_.el_.setAttribute('aria-expanded', 'false');
  14223. if (this.items && this.items.length <= this.hideThreshold_) {
  14224. this.hide();
  14225. this.menu.contentEl_.removeAttribute('role');
  14226. } else {
  14227. this.show();
  14228. this.menu.contentEl_.setAttribute('role', 'menu');
  14229. }
  14230. }
  14231. /**
  14232. * Create the menu and add all items to it.
  14233. *
  14234. * @return {Menu}
  14235. * The constructed menu
  14236. */
  14237. ;
  14238. _proto.createMenu = function createMenu() {
  14239. var menu = new Menu(this.player_, {
  14240. menuButton: this
  14241. });
  14242. /**
  14243. * Hide the menu if the number of items is less than or equal to this threshold. This defaults
  14244. * to 0 and whenever we add items which can be hidden to the menu we'll increment it. We list
  14245. * it here because every time we run `createMenu` we need to reset the value.
  14246. *
  14247. * @protected
  14248. * @type {Number}
  14249. */
  14250. this.hideThreshold_ = 0; // Add a title list item to the top
  14251. if (this.options_.title) {
  14252. var titleEl = createEl('li', {
  14253. className: 'vjs-menu-title',
  14254. textContent: toTitleCase$1(this.options_.title),
  14255. tabIndex: -1
  14256. });
  14257. var titleComponent = new Component$1(this.player_, {
  14258. el: titleEl
  14259. });
  14260. menu.addItem(titleComponent);
  14261. }
  14262. this.items = this.createItems();
  14263. if (this.items) {
  14264. // Add menu items to the menu
  14265. for (var i = 0; i < this.items.length; i++) {
  14266. menu.addItem(this.items[i]);
  14267. }
  14268. }
  14269. return menu;
  14270. }
  14271. /**
  14272. * Create the list of menu items. Specific to each subclass.
  14273. *
  14274. * @abstract
  14275. */
  14276. ;
  14277. _proto.createItems = function createItems() {}
  14278. /**
  14279. * Create the `MenuButtons`s DOM element.
  14280. *
  14281. * @return {Element}
  14282. * The element that gets created.
  14283. */
  14284. ;
  14285. _proto.createEl = function createEl() {
  14286. return _Component.prototype.createEl.call(this, 'div', {
  14287. className: this.buildWrapperCSSClass()
  14288. }, {});
  14289. }
  14290. /**
  14291. * Allow sub components to stack CSS class names for the wrapper element
  14292. *
  14293. * @return {string}
  14294. * The constructed wrapper DOM `className`
  14295. */
  14296. ;
  14297. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  14298. var menuButtonClass = 'vjs-menu-button'; // If the inline option is passed, we want to use different styles altogether.
  14299. if (this.options_.inline === true) {
  14300. menuButtonClass += '-inline';
  14301. } else {
  14302. menuButtonClass += '-popup';
  14303. } // TODO: Fix the CSS so that this isn't necessary
  14304. var buttonClass = Button.prototype.buildCSSClass();
  14305. return "vjs-menu-button " + menuButtonClass + " " + buttonClass + " " + _Component.prototype.buildCSSClass.call(this);
  14306. }
  14307. /**
  14308. * Builds the default DOM `className`.
  14309. *
  14310. * @return {string}
  14311. * The DOM `className` for this object.
  14312. */
  14313. ;
  14314. _proto.buildCSSClass = function buildCSSClass() {
  14315. var menuButtonClass = 'vjs-menu-button'; // If the inline option is passed, we want to use different styles altogether.
  14316. if (this.options_.inline === true) {
  14317. menuButtonClass += '-inline';
  14318. } else {
  14319. menuButtonClass += '-popup';
  14320. }
  14321. return "vjs-menu-button " + menuButtonClass + " " + _Component.prototype.buildCSSClass.call(this);
  14322. }
  14323. /**
  14324. * Get or set the localized control text that will be used for accessibility.
  14325. *
  14326. * > NOTE: This will come from the internal `menuButton_` element.
  14327. *
  14328. * @param {string} [text]
  14329. * Control text for element.
  14330. *
  14331. * @param {Element} [el=this.menuButton_.el()]
  14332. * Element to set the title on.
  14333. *
  14334. * @return {string}
  14335. * - The control text when getting
  14336. */
  14337. ;
  14338. _proto.controlText = function controlText(text, el) {
  14339. if (el === void 0) {
  14340. el = this.menuButton_.el();
  14341. }
  14342. return this.menuButton_.controlText(text, el);
  14343. }
  14344. /**
  14345. * Dispose of the `menu-button` and all child components.
  14346. */
  14347. ;
  14348. _proto.dispose = function dispose() {
  14349. this.handleMouseLeave();
  14350. _Component.prototype.dispose.call(this);
  14351. }
  14352. /**
  14353. * Handle a click on a `MenuButton`.
  14354. * See {@link ClickableComponent#handleClick} for instances where this is called.
  14355. *
  14356. * @param {EventTarget~Event} event
  14357. * The `keydown`, `tap`, or `click` event that caused this function to be
  14358. * called.
  14359. *
  14360. * @listens tap
  14361. * @listens click
  14362. */
  14363. ;
  14364. _proto.handleClick = function handleClick(event) {
  14365. if (this.buttonPressed_) {
  14366. this.unpressButton();
  14367. } else {
  14368. this.pressButton();
  14369. }
  14370. }
  14371. /**
  14372. * Handle `mouseleave` for `MenuButton`.
  14373. *
  14374. * @param {EventTarget~Event} event
  14375. * The `mouseleave` event that caused this function to be called.
  14376. *
  14377. * @listens mouseleave
  14378. */
  14379. ;
  14380. _proto.handleMouseLeave = function handleMouseLeave(event) {
  14381. this.removeClass('vjs-hover');
  14382. off(document, 'keyup', this.handleMenuKeyUp_);
  14383. }
  14384. /**
  14385. * Set the focus to the actual button, not to this element
  14386. */
  14387. ;
  14388. _proto.focus = function focus() {
  14389. this.menuButton_.focus();
  14390. }
  14391. /**
  14392. * Remove the focus from the actual button, not this element
  14393. */
  14394. ;
  14395. _proto.blur = function blur() {
  14396. this.menuButton_.blur();
  14397. }
  14398. /**
  14399. * Handle tab, escape, down arrow, and up arrow keys for `MenuButton`. See
  14400. * {@link ClickableComponent#handleKeyDown} for instances where this is called.
  14401. *
  14402. * @param {EventTarget~Event} event
  14403. * The `keydown` event that caused this function to be called.
  14404. *
  14405. * @listens keydown
  14406. */
  14407. ;
  14408. _proto.handleKeyDown = function handleKeyDown(event) {
  14409. // Escape or Tab unpress the 'button'
  14410. if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) {
  14411. if (this.buttonPressed_) {
  14412. this.unpressButton();
  14413. } // Don't preventDefault for Tab key - we still want to lose focus
  14414. if (!keycode.isEventKey(event, 'Tab')) {
  14415. event.preventDefault(); // Set focus back to the menu button's button
  14416. this.menuButton_.focus();
  14417. } // Up Arrow or Down Arrow also 'press' the button to open the menu
  14418. } else if (keycode.isEventKey(event, 'Up') || keycode.isEventKey(event, 'Down')) {
  14419. if (!this.buttonPressed_) {
  14420. event.preventDefault();
  14421. this.pressButton();
  14422. }
  14423. }
  14424. }
  14425. /**
  14426. * Handle a `keyup` event on a `MenuButton`. The listener for this is added in
  14427. * the constructor.
  14428. *
  14429. * @param {EventTarget~Event} event
  14430. * Key press event
  14431. *
  14432. * @listens keyup
  14433. */
  14434. ;
  14435. _proto.handleMenuKeyUp = function handleMenuKeyUp(event) {
  14436. // Escape hides popup menu
  14437. if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) {
  14438. this.removeClass('vjs-hover');
  14439. }
  14440. }
  14441. /**
  14442. * This method name now delegates to `handleSubmenuKeyDown`. This means
  14443. * anyone calling `handleSubmenuKeyPress` will not see their method calls
  14444. * stop working.
  14445. *
  14446. * @param {EventTarget~Event} event
  14447. * The event that caused this function to be called.
  14448. */
  14449. ;
  14450. _proto.handleSubmenuKeyPress = function handleSubmenuKeyPress(event) {
  14451. this.handleSubmenuKeyDown(event);
  14452. }
  14453. /**
  14454. * Handle a `keydown` event on a sub-menu. The listener for this is added in
  14455. * the constructor.
  14456. *
  14457. * @param {EventTarget~Event} event
  14458. * Key press event
  14459. *
  14460. * @listens keydown
  14461. */
  14462. ;
  14463. _proto.handleSubmenuKeyDown = function handleSubmenuKeyDown(event) {
  14464. // Escape or Tab unpress the 'button'
  14465. if (keycode.isEventKey(event, 'Esc') || keycode.isEventKey(event, 'Tab')) {
  14466. if (this.buttonPressed_) {
  14467. this.unpressButton();
  14468. } // Don't preventDefault for Tab key - we still want to lose focus
  14469. if (!keycode.isEventKey(event, 'Tab')) {
  14470. event.preventDefault(); // Set focus back to the menu button's button
  14471. this.menuButton_.focus();
  14472. }
  14473. }
  14474. }
  14475. /**
  14476. * Put the current `MenuButton` into a pressed state.
  14477. */
  14478. ;
  14479. _proto.pressButton = function pressButton() {
  14480. if (this.enabled_) {
  14481. this.buttonPressed_ = true;
  14482. this.menu.show();
  14483. this.menu.lockShowing();
  14484. this.menuButton_.el_.setAttribute('aria-expanded', 'true'); // set the focus into the submenu, except on iOS where it is resulting in
  14485. // undesired scrolling behavior when the player is in an iframe
  14486. if (IS_IOS && isInFrame()) {
  14487. // Return early so that the menu isn't focused
  14488. return;
  14489. }
  14490. this.menu.focus();
  14491. }
  14492. }
  14493. /**
  14494. * Take the current `MenuButton` out of a pressed state.
  14495. */
  14496. ;
  14497. _proto.unpressButton = function unpressButton() {
  14498. if (this.enabled_) {
  14499. this.buttonPressed_ = false;
  14500. this.menu.unlockShowing();
  14501. this.menu.hide();
  14502. this.menuButton_.el_.setAttribute('aria-expanded', 'false');
  14503. }
  14504. }
  14505. /**
  14506. * Disable the `MenuButton`. Don't allow it to be clicked.
  14507. */
  14508. ;
  14509. _proto.disable = function disable() {
  14510. this.unpressButton();
  14511. this.enabled_ = false;
  14512. this.addClass('vjs-disabled');
  14513. this.menuButton_.disable();
  14514. }
  14515. /**
  14516. * Enable the `MenuButton`. Allow it to be clicked.
  14517. */
  14518. ;
  14519. _proto.enable = function enable() {
  14520. this.enabled_ = true;
  14521. this.removeClass('vjs-disabled');
  14522. this.menuButton_.enable();
  14523. };
  14524. return MenuButton;
  14525. }(Component$1);
  14526. Component$1.registerComponent('MenuButton', MenuButton);
  14527. /**
  14528. * The base class for buttons that toggle specific track types (e.g. subtitles).
  14529. *
  14530. * @extends MenuButton
  14531. */
  14532. var TrackButton = /*#__PURE__*/function (_MenuButton) {
  14533. inheritsLoose(TrackButton, _MenuButton);
  14534. /**
  14535. * Creates an instance of this class.
  14536. *
  14537. * @param {Player} player
  14538. * The `Player` that this class should be attached to.
  14539. *
  14540. * @param {Object} [options]
  14541. * The key/value store of player options.
  14542. */
  14543. function TrackButton(player, options) {
  14544. var _this;
  14545. var tracks = options.tracks;
  14546. _this = _MenuButton.call(this, player, options) || this;
  14547. if (_this.items.length <= 1) {
  14548. _this.hide();
  14549. }
  14550. if (!tracks) {
  14551. return assertThisInitialized(_this);
  14552. }
  14553. var updateHandler = bind(assertThisInitialized(_this), _this.update);
  14554. tracks.addEventListener('removetrack', updateHandler);
  14555. tracks.addEventListener('addtrack', updateHandler);
  14556. tracks.addEventListener('labelchange', updateHandler);
  14557. _this.player_.on('ready', updateHandler);
  14558. _this.player_.on('dispose', function () {
  14559. tracks.removeEventListener('removetrack', updateHandler);
  14560. tracks.removeEventListener('addtrack', updateHandler);
  14561. tracks.removeEventListener('labelchange', updateHandler);
  14562. });
  14563. return _this;
  14564. }
  14565. return TrackButton;
  14566. }(MenuButton);
  14567. Component$1.registerComponent('TrackButton', TrackButton);
  14568. /**
  14569. * @file menu-keys.js
  14570. */
  14571. /**
  14572. * All keys used for operation of a menu (`MenuButton`, `Menu`, and `MenuItem`)
  14573. * Note that 'Enter' and 'Space' are not included here (otherwise they would
  14574. * prevent the `MenuButton` and `MenuItem` from being keyboard-clickable)
  14575. * @typedef MenuKeys
  14576. * @array
  14577. */
  14578. var MenuKeys = ['Tab', 'Esc', 'Up', 'Down', 'Right', 'Left'];
  14579. /**
  14580. * The component for a menu item. `<li>`
  14581. *
  14582. * @extends ClickableComponent
  14583. */
  14584. var MenuItem = /*#__PURE__*/function (_ClickableComponent) {
  14585. inheritsLoose(MenuItem, _ClickableComponent);
  14586. /**
  14587. * Creates an instance of the this class.
  14588. *
  14589. * @param {Player} player
  14590. * The `Player` that this class should be attached to.
  14591. *
  14592. * @param {Object} [options={}]
  14593. * The key/value store of player options.
  14594. *
  14595. */
  14596. function MenuItem(player, options) {
  14597. var _this;
  14598. _this = _ClickableComponent.call(this, player, options) || this;
  14599. _this.selectable = options.selectable;
  14600. _this.isSelected_ = options.selected || false;
  14601. _this.multiSelectable = options.multiSelectable;
  14602. _this.selected(_this.isSelected_);
  14603. if (_this.selectable) {
  14604. if (_this.multiSelectable) {
  14605. _this.el_.setAttribute('role', 'menuitemcheckbox');
  14606. } else {
  14607. _this.el_.setAttribute('role', 'menuitemradio');
  14608. }
  14609. } else {
  14610. _this.el_.setAttribute('role', 'menuitem');
  14611. }
  14612. return _this;
  14613. }
  14614. /**
  14615. * Create the `MenuItem's DOM element
  14616. *
  14617. * @param {string} [type=li]
  14618. * Element's node type, not actually used, always set to `li`.
  14619. *
  14620. * @param {Object} [props={}]
  14621. * An object of properties that should be set on the element
  14622. *
  14623. * @param {Object} [attrs={}]
  14624. * An object of attributes that should be set on the element
  14625. *
  14626. * @return {Element}
  14627. * The element that gets created.
  14628. */
  14629. var _proto = MenuItem.prototype;
  14630. _proto.createEl = function createEl$1(type, props, attrs) {
  14631. // The control is textual, not just an icon
  14632. this.nonIconControl = true;
  14633. var el = _ClickableComponent.prototype.createEl.call(this, 'li', assign$1({
  14634. className: 'vjs-menu-item',
  14635. tabIndex: -1
  14636. }, props), attrs); // swap icon with menu item text.
  14637. el.replaceChild(createEl('span', {
  14638. className: 'vjs-menu-item-text',
  14639. textContent: this.localize(this.options_.label)
  14640. }), el.querySelector('.vjs-icon-placeholder'));
  14641. return el;
  14642. }
  14643. /**
  14644. * Ignore keys which are used by the menu, but pass any other ones up. See
  14645. * {@link ClickableComponent#handleKeyDown} for instances where this is called.
  14646. *
  14647. * @param {EventTarget~Event} event
  14648. * The `keydown` event that caused this function to be called.
  14649. *
  14650. * @listens keydown
  14651. */
  14652. ;
  14653. _proto.handleKeyDown = function handleKeyDown(event) {
  14654. if (!MenuKeys.some(function (key) {
  14655. return keycode.isEventKey(event, key);
  14656. })) {
  14657. // Pass keydown handling up for unused keys
  14658. _ClickableComponent.prototype.handleKeyDown.call(this, event);
  14659. }
  14660. }
  14661. /**
  14662. * Any click on a `MenuItem` puts it into the selected state.
  14663. * See {@link ClickableComponent#handleClick} for instances where this is called.
  14664. *
  14665. * @param {EventTarget~Event} event
  14666. * The `keydown`, `tap`, or `click` event that caused this function to be
  14667. * called.
  14668. *
  14669. * @listens tap
  14670. * @listens click
  14671. */
  14672. ;
  14673. _proto.handleClick = function handleClick(event) {
  14674. this.selected(true);
  14675. }
  14676. /**
  14677. * Set the state for this menu item as selected or not.
  14678. *
  14679. * @param {boolean} selected
  14680. * if the menu item is selected or not
  14681. */
  14682. ;
  14683. _proto.selected = function selected(_selected) {
  14684. if (this.selectable) {
  14685. if (_selected) {
  14686. this.addClass('vjs-selected');
  14687. this.el_.setAttribute('aria-checked', 'true'); // aria-checked isn't fully supported by browsers/screen readers,
  14688. // so indicate selected state to screen reader in the control text.
  14689. this.controlText(', selected');
  14690. this.isSelected_ = true;
  14691. } else {
  14692. this.removeClass('vjs-selected');
  14693. this.el_.setAttribute('aria-checked', 'false'); // Indicate un-selected state to screen reader
  14694. this.controlText('');
  14695. this.isSelected_ = false;
  14696. }
  14697. }
  14698. };
  14699. return MenuItem;
  14700. }(ClickableComponent);
  14701. Component$1.registerComponent('MenuItem', MenuItem);
  14702. /**
  14703. * The specific menu item type for selecting a language within a text track kind
  14704. *
  14705. * @extends MenuItem
  14706. */
  14707. var TextTrackMenuItem = /*#__PURE__*/function (_MenuItem) {
  14708. inheritsLoose(TextTrackMenuItem, _MenuItem);
  14709. /**
  14710. * Creates an instance of this class.
  14711. *
  14712. * @param {Player} player
  14713. * The `Player` that this class should be attached to.
  14714. *
  14715. * @param {Object} [options]
  14716. * The key/value store of player options.
  14717. */
  14718. function TextTrackMenuItem(player, options) {
  14719. var _this;
  14720. var track = options.track;
  14721. var tracks = player.textTracks(); // Modify options for parent MenuItem class's init.
  14722. options.label = track.label || track.language || 'Unknown';
  14723. options.selected = track.mode === 'showing';
  14724. _this = _MenuItem.call(this, player, options) || this;
  14725. _this.track = track; // Determine the relevant kind(s) of tracks for this component and filter
  14726. // out empty kinds.
  14727. _this.kinds = (options.kinds || [options.kind || _this.track.kind]).filter(Boolean);
  14728. var changeHandler = function changeHandler() {
  14729. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  14730. args[_key] = arguments[_key];
  14731. }
  14732. _this.handleTracksChange.apply(assertThisInitialized(_this), args);
  14733. };
  14734. var selectedLanguageChangeHandler = function selectedLanguageChangeHandler() {
  14735. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  14736. args[_key2] = arguments[_key2];
  14737. }
  14738. _this.handleSelectedLanguageChange.apply(assertThisInitialized(_this), args);
  14739. };
  14740. player.on(['loadstart', 'texttrackchange'], changeHandler);
  14741. tracks.addEventListener('change', changeHandler);
  14742. tracks.addEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
  14743. _this.on('dispose', function () {
  14744. player.off(['loadstart', 'texttrackchange'], changeHandler);
  14745. tracks.removeEventListener('change', changeHandler);
  14746. tracks.removeEventListener('selectedlanguagechange', selectedLanguageChangeHandler);
  14747. }); // iOS7 doesn't dispatch change events to TextTrackLists when an
  14748. // associated track's mode changes. Without something like
  14749. // Object.observe() (also not present on iOS7), it's not
  14750. // possible to detect changes to the mode attribute and polyfill
  14751. // the change event. As a poor substitute, we manually dispatch
  14752. // change events whenever the controls modify the mode.
  14753. if (tracks.onchange === undefined) {
  14754. var event;
  14755. _this.on(['tap', 'click'], function () {
  14756. if (typeof window.Event !== 'object') {
  14757. // Android 2.3 throws an Illegal Constructor error for window.Event
  14758. try {
  14759. event = new window.Event('change');
  14760. } catch (err) {// continue regardless of error
  14761. }
  14762. }
  14763. if (!event) {
  14764. event = document.createEvent('Event');
  14765. event.initEvent('change', true, true);
  14766. }
  14767. tracks.dispatchEvent(event);
  14768. });
  14769. } // set the default state based on current tracks
  14770. _this.handleTracksChange();
  14771. return _this;
  14772. }
  14773. /**
  14774. * This gets called when an `TextTrackMenuItem` is "clicked". See
  14775. * {@link ClickableComponent} for more detailed information on what a click can be.
  14776. *
  14777. * @param {EventTarget~Event} event
  14778. * The `keydown`, `tap`, or `click` event that caused this function to be
  14779. * called.
  14780. *
  14781. * @listens tap
  14782. * @listens click
  14783. */
  14784. var _proto = TextTrackMenuItem.prototype;
  14785. _proto.handleClick = function handleClick(event) {
  14786. var referenceTrack = this.track;
  14787. var tracks = this.player_.textTracks();
  14788. _MenuItem.prototype.handleClick.call(this, event);
  14789. if (!tracks) {
  14790. return;
  14791. }
  14792. for (var i = 0; i < tracks.length; i++) {
  14793. var track = tracks[i]; // If the track from the text tracks list is not of the right kind,
  14794. // skip it. We do not want to affect tracks of incompatible kind(s).
  14795. if (this.kinds.indexOf(track.kind) === -1) {
  14796. continue;
  14797. } // If this text track is the component's track and it is not showing,
  14798. // set it to showing.
  14799. if (track === referenceTrack) {
  14800. if (track.mode !== 'showing') {
  14801. track.mode = 'showing';
  14802. } // If this text track is not the component's track and it is not
  14803. // disabled, set it to disabled.
  14804. } else if (track.mode !== 'disabled') {
  14805. track.mode = 'disabled';
  14806. }
  14807. }
  14808. }
  14809. /**
  14810. * Handle text track list change
  14811. *
  14812. * @param {EventTarget~Event} event
  14813. * The `change` event that caused this function to be called.
  14814. *
  14815. * @listens TextTrackList#change
  14816. */
  14817. ;
  14818. _proto.handleTracksChange = function handleTracksChange(event) {
  14819. var shouldBeSelected = this.track.mode === 'showing'; // Prevent redundant selected() calls because they may cause
  14820. // screen readers to read the appended control text unnecessarily
  14821. if (shouldBeSelected !== this.isSelected_) {
  14822. this.selected(shouldBeSelected);
  14823. }
  14824. };
  14825. _proto.handleSelectedLanguageChange = function handleSelectedLanguageChange(event) {
  14826. if (this.track.mode === 'showing') {
  14827. var selectedLanguage = this.player_.cache_.selectedLanguage; // Don't replace the kind of track across the same language
  14828. if (selectedLanguage && selectedLanguage.enabled && selectedLanguage.language === this.track.language && selectedLanguage.kind !== this.track.kind) {
  14829. return;
  14830. }
  14831. this.player_.cache_.selectedLanguage = {
  14832. enabled: true,
  14833. language: this.track.language,
  14834. kind: this.track.kind
  14835. };
  14836. }
  14837. };
  14838. _proto.dispose = function dispose() {
  14839. // remove reference to track object on dispose
  14840. this.track = null;
  14841. _MenuItem.prototype.dispose.call(this);
  14842. };
  14843. return TextTrackMenuItem;
  14844. }(MenuItem);
  14845. Component$1.registerComponent('TextTrackMenuItem', TextTrackMenuItem);
  14846. /**
  14847. * A special menu item for turning of a specific type of text track
  14848. *
  14849. * @extends TextTrackMenuItem
  14850. */
  14851. var OffTextTrackMenuItem = /*#__PURE__*/function (_TextTrackMenuItem) {
  14852. inheritsLoose(OffTextTrackMenuItem, _TextTrackMenuItem);
  14853. /**
  14854. * Creates an instance of this class.
  14855. *
  14856. * @param {Player} player
  14857. * The `Player` that this class should be attached to.
  14858. *
  14859. * @param {Object} [options]
  14860. * The key/value store of player options.
  14861. */
  14862. function OffTextTrackMenuItem(player, options) {
  14863. // Create pseudo track info
  14864. // Requires options['kind']
  14865. options.track = {
  14866. player: player,
  14867. // it is no longer necessary to store `kind` or `kinds` on the track itself
  14868. // since they are now stored in the `kinds` property of all instances of
  14869. // TextTrackMenuItem, but this will remain for backwards compatibility
  14870. kind: options.kind,
  14871. kinds: options.kinds,
  14872. "default": false,
  14873. mode: 'disabled'
  14874. };
  14875. if (!options.kinds) {
  14876. options.kinds = [options.kind];
  14877. }
  14878. if (options.label) {
  14879. options.track.label = options.label;
  14880. } else {
  14881. options.track.label = options.kinds.join(' and ') + ' off';
  14882. } // MenuItem is selectable
  14883. options.selectable = true; // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  14884. options.multiSelectable = false;
  14885. return _TextTrackMenuItem.call(this, player, options) || this;
  14886. }
  14887. /**
  14888. * Handle text track change
  14889. *
  14890. * @param {EventTarget~Event} event
  14891. * The event that caused this function to run
  14892. */
  14893. var _proto = OffTextTrackMenuItem.prototype;
  14894. _proto.handleTracksChange = function handleTracksChange(event) {
  14895. var tracks = this.player().textTracks();
  14896. var shouldBeSelected = true;
  14897. for (var i = 0, l = tracks.length; i < l; i++) {
  14898. var track = tracks[i];
  14899. if (this.options_.kinds.indexOf(track.kind) > -1 && track.mode === 'showing') {
  14900. shouldBeSelected = false;
  14901. break;
  14902. }
  14903. } // Prevent redundant selected() calls because they may cause
  14904. // screen readers to read the appended control text unnecessarily
  14905. if (shouldBeSelected !== this.isSelected_) {
  14906. this.selected(shouldBeSelected);
  14907. }
  14908. };
  14909. _proto.handleSelectedLanguageChange = function handleSelectedLanguageChange(event) {
  14910. var tracks = this.player().textTracks();
  14911. var allHidden = true;
  14912. for (var i = 0, l = tracks.length; i < l; i++) {
  14913. var track = tracks[i];
  14914. if (['captions', 'descriptions', 'subtitles'].indexOf(track.kind) > -1 && track.mode === 'showing') {
  14915. allHidden = false;
  14916. break;
  14917. }
  14918. }
  14919. if (allHidden) {
  14920. this.player_.cache_.selectedLanguage = {
  14921. enabled: false
  14922. };
  14923. }
  14924. };
  14925. return OffTextTrackMenuItem;
  14926. }(TextTrackMenuItem);
  14927. Component$1.registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem);
  14928. /**
  14929. * The base class for buttons that toggle specific text track types (e.g. subtitles)
  14930. *
  14931. * @extends MenuButton
  14932. */
  14933. var TextTrackButton = /*#__PURE__*/function (_TrackButton) {
  14934. inheritsLoose(TextTrackButton, _TrackButton);
  14935. /**
  14936. * Creates an instance of this class.
  14937. *
  14938. * @param {Player} player
  14939. * The `Player` that this class should be attached to.
  14940. *
  14941. * @param {Object} [options={}]
  14942. * The key/value store of player options.
  14943. */
  14944. function TextTrackButton(player, options) {
  14945. if (options === void 0) {
  14946. options = {};
  14947. }
  14948. options.tracks = player.textTracks();
  14949. return _TrackButton.call(this, player, options) || this;
  14950. }
  14951. /**
  14952. * Create a menu item for each text track
  14953. *
  14954. * @param {TextTrackMenuItem[]} [items=[]]
  14955. * Existing array of items to use during creation
  14956. *
  14957. * @return {TextTrackMenuItem[]}
  14958. * Array of menu items that were created
  14959. */
  14960. var _proto = TextTrackButton.prototype;
  14961. _proto.createItems = function createItems(items, TrackMenuItem) {
  14962. if (items === void 0) {
  14963. items = [];
  14964. }
  14965. if (TrackMenuItem === void 0) {
  14966. TrackMenuItem = TextTrackMenuItem;
  14967. }
  14968. // Label is an override for the [track] off label
  14969. // USed to localise captions/subtitles
  14970. var label;
  14971. if (this.label_) {
  14972. label = this.label_ + " off";
  14973. } // Add an OFF menu item to turn all tracks off
  14974. items.push(new OffTextTrackMenuItem(this.player_, {
  14975. kinds: this.kinds_,
  14976. kind: this.kind_,
  14977. label: label
  14978. }));
  14979. this.hideThreshold_ += 1;
  14980. var tracks = this.player_.textTracks();
  14981. if (!Array.isArray(this.kinds_)) {
  14982. this.kinds_ = [this.kind_];
  14983. }
  14984. for (var i = 0; i < tracks.length; i++) {
  14985. var track = tracks[i]; // only add tracks that are of an appropriate kind and have a label
  14986. if (this.kinds_.indexOf(track.kind) > -1) {
  14987. var item = new TrackMenuItem(this.player_, {
  14988. track: track,
  14989. kinds: this.kinds_,
  14990. kind: this.kind_,
  14991. // MenuItem is selectable
  14992. selectable: true,
  14993. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  14994. multiSelectable: false
  14995. });
  14996. item.addClass("vjs-" + track.kind + "-menu-item");
  14997. items.push(item);
  14998. }
  14999. }
  15000. return items;
  15001. };
  15002. return TextTrackButton;
  15003. }(TrackButton);
  15004. Component$1.registerComponent('TextTrackButton', TextTrackButton);
  15005. /**
  15006. * The chapter track menu item
  15007. *
  15008. * @extends MenuItem
  15009. */
  15010. var ChaptersTrackMenuItem = /*#__PURE__*/function (_MenuItem) {
  15011. inheritsLoose(ChaptersTrackMenuItem, _MenuItem);
  15012. /**
  15013. * Creates an instance of this class.
  15014. *
  15015. * @param {Player} player
  15016. * The `Player` that this class should be attached to.
  15017. *
  15018. * @param {Object} [options]
  15019. * The key/value store of player options.
  15020. */
  15021. function ChaptersTrackMenuItem(player, options) {
  15022. var _this;
  15023. var track = options.track;
  15024. var cue = options.cue;
  15025. var currentTime = player.currentTime(); // Modify options for parent MenuItem class's init.
  15026. options.selectable = true;
  15027. options.multiSelectable = false;
  15028. options.label = cue.text;
  15029. options.selected = cue.startTime <= currentTime && currentTime < cue.endTime;
  15030. _this = _MenuItem.call(this, player, options) || this;
  15031. _this.track = track;
  15032. _this.cue = cue;
  15033. return _this;
  15034. }
  15035. /**
  15036. * This gets called when an `ChaptersTrackMenuItem` is "clicked". See
  15037. * {@link ClickableComponent} for more detailed information on what a click can be.
  15038. *
  15039. * @param {EventTarget~Event} [event]
  15040. * The `keydown`, `tap`, or `click` event that caused this function to be
  15041. * called.
  15042. *
  15043. * @listens tap
  15044. * @listens click
  15045. */
  15046. var _proto = ChaptersTrackMenuItem.prototype;
  15047. _proto.handleClick = function handleClick(event) {
  15048. _MenuItem.prototype.handleClick.call(this);
  15049. this.player_.currentTime(this.cue.startTime);
  15050. };
  15051. return ChaptersTrackMenuItem;
  15052. }(MenuItem);
  15053. Component$1.registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem);
  15054. /**
  15055. * The button component for toggling and selecting chapters
  15056. * Chapters act much differently than other text tracks
  15057. * Cues are navigation vs. other tracks of alternative languages
  15058. *
  15059. * @extends TextTrackButton
  15060. */
  15061. var ChaptersButton = /*#__PURE__*/function (_TextTrackButton) {
  15062. inheritsLoose(ChaptersButton, _TextTrackButton);
  15063. /**
  15064. * Creates an instance of this class.
  15065. *
  15066. * @param {Player} player
  15067. * The `Player` that this class should be attached to.
  15068. *
  15069. * @param {Object} [options]
  15070. * The key/value store of player options.
  15071. *
  15072. * @param {Component~ReadyCallback} [ready]
  15073. * The function to call when this function is ready.
  15074. */
  15075. function ChaptersButton(player, options, ready) {
  15076. var _this;
  15077. _this = _TextTrackButton.call(this, player, options, ready) || this;
  15078. _this.selectCurrentItem_ = function () {
  15079. _this.items.forEach(function (item) {
  15080. item.selected(_this.track_.activeCues[0] === item.cue);
  15081. });
  15082. };
  15083. return _this;
  15084. }
  15085. /**
  15086. * Builds the default DOM `className`.
  15087. *
  15088. * @return {string}
  15089. * The DOM `className` for this object.
  15090. */
  15091. var _proto = ChaptersButton.prototype;
  15092. _proto.buildCSSClass = function buildCSSClass() {
  15093. return "vjs-chapters-button " + _TextTrackButton.prototype.buildCSSClass.call(this);
  15094. };
  15095. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  15096. return "vjs-chapters-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
  15097. }
  15098. /**
  15099. * Update the menu based on the current state of its items.
  15100. *
  15101. * @param {EventTarget~Event} [event]
  15102. * An event that triggered this function to run.
  15103. *
  15104. * @listens TextTrackList#addtrack
  15105. * @listens TextTrackList#removetrack
  15106. * @listens TextTrackList#change
  15107. */
  15108. ;
  15109. _proto.update = function update(event) {
  15110. if (event && event.track && event.track.kind !== 'chapters') {
  15111. return;
  15112. }
  15113. var track = this.findChaptersTrack();
  15114. if (track !== this.track_) {
  15115. this.setTrack(track);
  15116. _TextTrackButton.prototype.update.call(this);
  15117. } else if (!this.items || track && track.cues && track.cues.length !== this.items.length) {
  15118. // Update the menu initially or if the number of cues has changed since set
  15119. _TextTrackButton.prototype.update.call(this);
  15120. }
  15121. }
  15122. /**
  15123. * Set the currently selected track for the chapters button.
  15124. *
  15125. * @param {TextTrack} track
  15126. * The new track to select. Nothing will change if this is the currently selected
  15127. * track.
  15128. */
  15129. ;
  15130. _proto.setTrack = function setTrack(track) {
  15131. if (this.track_ === track) {
  15132. return;
  15133. }
  15134. if (!this.updateHandler_) {
  15135. this.updateHandler_ = this.update.bind(this);
  15136. } // here this.track_ refers to the old track instance
  15137. if (this.track_) {
  15138. var remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
  15139. if (remoteTextTrackEl) {
  15140. remoteTextTrackEl.removeEventListener('load', this.updateHandler_);
  15141. }
  15142. this.track_.removeEventListener('cuechange', this.selectCurrentItem_);
  15143. this.track_ = null;
  15144. }
  15145. this.track_ = track; // here this.track_ refers to the new track instance
  15146. if (this.track_) {
  15147. this.track_.mode = 'hidden';
  15148. var _remoteTextTrackEl = this.player_.remoteTextTrackEls().getTrackElementByTrack_(this.track_);
  15149. if (_remoteTextTrackEl) {
  15150. _remoteTextTrackEl.addEventListener('load', this.updateHandler_);
  15151. }
  15152. this.track_.addEventListener('cuechange', this.selectCurrentItem_);
  15153. }
  15154. }
  15155. /**
  15156. * Find the track object that is currently in use by this ChaptersButton
  15157. *
  15158. * @return {TextTrack|undefined}
  15159. * The current track or undefined if none was found.
  15160. */
  15161. ;
  15162. _proto.findChaptersTrack = function findChaptersTrack() {
  15163. var tracks = this.player_.textTracks() || [];
  15164. for (var i = tracks.length - 1; i >= 0; i--) {
  15165. // We will always choose the last track as our chaptersTrack
  15166. var track = tracks[i];
  15167. if (track.kind === this.kind_) {
  15168. return track;
  15169. }
  15170. }
  15171. }
  15172. /**
  15173. * Get the caption for the ChaptersButton based on the track label. This will also
  15174. * use the current tracks localized kind as a fallback if a label does not exist.
  15175. *
  15176. * @return {string}
  15177. * The tracks current label or the localized track kind.
  15178. */
  15179. ;
  15180. _proto.getMenuCaption = function getMenuCaption() {
  15181. if (this.track_ && this.track_.label) {
  15182. return this.track_.label;
  15183. }
  15184. return this.localize(toTitleCase$1(this.kind_));
  15185. }
  15186. /**
  15187. * Create menu from chapter track
  15188. *
  15189. * @return {Menu}
  15190. * New menu for the chapter buttons
  15191. */
  15192. ;
  15193. _proto.createMenu = function createMenu() {
  15194. this.options_.title = this.getMenuCaption();
  15195. return _TextTrackButton.prototype.createMenu.call(this);
  15196. }
  15197. /**
  15198. * Create a menu item for each text track
  15199. *
  15200. * @return {TextTrackMenuItem[]}
  15201. * Array of menu items
  15202. */
  15203. ;
  15204. _proto.createItems = function createItems() {
  15205. var items = [];
  15206. if (!this.track_) {
  15207. return items;
  15208. }
  15209. var cues = this.track_.cues;
  15210. if (!cues) {
  15211. return items;
  15212. }
  15213. for (var i = 0, l = cues.length; i < l; i++) {
  15214. var cue = cues[i];
  15215. var mi = new ChaptersTrackMenuItem(this.player_, {
  15216. track: this.track_,
  15217. cue: cue
  15218. });
  15219. items.push(mi);
  15220. }
  15221. return items;
  15222. };
  15223. return ChaptersButton;
  15224. }(TextTrackButton);
  15225. /**
  15226. * `kind` of TextTrack to look for to associate it with this menu.
  15227. *
  15228. * @type {string}
  15229. * @private
  15230. */
  15231. ChaptersButton.prototype.kind_ = 'chapters';
  15232. /**
  15233. * The text that should display over the `ChaptersButton`s controls. Added for localization.
  15234. *
  15235. * @type {string}
  15236. * @private
  15237. */
  15238. ChaptersButton.prototype.controlText_ = 'Chapters';
  15239. Component$1.registerComponent('ChaptersButton', ChaptersButton);
  15240. /**
  15241. * The button component for toggling and selecting descriptions
  15242. *
  15243. * @extends TextTrackButton
  15244. */
  15245. var DescriptionsButton = /*#__PURE__*/function (_TextTrackButton) {
  15246. inheritsLoose(DescriptionsButton, _TextTrackButton);
  15247. /**
  15248. * Creates an instance of this class.
  15249. *
  15250. * @param {Player} player
  15251. * The `Player` that this class should be attached to.
  15252. *
  15253. * @param {Object} [options]
  15254. * The key/value store of player options.
  15255. *
  15256. * @param {Component~ReadyCallback} [ready]
  15257. * The function to call when this component is ready.
  15258. */
  15259. function DescriptionsButton(player, options, ready) {
  15260. var _this;
  15261. _this = _TextTrackButton.call(this, player, options, ready) || this;
  15262. var tracks = player.textTracks();
  15263. var changeHandler = bind(assertThisInitialized(_this), _this.handleTracksChange);
  15264. tracks.addEventListener('change', changeHandler);
  15265. _this.on('dispose', function () {
  15266. tracks.removeEventListener('change', changeHandler);
  15267. });
  15268. return _this;
  15269. }
  15270. /**
  15271. * Handle text track change
  15272. *
  15273. * @param {EventTarget~Event} event
  15274. * The event that caused this function to run
  15275. *
  15276. * @listens TextTrackList#change
  15277. */
  15278. var _proto = DescriptionsButton.prototype;
  15279. _proto.handleTracksChange = function handleTracksChange(event) {
  15280. var tracks = this.player().textTracks();
  15281. var disabled = false; // Check whether a track of a different kind is showing
  15282. for (var i = 0, l = tracks.length; i < l; i++) {
  15283. var track = tracks[i];
  15284. if (track.kind !== this.kind_ && track.mode === 'showing') {
  15285. disabled = true;
  15286. break;
  15287. }
  15288. } // If another track is showing, disable this menu button
  15289. if (disabled) {
  15290. this.disable();
  15291. } else {
  15292. this.enable();
  15293. }
  15294. }
  15295. /**
  15296. * Builds the default DOM `className`.
  15297. *
  15298. * @return {string}
  15299. * The DOM `className` for this object.
  15300. */
  15301. ;
  15302. _proto.buildCSSClass = function buildCSSClass() {
  15303. return "vjs-descriptions-button " + _TextTrackButton.prototype.buildCSSClass.call(this);
  15304. };
  15305. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  15306. return "vjs-descriptions-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
  15307. };
  15308. return DescriptionsButton;
  15309. }(TextTrackButton);
  15310. /**
  15311. * `kind` of TextTrack to look for to associate it with this menu.
  15312. *
  15313. * @type {string}
  15314. * @private
  15315. */
  15316. DescriptionsButton.prototype.kind_ = 'descriptions';
  15317. /**
  15318. * The text that should display over the `DescriptionsButton`s controls. Added for localization.
  15319. *
  15320. * @type {string}
  15321. * @private
  15322. */
  15323. DescriptionsButton.prototype.controlText_ = 'Descriptions';
  15324. Component$1.registerComponent('DescriptionsButton', DescriptionsButton);
  15325. /**
  15326. * The button component for toggling and selecting subtitles
  15327. *
  15328. * @extends TextTrackButton
  15329. */
  15330. var SubtitlesButton = /*#__PURE__*/function (_TextTrackButton) {
  15331. inheritsLoose(SubtitlesButton, _TextTrackButton);
  15332. /**
  15333. * Creates an instance of this class.
  15334. *
  15335. * @param {Player} player
  15336. * The `Player` that this class should be attached to.
  15337. *
  15338. * @param {Object} [options]
  15339. * The key/value store of player options.
  15340. *
  15341. * @param {Component~ReadyCallback} [ready]
  15342. * The function to call when this component is ready.
  15343. */
  15344. function SubtitlesButton(player, options, ready) {
  15345. return _TextTrackButton.call(this, player, options, ready) || this;
  15346. }
  15347. /**
  15348. * Builds the default DOM `className`.
  15349. *
  15350. * @return {string}
  15351. * The DOM `className` for this object.
  15352. */
  15353. var _proto = SubtitlesButton.prototype;
  15354. _proto.buildCSSClass = function buildCSSClass() {
  15355. return "vjs-subtitles-button " + _TextTrackButton.prototype.buildCSSClass.call(this);
  15356. };
  15357. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  15358. return "vjs-subtitles-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
  15359. };
  15360. return SubtitlesButton;
  15361. }(TextTrackButton);
  15362. /**
  15363. * `kind` of TextTrack to look for to associate it with this menu.
  15364. *
  15365. * @type {string}
  15366. * @private
  15367. */
  15368. SubtitlesButton.prototype.kind_ = 'subtitles';
  15369. /**
  15370. * The text that should display over the `SubtitlesButton`s controls. Added for localization.
  15371. *
  15372. * @type {string}
  15373. * @private
  15374. */
  15375. SubtitlesButton.prototype.controlText_ = 'Subtitles';
  15376. Component$1.registerComponent('SubtitlesButton', SubtitlesButton);
  15377. /**
  15378. * The menu item for caption track settings menu
  15379. *
  15380. * @extends TextTrackMenuItem
  15381. */
  15382. var CaptionSettingsMenuItem = /*#__PURE__*/function (_TextTrackMenuItem) {
  15383. inheritsLoose(CaptionSettingsMenuItem, _TextTrackMenuItem);
  15384. /**
  15385. * Creates an instance of this class.
  15386. *
  15387. * @param {Player} player
  15388. * The `Player` that this class should be attached to.
  15389. *
  15390. * @param {Object} [options]
  15391. * The key/value store of player options.
  15392. */
  15393. function CaptionSettingsMenuItem(player, options) {
  15394. var _this;
  15395. options.track = {
  15396. player: player,
  15397. kind: options.kind,
  15398. label: options.kind + ' settings',
  15399. selectable: false,
  15400. "default": false,
  15401. mode: 'disabled'
  15402. }; // CaptionSettingsMenuItem has no concept of 'selected'
  15403. options.selectable = false;
  15404. options.name = 'CaptionSettingsMenuItem';
  15405. _this = _TextTrackMenuItem.call(this, player, options) || this;
  15406. _this.addClass('vjs-texttrack-settings');
  15407. _this.controlText(', opens ' + options.kind + ' settings dialog');
  15408. return _this;
  15409. }
  15410. /**
  15411. * This gets called when an `CaptionSettingsMenuItem` is "clicked". See
  15412. * {@link ClickableComponent} for more detailed information on what a click can be.
  15413. *
  15414. * @param {EventTarget~Event} [event]
  15415. * The `keydown`, `tap`, or `click` event that caused this function to be
  15416. * called.
  15417. *
  15418. * @listens tap
  15419. * @listens click
  15420. */
  15421. var _proto = CaptionSettingsMenuItem.prototype;
  15422. _proto.handleClick = function handleClick(event) {
  15423. this.player().getChild('textTrackSettings').open();
  15424. };
  15425. return CaptionSettingsMenuItem;
  15426. }(TextTrackMenuItem);
  15427. Component$1.registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem);
  15428. /**
  15429. * The button component for toggling and selecting captions
  15430. *
  15431. * @extends TextTrackButton
  15432. */
  15433. var CaptionsButton = /*#__PURE__*/function (_TextTrackButton) {
  15434. inheritsLoose(CaptionsButton, _TextTrackButton);
  15435. /**
  15436. * Creates an instance of this class.
  15437. *
  15438. * @param {Player} player
  15439. * The `Player` that this class should be attached to.
  15440. *
  15441. * @param {Object} [options]
  15442. * The key/value store of player options.
  15443. *
  15444. * @param {Component~ReadyCallback} [ready]
  15445. * The function to call when this component is ready.
  15446. */
  15447. function CaptionsButton(player, options, ready) {
  15448. return _TextTrackButton.call(this, player, options, ready) || this;
  15449. }
  15450. /**
  15451. * Builds the default DOM `className`.
  15452. *
  15453. * @return {string}
  15454. * The DOM `className` for this object.
  15455. */
  15456. var _proto = CaptionsButton.prototype;
  15457. _proto.buildCSSClass = function buildCSSClass() {
  15458. return "vjs-captions-button " + _TextTrackButton.prototype.buildCSSClass.call(this);
  15459. };
  15460. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  15461. return "vjs-captions-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
  15462. }
  15463. /**
  15464. * Create caption menu items
  15465. *
  15466. * @return {CaptionSettingsMenuItem[]}
  15467. * The array of current menu items.
  15468. */
  15469. ;
  15470. _proto.createItems = function createItems() {
  15471. var items = [];
  15472. if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
  15473. items.push(new CaptionSettingsMenuItem(this.player_, {
  15474. kind: this.kind_
  15475. }));
  15476. this.hideThreshold_ += 1;
  15477. }
  15478. return _TextTrackButton.prototype.createItems.call(this, items);
  15479. };
  15480. return CaptionsButton;
  15481. }(TextTrackButton);
  15482. /**
  15483. * `kind` of TextTrack to look for to associate it with this menu.
  15484. *
  15485. * @type {string}
  15486. * @private
  15487. */
  15488. CaptionsButton.prototype.kind_ = 'captions';
  15489. /**
  15490. * The text that should display over the `CaptionsButton`s controls. Added for localization.
  15491. *
  15492. * @type {string}
  15493. * @private
  15494. */
  15495. CaptionsButton.prototype.controlText_ = 'Captions';
  15496. Component$1.registerComponent('CaptionsButton', CaptionsButton);
  15497. /**
  15498. * SubsCapsMenuItem has an [cc] icon to distinguish captions from subtitles
  15499. * in the SubsCapsMenu.
  15500. *
  15501. * @extends TextTrackMenuItem
  15502. */
  15503. var SubsCapsMenuItem = /*#__PURE__*/function (_TextTrackMenuItem) {
  15504. inheritsLoose(SubsCapsMenuItem, _TextTrackMenuItem);
  15505. function SubsCapsMenuItem() {
  15506. return _TextTrackMenuItem.apply(this, arguments) || this;
  15507. }
  15508. var _proto = SubsCapsMenuItem.prototype;
  15509. _proto.createEl = function createEl$1(type, props, attrs) {
  15510. var el = _TextTrackMenuItem.prototype.createEl.call(this, type, props, attrs);
  15511. var parentSpan = el.querySelector('.vjs-menu-item-text');
  15512. if (this.options_.track.kind === 'captions') {
  15513. parentSpan.appendChild(createEl('span', {
  15514. className: 'vjs-icon-placeholder'
  15515. }, {
  15516. 'aria-hidden': true
  15517. }));
  15518. parentSpan.appendChild(createEl('span', {
  15519. className: 'vjs-control-text',
  15520. // space added as the text will visually flow with the
  15521. // label
  15522. textContent: " " + this.localize('Captions')
  15523. }));
  15524. }
  15525. return el;
  15526. };
  15527. return SubsCapsMenuItem;
  15528. }(TextTrackMenuItem);
  15529. Component$1.registerComponent('SubsCapsMenuItem', SubsCapsMenuItem);
  15530. /**
  15531. * The button component for toggling and selecting captions and/or subtitles
  15532. *
  15533. * @extends TextTrackButton
  15534. */
  15535. var SubsCapsButton = /*#__PURE__*/function (_TextTrackButton) {
  15536. inheritsLoose(SubsCapsButton, _TextTrackButton);
  15537. function SubsCapsButton(player, options) {
  15538. var _this;
  15539. if (options === void 0) {
  15540. options = {};
  15541. }
  15542. _this = _TextTrackButton.call(this, player, options) || this; // Although North America uses "captions" in most cases for
  15543. // "captions and subtitles" other locales use "subtitles"
  15544. _this.label_ = 'subtitles';
  15545. if (['en', 'en-us', 'en-ca', 'fr-ca'].indexOf(_this.player_.language_) > -1) {
  15546. _this.label_ = 'captions';
  15547. }
  15548. _this.menuButton_.controlText(toTitleCase$1(_this.label_));
  15549. return _this;
  15550. }
  15551. /**
  15552. * Builds the default DOM `className`.
  15553. *
  15554. * @return {string}
  15555. * The DOM `className` for this object.
  15556. */
  15557. var _proto = SubsCapsButton.prototype;
  15558. _proto.buildCSSClass = function buildCSSClass() {
  15559. return "vjs-subs-caps-button " + _TextTrackButton.prototype.buildCSSClass.call(this);
  15560. };
  15561. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  15562. return "vjs-subs-caps-button " + _TextTrackButton.prototype.buildWrapperCSSClass.call(this);
  15563. }
  15564. /**
  15565. * Create caption/subtitles menu items
  15566. *
  15567. * @return {CaptionSettingsMenuItem[]}
  15568. * The array of current menu items.
  15569. */
  15570. ;
  15571. _proto.createItems = function createItems() {
  15572. var items = [];
  15573. if (!(this.player().tech_ && this.player().tech_.featuresNativeTextTracks) && this.player().getChild('textTrackSettings')) {
  15574. items.push(new CaptionSettingsMenuItem(this.player_, {
  15575. kind: this.label_
  15576. }));
  15577. this.hideThreshold_ += 1;
  15578. }
  15579. items = _TextTrackButton.prototype.createItems.call(this, items, SubsCapsMenuItem);
  15580. return items;
  15581. };
  15582. return SubsCapsButton;
  15583. }(TextTrackButton);
  15584. /**
  15585. * `kind`s of TextTrack to look for to associate it with this menu.
  15586. *
  15587. * @type {array}
  15588. * @private
  15589. */
  15590. SubsCapsButton.prototype.kinds_ = ['captions', 'subtitles'];
  15591. /**
  15592. * The text that should display over the `SubsCapsButton`s controls.
  15593. *
  15594. *
  15595. * @type {string}
  15596. * @private
  15597. */
  15598. SubsCapsButton.prototype.controlText_ = 'Subtitles';
  15599. Component$1.registerComponent('SubsCapsButton', SubsCapsButton);
  15600. /**
  15601. * An {@link AudioTrack} {@link MenuItem}
  15602. *
  15603. * @extends MenuItem
  15604. */
  15605. var AudioTrackMenuItem = /*#__PURE__*/function (_MenuItem) {
  15606. inheritsLoose(AudioTrackMenuItem, _MenuItem);
  15607. /**
  15608. * Creates an instance of this class.
  15609. *
  15610. * @param {Player} player
  15611. * The `Player` that this class should be attached to.
  15612. *
  15613. * @param {Object} [options]
  15614. * The key/value store of player options.
  15615. */
  15616. function AudioTrackMenuItem(player, options) {
  15617. var _this;
  15618. var track = options.track;
  15619. var tracks = player.audioTracks(); // Modify options for parent MenuItem class's init.
  15620. options.label = track.label || track.language || 'Unknown';
  15621. options.selected = track.enabled;
  15622. _this = _MenuItem.call(this, player, options) || this;
  15623. _this.track = track;
  15624. _this.addClass("vjs-" + track.kind + "-menu-item");
  15625. var changeHandler = function changeHandler() {
  15626. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  15627. args[_key] = arguments[_key];
  15628. }
  15629. _this.handleTracksChange.apply(assertThisInitialized(_this), args);
  15630. };
  15631. tracks.addEventListener('change', changeHandler);
  15632. _this.on('dispose', function () {
  15633. tracks.removeEventListener('change', changeHandler);
  15634. });
  15635. return _this;
  15636. }
  15637. var _proto = AudioTrackMenuItem.prototype;
  15638. _proto.createEl = function createEl$1(type, props, attrs) {
  15639. var el = _MenuItem.prototype.createEl.call(this, type, props, attrs);
  15640. var parentSpan = el.querySelector('.vjs-menu-item-text');
  15641. if (this.options_.track.kind === 'main-desc') {
  15642. parentSpan.appendChild(createEl('span', {
  15643. className: 'vjs-icon-placeholder'
  15644. }, {
  15645. 'aria-hidden': true
  15646. }));
  15647. parentSpan.appendChild(createEl('span', {
  15648. className: 'vjs-control-text',
  15649. textContent: ' ' + this.localize('Descriptions')
  15650. }));
  15651. }
  15652. return el;
  15653. }
  15654. /**
  15655. * This gets called when an `AudioTrackMenuItem is "clicked". See {@link ClickableComponent}
  15656. * for more detailed information on what a click can be.
  15657. *
  15658. * @param {EventTarget~Event} [event]
  15659. * The `keydown`, `tap`, or `click` event that caused this function to be
  15660. * called.
  15661. *
  15662. * @listens tap
  15663. * @listens click
  15664. */
  15665. ;
  15666. _proto.handleClick = function handleClick(event) {
  15667. _MenuItem.prototype.handleClick.call(this, event); // the audio track list will automatically toggle other tracks
  15668. // off for us.
  15669. this.track.enabled = true; // when native audio tracks are used, we want to make sure that other tracks are turned off
  15670. if (this.player_.tech_.featuresNativeAudioTracks) {
  15671. var tracks = this.player_.audioTracks();
  15672. for (var i = 0; i < tracks.length; i++) {
  15673. var track = tracks[i]; // skip the current track since we enabled it above
  15674. if (track === this.track) {
  15675. continue;
  15676. }
  15677. track.enabled = track === this.track;
  15678. }
  15679. }
  15680. }
  15681. /**
  15682. * Handle any {@link AudioTrack} change.
  15683. *
  15684. * @param {EventTarget~Event} [event]
  15685. * The {@link AudioTrackList#change} event that caused this to run.
  15686. *
  15687. * @listens AudioTrackList#change
  15688. */
  15689. ;
  15690. _proto.handleTracksChange = function handleTracksChange(event) {
  15691. this.selected(this.track.enabled);
  15692. };
  15693. return AudioTrackMenuItem;
  15694. }(MenuItem);
  15695. Component$1.registerComponent('AudioTrackMenuItem', AudioTrackMenuItem);
  15696. /**
  15697. * The base class for buttons that toggle specific {@link AudioTrack} types.
  15698. *
  15699. * @extends TrackButton
  15700. */
  15701. var AudioTrackButton = /*#__PURE__*/function (_TrackButton) {
  15702. inheritsLoose(AudioTrackButton, _TrackButton);
  15703. /**
  15704. * Creates an instance of this class.
  15705. *
  15706. * @param {Player} player
  15707. * The `Player` that this class should be attached to.
  15708. *
  15709. * @param {Object} [options={}]
  15710. * The key/value store of player options.
  15711. */
  15712. function AudioTrackButton(player, options) {
  15713. if (options === void 0) {
  15714. options = {};
  15715. }
  15716. options.tracks = player.audioTracks();
  15717. return _TrackButton.call(this, player, options) || this;
  15718. }
  15719. /**
  15720. * Builds the default DOM `className`.
  15721. *
  15722. * @return {string}
  15723. * The DOM `className` for this object.
  15724. */
  15725. var _proto = AudioTrackButton.prototype;
  15726. _proto.buildCSSClass = function buildCSSClass() {
  15727. return "vjs-audio-button " + _TrackButton.prototype.buildCSSClass.call(this);
  15728. };
  15729. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  15730. return "vjs-audio-button " + _TrackButton.prototype.buildWrapperCSSClass.call(this);
  15731. }
  15732. /**
  15733. * Create a menu item for each audio track
  15734. *
  15735. * @param {AudioTrackMenuItem[]} [items=[]]
  15736. * An array of existing menu items to use.
  15737. *
  15738. * @return {AudioTrackMenuItem[]}
  15739. * An array of menu items
  15740. */
  15741. ;
  15742. _proto.createItems = function createItems(items) {
  15743. if (items === void 0) {
  15744. items = [];
  15745. }
  15746. // if there's only one audio track, there no point in showing it
  15747. this.hideThreshold_ = 1;
  15748. var tracks = this.player_.audioTracks();
  15749. for (var i = 0; i < tracks.length; i++) {
  15750. var track = tracks[i];
  15751. items.push(new AudioTrackMenuItem(this.player_, {
  15752. track: track,
  15753. // MenuItem is selectable
  15754. selectable: true,
  15755. // MenuItem is NOT multiSelectable (i.e. only one can be marked "selected" at a time)
  15756. multiSelectable: false
  15757. }));
  15758. }
  15759. return items;
  15760. };
  15761. return AudioTrackButton;
  15762. }(TrackButton);
  15763. /**
  15764. * The text that should display over the `AudioTrackButton`s controls. Added for localization.
  15765. *
  15766. * @type {string}
  15767. * @private
  15768. */
  15769. AudioTrackButton.prototype.controlText_ = 'Audio Track';
  15770. Component$1.registerComponent('AudioTrackButton', AudioTrackButton);
  15771. /**
  15772. * The specific menu item type for selecting a playback rate.
  15773. *
  15774. * @extends MenuItem
  15775. */
  15776. var PlaybackRateMenuItem = /*#__PURE__*/function (_MenuItem) {
  15777. inheritsLoose(PlaybackRateMenuItem, _MenuItem);
  15778. /**
  15779. * Creates an instance of this class.
  15780. *
  15781. * @param {Player} player
  15782. * The `Player` that this class should be attached to.
  15783. *
  15784. * @param {Object} [options]
  15785. * The key/value store of player options.
  15786. */
  15787. function PlaybackRateMenuItem(player, options) {
  15788. var _this;
  15789. var label = options.rate;
  15790. var rate = parseFloat(label, 10); // Modify options for parent MenuItem class's init.
  15791. options.label = label;
  15792. options.selected = rate === player.playbackRate();
  15793. options.selectable = true;
  15794. options.multiSelectable = false;
  15795. _this = _MenuItem.call(this, player, options) || this;
  15796. _this.label = label;
  15797. _this.rate = rate;
  15798. _this.on(player, 'ratechange', function (e) {
  15799. return _this.update(e);
  15800. });
  15801. return _this;
  15802. }
  15803. /**
  15804. * This gets called when an `PlaybackRateMenuItem` is "clicked". See
  15805. * {@link ClickableComponent} for more detailed information on what a click can be.
  15806. *
  15807. * @param {EventTarget~Event} [event]
  15808. * The `keydown`, `tap`, or `click` event that caused this function to be
  15809. * called.
  15810. *
  15811. * @listens tap
  15812. * @listens click
  15813. */
  15814. var _proto = PlaybackRateMenuItem.prototype;
  15815. _proto.handleClick = function handleClick(event) {
  15816. _MenuItem.prototype.handleClick.call(this);
  15817. this.player().playbackRate(this.rate);
  15818. }
  15819. /**
  15820. * Update the PlaybackRateMenuItem when the playbackrate changes.
  15821. *
  15822. * @param {EventTarget~Event} [event]
  15823. * The `ratechange` event that caused this function to run.
  15824. *
  15825. * @listens Player#ratechange
  15826. */
  15827. ;
  15828. _proto.update = function update(event) {
  15829. this.selected(this.player().playbackRate() === this.rate);
  15830. };
  15831. return PlaybackRateMenuItem;
  15832. }(MenuItem);
  15833. /**
  15834. * The text that should display over the `PlaybackRateMenuItem`s controls. Added for localization.
  15835. *
  15836. * @type {string}
  15837. * @private
  15838. */
  15839. PlaybackRateMenuItem.prototype.contentElType = 'button';
  15840. Component$1.registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem);
  15841. /**
  15842. * The component for controlling the playback rate.
  15843. *
  15844. * @extends MenuButton
  15845. */
  15846. var PlaybackRateMenuButton = /*#__PURE__*/function (_MenuButton) {
  15847. inheritsLoose(PlaybackRateMenuButton, _MenuButton);
  15848. /**
  15849. * Creates an instance of this class.
  15850. *
  15851. * @param {Player} player
  15852. * The `Player` that this class should be attached to.
  15853. *
  15854. * @param {Object} [options]
  15855. * The key/value store of player options.
  15856. */
  15857. function PlaybackRateMenuButton(player, options) {
  15858. var _this;
  15859. _this = _MenuButton.call(this, player, options) || this;
  15860. _this.menuButton_.el_.setAttribute('aria-describedby', _this.labelElId_);
  15861. _this.updateVisibility();
  15862. _this.updateLabel();
  15863. _this.on(player, 'loadstart', function (e) {
  15864. return _this.updateVisibility(e);
  15865. });
  15866. _this.on(player, 'ratechange', function (e) {
  15867. return _this.updateLabel(e);
  15868. });
  15869. _this.on(player, 'playbackrateschange', function (e) {
  15870. return _this.handlePlaybackRateschange(e);
  15871. });
  15872. return _this;
  15873. }
  15874. /**
  15875. * Create the `Component`'s DOM element
  15876. *
  15877. * @return {Element}
  15878. * The element that was created.
  15879. */
  15880. var _proto = PlaybackRateMenuButton.prototype;
  15881. _proto.createEl = function createEl$1() {
  15882. var el = _MenuButton.prototype.createEl.call(this);
  15883. this.labelElId_ = 'vjs-playback-rate-value-label-' + this.id_;
  15884. this.labelEl_ = createEl('div', {
  15885. className: 'vjs-playback-rate-value',
  15886. id: this.labelElId_,
  15887. textContent: '1x'
  15888. });
  15889. el.appendChild(this.labelEl_);
  15890. return el;
  15891. };
  15892. _proto.dispose = function dispose() {
  15893. this.labelEl_ = null;
  15894. _MenuButton.prototype.dispose.call(this);
  15895. }
  15896. /**
  15897. * Builds the default DOM `className`.
  15898. *
  15899. * @return {string}
  15900. * The DOM `className` for this object.
  15901. */
  15902. ;
  15903. _proto.buildCSSClass = function buildCSSClass() {
  15904. return "vjs-playback-rate " + _MenuButton.prototype.buildCSSClass.call(this);
  15905. };
  15906. _proto.buildWrapperCSSClass = function buildWrapperCSSClass() {
  15907. return "vjs-playback-rate " + _MenuButton.prototype.buildWrapperCSSClass.call(this);
  15908. }
  15909. /**
  15910. * Create the list of menu items. Specific to each subclass.
  15911. *
  15912. */
  15913. ;
  15914. _proto.createItems = function createItems() {
  15915. var rates = this.playbackRates();
  15916. var items = [];
  15917. for (var i = rates.length - 1; i >= 0; i--) {
  15918. items.push(new PlaybackRateMenuItem(this.player(), {
  15919. rate: rates[i] + 'x'
  15920. }));
  15921. }
  15922. return items;
  15923. }
  15924. /**
  15925. * Updates ARIA accessibility attributes
  15926. */
  15927. ;
  15928. _proto.updateARIAAttributes = function updateARIAAttributes() {
  15929. // Current playback rate
  15930. this.el().setAttribute('aria-valuenow', this.player().playbackRate());
  15931. }
  15932. /**
  15933. * This gets called when an `PlaybackRateMenuButton` is "clicked". See
  15934. * {@link ClickableComponent} for more detailed information on what a click can be.
  15935. *
  15936. * @param {EventTarget~Event} [event]
  15937. * The `keydown`, `tap`, or `click` event that caused this function to be
  15938. * called.
  15939. *
  15940. * @listens tap
  15941. * @listens click
  15942. */
  15943. ;
  15944. _proto.handleClick = function handleClick(event) {
  15945. // select next rate option
  15946. var currentRate = this.player().playbackRate();
  15947. var rates = this.playbackRates();
  15948. var currentIndex = rates.indexOf(currentRate); // this get the next rate and it will select first one if the last one currently selected
  15949. var newIndex = (currentIndex + 1) % rates.length;
  15950. this.player().playbackRate(rates[newIndex]);
  15951. }
  15952. /**
  15953. * On playbackrateschange, update the menu to account for the new items.
  15954. *
  15955. * @listens Player#playbackrateschange
  15956. */
  15957. ;
  15958. _proto.handlePlaybackRateschange = function handlePlaybackRateschange(event) {
  15959. this.update();
  15960. }
  15961. /**
  15962. * Get possible playback rates
  15963. *
  15964. * @return {Array}
  15965. * All possible playback rates
  15966. */
  15967. ;
  15968. _proto.playbackRates = function playbackRates() {
  15969. var player = this.player();
  15970. return player.playbackRates && player.playbackRates() || [];
  15971. }
  15972. /**
  15973. * Get whether playback rates is supported by the tech
  15974. * and an array of playback rates exists
  15975. *
  15976. * @return {boolean}
  15977. * Whether changing playback rate is supported
  15978. */
  15979. ;
  15980. _proto.playbackRateSupported = function playbackRateSupported() {
  15981. return this.player().tech_ && this.player().tech_.featuresPlaybackRate && this.playbackRates() && this.playbackRates().length > 0;
  15982. }
  15983. /**
  15984. * Hide playback rate controls when they're no playback rate options to select
  15985. *
  15986. * @param {EventTarget~Event} [event]
  15987. * The event that caused this function to run.
  15988. *
  15989. * @listens Player#loadstart
  15990. */
  15991. ;
  15992. _proto.updateVisibility = function updateVisibility(event) {
  15993. if (this.playbackRateSupported()) {
  15994. this.removeClass('vjs-hidden');
  15995. } else {
  15996. this.addClass('vjs-hidden');
  15997. }
  15998. }
  15999. /**
  16000. * Update button label when rate changed
  16001. *
  16002. * @param {EventTarget~Event} [event]
  16003. * The event that caused this function to run.
  16004. *
  16005. * @listens Player#ratechange
  16006. */
  16007. ;
  16008. _proto.updateLabel = function updateLabel(event) {
  16009. if (this.playbackRateSupported()) {
  16010. this.labelEl_.textContent = this.player().playbackRate() + 'x';
  16011. }
  16012. };
  16013. return PlaybackRateMenuButton;
  16014. }(MenuButton);
  16015. /**
  16016. * The text that should display over the `FullscreenToggle`s controls. Added for localization.
  16017. *
  16018. * @type {string}
  16019. * @private
  16020. */
  16021. PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate';
  16022. Component$1.registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton);
  16023. /**
  16024. * Just an empty spacer element that can be used as an append point for plugins, etc.
  16025. * Also can be used to create space between elements when necessary.
  16026. *
  16027. * @extends Component
  16028. */
  16029. var Spacer = /*#__PURE__*/function (_Component) {
  16030. inheritsLoose(Spacer, _Component);
  16031. function Spacer() {
  16032. return _Component.apply(this, arguments) || this;
  16033. }
  16034. var _proto = Spacer.prototype;
  16035. /**
  16036. * Builds the default DOM `className`.
  16037. *
  16038. * @return {string}
  16039. * The DOM `className` for this object.
  16040. */
  16041. _proto.buildCSSClass = function buildCSSClass() {
  16042. return "vjs-spacer " + _Component.prototype.buildCSSClass.call(this);
  16043. }
  16044. /**
  16045. * Create the `Component`'s DOM element
  16046. *
  16047. * @return {Element}
  16048. * The element that was created.
  16049. */
  16050. ;
  16051. _proto.createEl = function createEl(tag, props, attributes) {
  16052. if (tag === void 0) {
  16053. tag = 'div';
  16054. }
  16055. if (props === void 0) {
  16056. props = {};
  16057. }
  16058. if (attributes === void 0) {
  16059. attributes = {};
  16060. }
  16061. if (!props.className) {
  16062. props.className = this.buildCSSClass();
  16063. }
  16064. return _Component.prototype.createEl.call(this, tag, props, attributes);
  16065. };
  16066. return Spacer;
  16067. }(Component$1);
  16068. Component$1.registerComponent('Spacer', Spacer);
  16069. /**
  16070. * Spacer specifically meant to be used as an insertion point for new plugins, etc.
  16071. *
  16072. * @extends Spacer
  16073. */
  16074. var CustomControlSpacer = /*#__PURE__*/function (_Spacer) {
  16075. inheritsLoose(CustomControlSpacer, _Spacer);
  16076. function CustomControlSpacer() {
  16077. return _Spacer.apply(this, arguments) || this;
  16078. }
  16079. var _proto = CustomControlSpacer.prototype;
  16080. /**
  16081. * Builds the default DOM `className`.
  16082. *
  16083. * @return {string}
  16084. * The DOM `className` for this object.
  16085. */
  16086. _proto.buildCSSClass = function buildCSSClass() {
  16087. return "vjs-custom-control-spacer " + _Spacer.prototype.buildCSSClass.call(this);
  16088. }
  16089. /**
  16090. * Create the `Component`'s DOM element
  16091. *
  16092. * @return {Element}
  16093. * The element that was created.
  16094. */
  16095. ;
  16096. _proto.createEl = function createEl() {
  16097. return _Spacer.prototype.createEl.call(this, 'div', {
  16098. className: this.buildCSSClass(),
  16099. // No-flex/table-cell mode requires there be some content
  16100. // in the cell to fill the remaining space of the table.
  16101. textContent: "\xA0"
  16102. });
  16103. };
  16104. return CustomControlSpacer;
  16105. }(Spacer);
  16106. Component$1.registerComponent('CustomControlSpacer', CustomControlSpacer);
  16107. /**
  16108. * Container of main controls.
  16109. *
  16110. * @extends Component
  16111. */
  16112. var ControlBar = /*#__PURE__*/function (_Component) {
  16113. inheritsLoose(ControlBar, _Component);
  16114. function ControlBar() {
  16115. return _Component.apply(this, arguments) || this;
  16116. }
  16117. var _proto = ControlBar.prototype;
  16118. /**
  16119. * Create the `Component`'s DOM element
  16120. *
  16121. * @return {Element}
  16122. * The element that was created.
  16123. */
  16124. _proto.createEl = function createEl() {
  16125. return _Component.prototype.createEl.call(this, 'div', {
  16126. className: 'vjs-control-bar',
  16127. dir: 'ltr'
  16128. });
  16129. };
  16130. return ControlBar;
  16131. }(Component$1);
  16132. /**
  16133. * Default options for `ControlBar`
  16134. *
  16135. * @type {Object}
  16136. * @private
  16137. */
  16138. ControlBar.prototype.options_ = {
  16139. children: ['playToggle', 'volumePanel', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'seekToLive', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'chaptersButton', 'descriptionsButton', 'subsCapsButton', 'audioTrackButton', 'fullscreenToggle']
  16140. };
  16141. if ('exitPictureInPicture' in document) {
  16142. ControlBar.prototype.options_.children.splice(ControlBar.prototype.options_.children.length - 1, 0, 'pictureInPictureToggle');
  16143. }
  16144. Component$1.registerComponent('ControlBar', ControlBar);
  16145. /**
  16146. * A display that indicates an error has occurred. This means that the video
  16147. * is unplayable.
  16148. *
  16149. * @extends ModalDialog
  16150. */
  16151. var ErrorDisplay = /*#__PURE__*/function (_ModalDialog) {
  16152. inheritsLoose(ErrorDisplay, _ModalDialog);
  16153. /**
  16154. * Creates an instance of this class.
  16155. *
  16156. * @param {Player} player
  16157. * The `Player` that this class should be attached to.
  16158. *
  16159. * @param {Object} [options]
  16160. * The key/value store of player options.
  16161. */
  16162. function ErrorDisplay(player, options) {
  16163. var _this;
  16164. _this = _ModalDialog.call(this, player, options) || this;
  16165. _this.on(player, 'error', function (e) {
  16166. return _this.open(e);
  16167. });
  16168. return _this;
  16169. }
  16170. /**
  16171. * Builds the default DOM `className`.
  16172. *
  16173. * @return {string}
  16174. * The DOM `className` for this object.
  16175. *
  16176. * @deprecated Since version 5.
  16177. */
  16178. var _proto = ErrorDisplay.prototype;
  16179. _proto.buildCSSClass = function buildCSSClass() {
  16180. return "vjs-error-display " + _ModalDialog.prototype.buildCSSClass.call(this);
  16181. }
  16182. /**
  16183. * Gets the localized error message based on the `Player`s error.
  16184. *
  16185. * @return {string}
  16186. * The `Player`s error message localized or an empty string.
  16187. */
  16188. ;
  16189. _proto.content = function content() {
  16190. var error = this.player().error();
  16191. return error ? this.localize(error.message) : '';
  16192. };
  16193. return ErrorDisplay;
  16194. }(ModalDialog);
  16195. /**
  16196. * The default options for an `ErrorDisplay`.
  16197. *
  16198. * @private
  16199. */
  16200. ErrorDisplay.prototype.options_ = _extends_1({}, ModalDialog.prototype.options_, {
  16201. pauseOnOpen: false,
  16202. fillAlways: true,
  16203. temporary: false,
  16204. uncloseable: true
  16205. });
  16206. Component$1.registerComponent('ErrorDisplay', ErrorDisplay);
  16207. var LOCAL_STORAGE_KEY$1 = 'vjs-text-track-settings';
  16208. var COLOR_BLACK = ['#000', 'Black'];
  16209. var COLOR_BLUE = ['#00F', 'Blue'];
  16210. var COLOR_CYAN = ['#0FF', 'Cyan'];
  16211. var COLOR_GREEN = ['#0F0', 'Green'];
  16212. var COLOR_MAGENTA = ['#F0F', 'Magenta'];
  16213. var COLOR_RED = ['#F00', 'Red'];
  16214. var COLOR_WHITE = ['#FFF', 'White'];
  16215. var COLOR_YELLOW = ['#FF0', 'Yellow'];
  16216. var OPACITY_OPAQUE = ['1', 'Opaque'];
  16217. var OPACITY_SEMI = ['0.5', 'Semi-Transparent'];
  16218. var OPACITY_TRANS = ['0', 'Transparent']; // Configuration for the various <select> elements in the DOM of this component.
  16219. //
  16220. // Possible keys include:
  16221. //
  16222. // `default`:
  16223. // The default option index. Only needs to be provided if not zero.
  16224. // `parser`:
  16225. // A function which is used to parse the value from the selected option in
  16226. // a customized way.
  16227. // `selector`:
  16228. // The selector used to find the associated <select> element.
  16229. var selectConfigs = {
  16230. backgroundColor: {
  16231. selector: '.vjs-bg-color > select',
  16232. id: 'captions-background-color-%s',
  16233. label: 'Color',
  16234. options: [COLOR_BLACK, COLOR_WHITE, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN]
  16235. },
  16236. backgroundOpacity: {
  16237. selector: '.vjs-bg-opacity > select',
  16238. id: 'captions-background-opacity-%s',
  16239. label: 'Transparency',
  16240. options: [OPACITY_OPAQUE, OPACITY_SEMI, OPACITY_TRANS]
  16241. },
  16242. color: {
  16243. selector: '.vjs-fg-color > select',
  16244. id: 'captions-foreground-color-%s',
  16245. label: 'Color',
  16246. options: [COLOR_WHITE, COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_YELLOW, COLOR_MAGENTA, COLOR_CYAN]
  16247. },
  16248. edgeStyle: {
  16249. selector: '.vjs-edge-style > select',
  16250. id: '%s',
  16251. label: 'Text Edge Style',
  16252. options: [['none', 'None'], ['raised', 'Raised'], ['depressed', 'Depressed'], ['uniform', 'Uniform'], ['dropshadow', 'Dropshadow']]
  16253. },
  16254. fontFamily: {
  16255. selector: '.vjs-font-family > select',
  16256. id: 'captions-font-family-%s',
  16257. label: 'Font Family',
  16258. options: [['proportionalSansSerif', 'Proportional Sans-Serif'], ['monospaceSansSerif', 'Monospace Sans-Serif'], ['proportionalSerif', 'Proportional Serif'], ['monospaceSerif', 'Monospace Serif'], ['casual', 'Casual'], ['script', 'Script'], ['small-caps', 'Small Caps']]
  16259. },
  16260. fontPercent: {
  16261. selector: '.vjs-font-percent > select',
  16262. id: 'captions-font-size-%s',
  16263. label: 'Font Size',
  16264. 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%']],
  16265. "default": 2,
  16266. parser: function parser(v) {
  16267. return v === '1.00' ? null : Number(v);
  16268. }
  16269. },
  16270. textOpacity: {
  16271. selector: '.vjs-text-opacity > select',
  16272. id: 'captions-foreground-opacity-%s',
  16273. label: 'Transparency',
  16274. options: [OPACITY_OPAQUE, OPACITY_SEMI]
  16275. },
  16276. // Options for this object are defined below.
  16277. windowColor: {
  16278. selector: '.vjs-window-color > select',
  16279. id: 'captions-window-color-%s',
  16280. label: 'Color'
  16281. },
  16282. // Options for this object are defined below.
  16283. windowOpacity: {
  16284. selector: '.vjs-window-opacity > select',
  16285. id: 'captions-window-opacity-%s',
  16286. label: 'Transparency',
  16287. options: [OPACITY_TRANS, OPACITY_SEMI, OPACITY_OPAQUE]
  16288. }
  16289. };
  16290. selectConfigs.windowColor.options = selectConfigs.backgroundColor.options;
  16291. /**
  16292. * Get the actual value of an option.
  16293. *
  16294. * @param {string} value
  16295. * The value to get
  16296. *
  16297. * @param {Function} [parser]
  16298. * Optional function to adjust the value.
  16299. *
  16300. * @return {Mixed}
  16301. * - Will be `undefined` if no value exists
  16302. * - Will be `undefined` if the given value is "none".
  16303. * - Will be the actual value otherwise.
  16304. *
  16305. * @private
  16306. */
  16307. function parseOptionValue(value, parser) {
  16308. if (parser) {
  16309. value = parser(value);
  16310. }
  16311. if (value && value !== 'none') {
  16312. return value;
  16313. }
  16314. }
  16315. /**
  16316. * Gets the value of the selected <option> element within a <select> element.
  16317. *
  16318. * @param {Element} el
  16319. * the element to look in
  16320. *
  16321. * @param {Function} [parser]
  16322. * Optional function to adjust the value.
  16323. *
  16324. * @return {Mixed}
  16325. * - Will be `undefined` if no value exists
  16326. * - Will be `undefined` if the given value is "none".
  16327. * - Will be the actual value otherwise.
  16328. *
  16329. * @private
  16330. */
  16331. function getSelectedOptionValue(el, parser) {
  16332. var value = el.options[el.options.selectedIndex].value;
  16333. return parseOptionValue(value, parser);
  16334. }
  16335. /**
  16336. * Sets the selected <option> element within a <select> element based on a
  16337. * given value.
  16338. *
  16339. * @param {Element} el
  16340. * The element to look in.
  16341. *
  16342. * @param {string} value
  16343. * the property to look on.
  16344. *
  16345. * @param {Function} [parser]
  16346. * Optional function to adjust the value before comparing.
  16347. *
  16348. * @private
  16349. */
  16350. function setSelectedOption(el, value, parser) {
  16351. if (!value) {
  16352. return;
  16353. }
  16354. for (var i = 0; i < el.options.length; i++) {
  16355. if (parseOptionValue(el.options[i].value, parser) === value) {
  16356. el.selectedIndex = i;
  16357. break;
  16358. }
  16359. }
  16360. }
  16361. /**
  16362. * Manipulate Text Tracks settings.
  16363. *
  16364. * @extends ModalDialog
  16365. */
  16366. var TextTrackSettings = /*#__PURE__*/function (_ModalDialog) {
  16367. inheritsLoose(TextTrackSettings, _ModalDialog);
  16368. /**
  16369. * Creates an instance of this class.
  16370. *
  16371. * @param {Player} player
  16372. * The `Player` that this class should be attached to.
  16373. *
  16374. * @param {Object} [options]
  16375. * The key/value store of player options.
  16376. */
  16377. function TextTrackSettings(player, options) {
  16378. var _this;
  16379. options.temporary = false;
  16380. _this = _ModalDialog.call(this, player, options) || this;
  16381. _this.updateDisplay = _this.updateDisplay.bind(assertThisInitialized(_this)); // fill the modal and pretend we have opened it
  16382. _this.fill();
  16383. _this.hasBeenOpened_ = _this.hasBeenFilled_ = true;
  16384. _this.endDialog = createEl('p', {
  16385. className: 'vjs-control-text',
  16386. textContent: _this.localize('End of dialog window.')
  16387. });
  16388. _this.el().appendChild(_this.endDialog);
  16389. _this.setDefaults(); // Grab `persistTextTrackSettings` from the player options if not passed in child options
  16390. if (options.persistTextTrackSettings === undefined) {
  16391. _this.options_.persistTextTrackSettings = _this.options_.playerOptions.persistTextTrackSettings;
  16392. }
  16393. _this.on(_this.$('.vjs-done-button'), 'click', function () {
  16394. _this.saveSettings();
  16395. _this.close();
  16396. });
  16397. _this.on(_this.$('.vjs-default-button'), 'click', function () {
  16398. _this.setDefaults();
  16399. _this.updateDisplay();
  16400. });
  16401. each(selectConfigs, function (config) {
  16402. _this.on(_this.$(config.selector), 'change', _this.updateDisplay);
  16403. });
  16404. if (_this.options_.persistTextTrackSettings) {
  16405. _this.restoreSettings();
  16406. }
  16407. return _this;
  16408. }
  16409. var _proto = TextTrackSettings.prototype;
  16410. _proto.dispose = function dispose() {
  16411. this.endDialog = null;
  16412. _ModalDialog.prototype.dispose.call(this);
  16413. }
  16414. /**
  16415. * Create a <select> element with configured options.
  16416. *
  16417. * @param {string} key
  16418. * Configuration key to use during creation.
  16419. *
  16420. * @return {string}
  16421. * An HTML string.
  16422. *
  16423. * @private
  16424. */
  16425. ;
  16426. _proto.createElSelect_ = function createElSelect_(key, legendId, type) {
  16427. var _this2 = this;
  16428. if (legendId === void 0) {
  16429. legendId = '';
  16430. }
  16431. if (type === void 0) {
  16432. type = 'label';
  16433. }
  16434. var config = selectConfigs[key];
  16435. var id = config.id.replace('%s', this.id_);
  16436. var selectLabelledbyIds = [legendId, id].join(' ').trim();
  16437. return ["<" + type + " id=\"" + id + "\" class=\"" + (type === 'label' ? 'vjs-label' : '') + "\">", this.localize(config.label), "</" + type + ">", "<select aria-labelledby=\"" + selectLabelledbyIds + "\">"].concat(config.options.map(function (o) {
  16438. var optionId = id + '-' + o[1].replace(/\W+/g, '');
  16439. return ["<option id=\"" + optionId + "\" value=\"" + o[0] + "\" ", "aria-labelledby=\"" + selectLabelledbyIds + " " + optionId + "\">", _this2.localize(o[1]), '</option>'].join('');
  16440. })).concat('</select>').join('');
  16441. }
  16442. /**
  16443. * Create foreground color element for the component
  16444. *
  16445. * @return {string}
  16446. * An HTML string.
  16447. *
  16448. * @private
  16449. */
  16450. ;
  16451. _proto.createElFgColor_ = function createElFgColor_() {
  16452. var legendId = "captions-text-legend-" + this.id_;
  16453. 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('');
  16454. }
  16455. /**
  16456. * Create background color element for the component
  16457. *
  16458. * @return {string}
  16459. * An HTML string.
  16460. *
  16461. * @private
  16462. */
  16463. ;
  16464. _proto.createElBgColor_ = function createElBgColor_() {
  16465. var legendId = "captions-background-" + this.id_;
  16466. 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('');
  16467. }
  16468. /**
  16469. * Create window color element for the component
  16470. *
  16471. * @return {string}
  16472. * An HTML string.
  16473. *
  16474. * @private
  16475. */
  16476. ;
  16477. _proto.createElWinColor_ = function createElWinColor_() {
  16478. var legendId = "captions-window-" + this.id_;
  16479. 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('');
  16480. }
  16481. /**
  16482. * Create color elements for the component
  16483. *
  16484. * @return {Element}
  16485. * The element that was created
  16486. *
  16487. * @private
  16488. */
  16489. ;
  16490. _proto.createElColors_ = function createElColors_() {
  16491. return createEl('div', {
  16492. className: 'vjs-track-settings-colors',
  16493. innerHTML: [this.createElFgColor_(), this.createElBgColor_(), this.createElWinColor_()].join('')
  16494. });
  16495. }
  16496. /**
  16497. * Create font elements for the component
  16498. *
  16499. * @return {Element}
  16500. * The element that was created.
  16501. *
  16502. * @private
  16503. */
  16504. ;
  16505. _proto.createElFont_ = function createElFont_() {
  16506. return createEl('div', {
  16507. className: 'vjs-track-settings-font',
  16508. 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('')
  16509. });
  16510. }
  16511. /**
  16512. * Create controls for the component
  16513. *
  16514. * @return {Element}
  16515. * The element that was created.
  16516. *
  16517. * @private
  16518. */
  16519. ;
  16520. _proto.createElControls_ = function createElControls_() {
  16521. var defaultsDescription = this.localize('restore all settings to the default values');
  16522. return createEl('div', {
  16523. className: 'vjs-track-settings-controls',
  16524. 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('')
  16525. });
  16526. };
  16527. _proto.content = function content() {
  16528. return [this.createElColors_(), this.createElFont_(), this.createElControls_()];
  16529. };
  16530. _proto.label = function label() {
  16531. return this.localize('Caption Settings Dialog');
  16532. };
  16533. _proto.description = function description() {
  16534. return this.localize('Beginning of dialog window. Escape will cancel and close the window.');
  16535. };
  16536. _proto.buildCSSClass = function buildCSSClass() {
  16537. return _ModalDialog.prototype.buildCSSClass.call(this) + ' vjs-text-track-settings';
  16538. }
  16539. /**
  16540. * Gets an object of text track settings (or null).
  16541. *
  16542. * @return {Object}
  16543. * An object with config values parsed from the DOM or localStorage.
  16544. */
  16545. ;
  16546. _proto.getValues = function getValues() {
  16547. var _this3 = this;
  16548. return reduce(selectConfigs, function (accum, config, key) {
  16549. var value = getSelectedOptionValue(_this3.$(config.selector), config.parser);
  16550. if (value !== undefined) {
  16551. accum[key] = value;
  16552. }
  16553. return accum;
  16554. }, {});
  16555. }
  16556. /**
  16557. * Sets text track settings from an object of values.
  16558. *
  16559. * @param {Object} values
  16560. * An object with config values parsed from the DOM or localStorage.
  16561. */
  16562. ;
  16563. _proto.setValues = function setValues(values) {
  16564. var _this4 = this;
  16565. each(selectConfigs, function (config, key) {
  16566. setSelectedOption(_this4.$(config.selector), values[key], config.parser);
  16567. });
  16568. }
  16569. /**
  16570. * Sets all `<select>` elements to their default values.
  16571. */
  16572. ;
  16573. _proto.setDefaults = function setDefaults() {
  16574. var _this5 = this;
  16575. each(selectConfigs, function (config) {
  16576. var index = config.hasOwnProperty('default') ? config["default"] : 0;
  16577. _this5.$(config.selector).selectedIndex = index;
  16578. });
  16579. }
  16580. /**
  16581. * Restore texttrack settings from localStorage
  16582. */
  16583. ;
  16584. _proto.restoreSettings = function restoreSettings() {
  16585. var values;
  16586. try {
  16587. values = JSON.parse(window.localStorage.getItem(LOCAL_STORAGE_KEY$1));
  16588. } catch (err) {
  16589. log$1.warn(err);
  16590. }
  16591. if (values) {
  16592. this.setValues(values);
  16593. }
  16594. }
  16595. /**
  16596. * Save text track settings to localStorage
  16597. */
  16598. ;
  16599. _proto.saveSettings = function saveSettings() {
  16600. if (!this.options_.persistTextTrackSettings) {
  16601. return;
  16602. }
  16603. var values = this.getValues();
  16604. try {
  16605. if (Object.keys(values).length) {
  16606. window.localStorage.setItem(LOCAL_STORAGE_KEY$1, JSON.stringify(values));
  16607. } else {
  16608. window.localStorage.removeItem(LOCAL_STORAGE_KEY$1);
  16609. }
  16610. } catch (err) {
  16611. log$1.warn(err);
  16612. }
  16613. }
  16614. /**
  16615. * Update display of text track settings
  16616. */
  16617. ;
  16618. _proto.updateDisplay = function updateDisplay() {
  16619. var ttDisplay = this.player_.getChild('textTrackDisplay');
  16620. if (ttDisplay) {
  16621. ttDisplay.updateDisplay();
  16622. }
  16623. }
  16624. /**
  16625. * conditionally blur the element and refocus the captions button
  16626. *
  16627. * @private
  16628. */
  16629. ;
  16630. _proto.conditionalBlur_ = function conditionalBlur_() {
  16631. this.previouslyActiveEl_ = null;
  16632. var cb = this.player_.controlBar;
  16633. var subsCapsBtn = cb && cb.subsCapsButton;
  16634. var ccBtn = cb && cb.captionsButton;
  16635. if (subsCapsBtn) {
  16636. subsCapsBtn.focus();
  16637. } else if (ccBtn) {
  16638. ccBtn.focus();
  16639. }
  16640. };
  16641. return TextTrackSettings;
  16642. }(ModalDialog);
  16643. Component$1.registerComponent('TextTrackSettings', TextTrackSettings);
  16644. /**
  16645. * A Resize Manager. It is in charge of triggering `playerresize` on the player in the right conditions.
  16646. *
  16647. * 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}.
  16648. *
  16649. * If the ResizeObserver is available natively, it will be used. A polyfill can be passed in as an option.
  16650. * If a `playerresize` event is not needed, the ResizeManager component can be removed from the player, see the example below.
  16651. * @example <caption>How to disable the resize manager</caption>
  16652. * const player = videojs('#vid', {
  16653. * resizeManager: false
  16654. * });
  16655. *
  16656. * @see {@link https://wicg.github.io/ResizeObserver/|ResizeObserver specification}
  16657. *
  16658. * @extends Component
  16659. */
  16660. var ResizeManager = /*#__PURE__*/function (_Component) {
  16661. inheritsLoose(ResizeManager, _Component);
  16662. /**
  16663. * Create the ResizeManager.
  16664. *
  16665. * @param {Object} player
  16666. * The `Player` that this class should be attached to.
  16667. *
  16668. * @param {Object} [options]
  16669. * The key/value store of ResizeManager options.
  16670. *
  16671. * @param {Object} [options.ResizeObserver]
  16672. * A polyfill for ResizeObserver can be passed in here.
  16673. * If this is set to null it will ignore the native ResizeObserver and fall back to the iframe fallback.
  16674. */
  16675. function ResizeManager(player, options) {
  16676. var _this;
  16677. var RESIZE_OBSERVER_AVAILABLE = options.ResizeObserver || window.ResizeObserver; // if `null` was passed, we want to disable the ResizeObserver
  16678. if (options.ResizeObserver === null) {
  16679. RESIZE_OBSERVER_AVAILABLE = false;
  16680. } // Only create an element when ResizeObserver isn't available
  16681. var options_ = mergeOptions$3({
  16682. createEl: !RESIZE_OBSERVER_AVAILABLE,
  16683. reportTouchActivity: false
  16684. }, options);
  16685. _this = _Component.call(this, player, options_) || this;
  16686. _this.ResizeObserver = options.ResizeObserver || window.ResizeObserver;
  16687. _this.loadListener_ = null;
  16688. _this.resizeObserver_ = null;
  16689. _this.debouncedHandler_ = debounce(function () {
  16690. _this.resizeHandler();
  16691. }, 100, false, assertThisInitialized(_this));
  16692. if (RESIZE_OBSERVER_AVAILABLE) {
  16693. _this.resizeObserver_ = new _this.ResizeObserver(_this.debouncedHandler_);
  16694. _this.resizeObserver_.observe(player.el());
  16695. } else {
  16696. _this.loadListener_ = function () {
  16697. if (!_this.el_ || !_this.el_.contentWindow) {
  16698. return;
  16699. }
  16700. var debouncedHandler_ = _this.debouncedHandler_;
  16701. var unloadListener_ = _this.unloadListener_ = function () {
  16702. off(this, 'resize', debouncedHandler_);
  16703. off(this, 'unload', unloadListener_);
  16704. unloadListener_ = null;
  16705. }; // safari and edge can unload the iframe before resizemanager dispose
  16706. // we have to dispose of event handlers correctly before that happens
  16707. on(_this.el_.contentWindow, 'unload', unloadListener_);
  16708. on(_this.el_.contentWindow, 'resize', debouncedHandler_);
  16709. };
  16710. _this.one('load', _this.loadListener_);
  16711. }
  16712. return _this;
  16713. }
  16714. var _proto = ResizeManager.prototype;
  16715. _proto.createEl = function createEl() {
  16716. return _Component.prototype.createEl.call(this, 'iframe', {
  16717. className: 'vjs-resize-manager',
  16718. tabIndex: -1,
  16719. title: this.localize('No content')
  16720. }, {
  16721. 'aria-hidden': 'true'
  16722. });
  16723. }
  16724. /**
  16725. * Called when a resize is triggered on the iframe or a resize is observed via the ResizeObserver
  16726. *
  16727. * @fires Player#playerresize
  16728. */
  16729. ;
  16730. _proto.resizeHandler = function resizeHandler() {
  16731. /**
  16732. * Called when the player size has changed
  16733. *
  16734. * @event Player#playerresize
  16735. * @type {EventTarget~Event}
  16736. */
  16737. // make sure player is still around to trigger
  16738. // prevents this from causing an error after dispose
  16739. if (!this.player_ || !this.player_.trigger) {
  16740. return;
  16741. }
  16742. this.player_.trigger('playerresize');
  16743. };
  16744. _proto.dispose = function dispose() {
  16745. if (this.debouncedHandler_) {
  16746. this.debouncedHandler_.cancel();
  16747. }
  16748. if (this.resizeObserver_) {
  16749. if (this.player_.el()) {
  16750. this.resizeObserver_.unobserve(this.player_.el());
  16751. }
  16752. this.resizeObserver_.disconnect();
  16753. }
  16754. if (this.loadListener_) {
  16755. this.off('load', this.loadListener_);
  16756. }
  16757. if (this.el_ && this.el_.contentWindow && this.unloadListener_) {
  16758. this.unloadListener_.call(this.el_.contentWindow);
  16759. }
  16760. this.ResizeObserver = null;
  16761. this.resizeObserver = null;
  16762. this.debouncedHandler_ = null;
  16763. this.loadListener_ = null;
  16764. _Component.prototype.dispose.call(this);
  16765. };
  16766. return ResizeManager;
  16767. }(Component$1);
  16768. Component$1.registerComponent('ResizeManager', ResizeManager);
  16769. var defaults = {
  16770. trackingThreshold: 20,
  16771. liveTolerance: 15
  16772. };
  16773. /*
  16774. track when we are at the live edge, and other helpers for live playback */
  16775. /**
  16776. * A class for checking live current time and determining when the player
  16777. * is at or behind the live edge.
  16778. */
  16779. var LiveTracker = /*#__PURE__*/function (_Component) {
  16780. inheritsLoose(LiveTracker, _Component);
  16781. /**
  16782. * Creates an instance of this class.
  16783. *
  16784. * @param {Player} player
  16785. * The `Player` that this class should be attached to.
  16786. *
  16787. * @param {Object} [options]
  16788. * The key/value store of player options.
  16789. *
  16790. * @param {number} [options.trackingThreshold=20]
  16791. * Number of seconds of live window (seekableEnd - seekableStart) that
  16792. * media needs to have before the liveui will be shown.
  16793. *
  16794. * @param {number} [options.liveTolerance=15]
  16795. * Number of seconds behind live that we have to be
  16796. * before we will be considered non-live. Note that this will only
  16797. * be used when playing at the live edge. This allows large seekable end
  16798. * changes to not effect wether we are live or not.
  16799. */
  16800. function LiveTracker(player, options) {
  16801. var _this;
  16802. // LiveTracker does not need an element
  16803. var options_ = mergeOptions$3(defaults, options, {
  16804. createEl: false
  16805. });
  16806. _this = _Component.call(this, player, options_) || this;
  16807. _this.handleVisibilityChange_ = function (e) {
  16808. return _this.handleVisibilityChange(e);
  16809. };
  16810. _this.trackLiveHandler_ = function () {
  16811. return _this.trackLive_();
  16812. };
  16813. _this.handlePlay_ = function (e) {
  16814. return _this.handlePlay(e);
  16815. };
  16816. _this.handleFirstTimeupdate_ = function (e) {
  16817. return _this.handleFirstTimeupdate(e);
  16818. };
  16819. _this.handleSeeked_ = function (e) {
  16820. return _this.handleSeeked(e);
  16821. };
  16822. _this.seekToLiveEdge_ = function (e) {
  16823. return _this.seekToLiveEdge(e);
  16824. };
  16825. _this.reset_();
  16826. _this.on(_this.player_, 'durationchange', function (e) {
  16827. return _this.handleDurationchange(e);
  16828. }); // we should try to toggle tracking on canplay as native playback engines, like Safari
  16829. // may not have the proper values for things like seekableEnd until then
  16830. _this.on(_this.player_, 'canplay', function () {
  16831. return _this.toggleTracking();
  16832. }); // we don't need to track live playback if the document is hidden,
  16833. // also, tracking when the document is hidden can
  16834. // cause the CPU to spike and eventually crash the page on IE11.
  16835. if (IE_VERSION && 'hidden' in document && 'visibilityState' in document) {
  16836. _this.on(document, 'visibilitychange', _this.handleVisibilityChange_);
  16837. }
  16838. return _this;
  16839. }
  16840. /**
  16841. * toggle tracking based on document visiblility
  16842. */
  16843. var _proto = LiveTracker.prototype;
  16844. _proto.handleVisibilityChange = function handleVisibilityChange() {
  16845. if (this.player_.duration() !== Infinity) {
  16846. return;
  16847. }
  16848. if (document.hidden) {
  16849. this.stopTracking();
  16850. } else {
  16851. this.startTracking();
  16852. }
  16853. }
  16854. /**
  16855. * all the functionality for tracking when seek end changes
  16856. * and for tracking how far past seek end we should be
  16857. */
  16858. ;
  16859. _proto.trackLive_ = function trackLive_() {
  16860. var seekable = this.player_.seekable(); // skip undefined seekable
  16861. if (!seekable || !seekable.length) {
  16862. return;
  16863. }
  16864. var newTime = Number(window.performance.now().toFixed(4));
  16865. var deltaTime = this.lastTime_ === -1 ? 0 : (newTime - this.lastTime_) / 1000;
  16866. this.lastTime_ = newTime;
  16867. this.pastSeekEnd_ = this.pastSeekEnd() + deltaTime;
  16868. var liveCurrentTime = this.liveCurrentTime();
  16869. var currentTime = this.player_.currentTime(); // we are behind live if any are true
  16870. // 1. the player is paused
  16871. // 2. the user seeked to a location 2 seconds away from live
  16872. // 3. the difference between live and current time is greater
  16873. // liveTolerance which defaults to 15s
  16874. var isBehind = this.player_.paused() || this.seekedBehindLive_ || Math.abs(liveCurrentTime - currentTime) > this.options_.liveTolerance; // we cannot be behind if
  16875. // 1. until we have not seen a timeupdate yet
  16876. // 2. liveCurrentTime is Infinity, which happens on Android and Native Safari
  16877. if (!this.timeupdateSeen_ || liveCurrentTime === Infinity) {
  16878. isBehind = false;
  16879. }
  16880. if (isBehind !== this.behindLiveEdge_) {
  16881. this.behindLiveEdge_ = isBehind;
  16882. this.trigger('liveedgechange');
  16883. }
  16884. }
  16885. /**
  16886. * handle a durationchange event on the player
  16887. * and start/stop tracking accordingly.
  16888. */
  16889. ;
  16890. _proto.handleDurationchange = function handleDurationchange() {
  16891. this.toggleTracking();
  16892. }
  16893. /**
  16894. * start/stop tracking
  16895. */
  16896. ;
  16897. _proto.toggleTracking = function toggleTracking() {
  16898. if (this.player_.duration() === Infinity && this.liveWindow() >= this.options_.trackingThreshold) {
  16899. if (this.player_.options_.liveui) {
  16900. this.player_.addClass('vjs-liveui');
  16901. }
  16902. this.startTracking();
  16903. } else {
  16904. this.player_.removeClass('vjs-liveui');
  16905. this.stopTracking();
  16906. }
  16907. }
  16908. /**
  16909. * start tracking live playback
  16910. */
  16911. ;
  16912. _proto.startTracking = function startTracking() {
  16913. if (this.isTracking()) {
  16914. return;
  16915. } // If we haven't seen a timeupdate, we need to check whether playback
  16916. // began before this component started tracking. This can happen commonly
  16917. // when using autoplay.
  16918. if (!this.timeupdateSeen_) {
  16919. this.timeupdateSeen_ = this.player_.hasStarted();
  16920. }
  16921. this.trackingInterval_ = this.setInterval(this.trackLiveHandler_, UPDATE_REFRESH_INTERVAL);
  16922. this.trackLive_();
  16923. this.on(this.player_, ['play', 'pause'], this.trackLiveHandler_);
  16924. if (!this.timeupdateSeen_) {
  16925. this.one(this.player_, 'play', this.handlePlay_);
  16926. this.one(this.player_, 'timeupdate', this.handleFirstTimeupdate_);
  16927. } else {
  16928. this.on(this.player_, 'seeked', this.handleSeeked_);
  16929. }
  16930. }
  16931. /**
  16932. * handle the first timeupdate on the player if it wasn't already playing
  16933. * when live tracker started tracking.
  16934. */
  16935. ;
  16936. _proto.handleFirstTimeupdate = function handleFirstTimeupdate() {
  16937. this.timeupdateSeen_ = true;
  16938. this.on(this.player_, 'seeked', this.handleSeeked_);
  16939. }
  16940. /**
  16941. * Keep track of what time a seek starts, and listen for seeked
  16942. * to find where a seek ends.
  16943. */
  16944. ;
  16945. _proto.handleSeeked = function handleSeeked() {
  16946. var timeDiff = Math.abs(this.liveCurrentTime() - this.player_.currentTime());
  16947. this.seekedBehindLive_ = this.nextSeekedFromUser_ && timeDiff > 2;
  16948. this.nextSeekedFromUser_ = false;
  16949. this.trackLive_();
  16950. }
  16951. /**
  16952. * handle the first play on the player, and make sure that we seek
  16953. * right to the live edge.
  16954. */
  16955. ;
  16956. _proto.handlePlay = function handlePlay() {
  16957. this.one(this.player_, 'timeupdate', this.seekToLiveEdge_);
  16958. }
  16959. /**
  16960. * Stop tracking, and set all internal variables to
  16961. * their initial value.
  16962. */
  16963. ;
  16964. _proto.reset_ = function reset_() {
  16965. this.lastTime_ = -1;
  16966. this.pastSeekEnd_ = 0;
  16967. this.lastSeekEnd_ = -1;
  16968. this.behindLiveEdge_ = true;
  16969. this.timeupdateSeen_ = false;
  16970. this.seekedBehindLive_ = false;
  16971. this.nextSeekedFromUser_ = false;
  16972. this.clearInterval(this.trackingInterval_);
  16973. this.trackingInterval_ = null;
  16974. this.off(this.player_, ['play', 'pause'], this.trackLiveHandler_);
  16975. this.off(this.player_, 'seeked', this.handleSeeked_);
  16976. this.off(this.player_, 'play', this.handlePlay_);
  16977. this.off(this.player_, 'timeupdate', this.handleFirstTimeupdate_);
  16978. this.off(this.player_, 'timeupdate', this.seekToLiveEdge_);
  16979. }
  16980. /**
  16981. * The next seeked event is from the user. Meaning that any seek
  16982. * > 2s behind live will be considered behind live for real and
  16983. * liveTolerance will be ignored.
  16984. */
  16985. ;
  16986. _proto.nextSeekedFromUser = function nextSeekedFromUser() {
  16987. this.nextSeekedFromUser_ = true;
  16988. }
  16989. /**
  16990. * stop tracking live playback
  16991. */
  16992. ;
  16993. _proto.stopTracking = function stopTracking() {
  16994. if (!this.isTracking()) {
  16995. return;
  16996. }
  16997. this.reset_();
  16998. this.trigger('liveedgechange');
  16999. }
  17000. /**
  17001. * A helper to get the player seekable end
  17002. * so that we don't have to null check everywhere
  17003. *
  17004. * @return {number}
  17005. * The furthest seekable end or Infinity.
  17006. */
  17007. ;
  17008. _proto.seekableEnd = function seekableEnd() {
  17009. var seekable = this.player_.seekable();
  17010. var seekableEnds = [];
  17011. var i = seekable ? seekable.length : 0;
  17012. while (i--) {
  17013. seekableEnds.push(seekable.end(i));
  17014. } // grab the furthest seekable end after sorting, or if there are none
  17015. // default to Infinity
  17016. return seekableEnds.length ? seekableEnds.sort()[seekableEnds.length - 1] : Infinity;
  17017. }
  17018. /**
  17019. * A helper to get the player seekable start
  17020. * so that we don't have to null check everywhere
  17021. *
  17022. * @return {number}
  17023. * The earliest seekable start or 0.
  17024. */
  17025. ;
  17026. _proto.seekableStart = function seekableStart() {
  17027. var seekable = this.player_.seekable();
  17028. var seekableStarts = [];
  17029. var i = seekable ? seekable.length : 0;
  17030. while (i--) {
  17031. seekableStarts.push(seekable.start(i));
  17032. } // grab the first seekable start after sorting, or if there are none
  17033. // default to 0
  17034. return seekableStarts.length ? seekableStarts.sort()[0] : 0;
  17035. }
  17036. /**
  17037. * Get the live time window aka
  17038. * the amount of time between seekable start and
  17039. * live current time.
  17040. *
  17041. * @return {number}
  17042. * The amount of seconds that are seekable in
  17043. * the live video.
  17044. */
  17045. ;
  17046. _proto.liveWindow = function liveWindow() {
  17047. var liveCurrentTime = this.liveCurrentTime(); // if liveCurrenTime is Infinity then we don't have a liveWindow at all
  17048. if (liveCurrentTime === Infinity) {
  17049. return 0;
  17050. }
  17051. return liveCurrentTime - this.seekableStart();
  17052. }
  17053. /**
  17054. * Determines if the player is live, only checks if this component
  17055. * is tracking live playback or not
  17056. *
  17057. * @return {boolean}
  17058. * Wether liveTracker is tracking
  17059. */
  17060. ;
  17061. _proto.isLive = function isLive() {
  17062. return this.isTracking();
  17063. }
  17064. /**
  17065. * Determines if currentTime is at the live edge and won't fall behind
  17066. * on each seekableendchange
  17067. *
  17068. * @return {boolean}
  17069. * Wether playback is at the live edge
  17070. */
  17071. ;
  17072. _proto.atLiveEdge = function atLiveEdge() {
  17073. return !this.behindLiveEdge();
  17074. }
  17075. /**
  17076. * get what we expect the live current time to be
  17077. *
  17078. * @return {number}
  17079. * The expected live current time
  17080. */
  17081. ;
  17082. _proto.liveCurrentTime = function liveCurrentTime() {
  17083. return this.pastSeekEnd() + this.seekableEnd();
  17084. }
  17085. /**
  17086. * The number of seconds that have occured after seekable end
  17087. * changed. This will be reset to 0 once seekable end changes.
  17088. *
  17089. * @return {number}
  17090. * Seconds past the current seekable end
  17091. */
  17092. ;
  17093. _proto.pastSeekEnd = function pastSeekEnd() {
  17094. var seekableEnd = this.seekableEnd();
  17095. if (this.lastSeekEnd_ !== -1 && seekableEnd !== this.lastSeekEnd_) {
  17096. this.pastSeekEnd_ = 0;
  17097. }
  17098. this.lastSeekEnd_ = seekableEnd;
  17099. return this.pastSeekEnd_;
  17100. }
  17101. /**
  17102. * If we are currently behind the live edge, aka currentTime will be
  17103. * behind on a seekableendchange
  17104. *
  17105. * @return {boolean}
  17106. * If we are behind the live edge
  17107. */
  17108. ;
  17109. _proto.behindLiveEdge = function behindLiveEdge() {
  17110. return this.behindLiveEdge_;
  17111. }
  17112. /**
  17113. * Wether live tracker is currently tracking or not.
  17114. */
  17115. ;
  17116. _proto.isTracking = function isTracking() {
  17117. return typeof this.trackingInterval_ === 'number';
  17118. }
  17119. /**
  17120. * Seek to the live edge if we are behind the live edge
  17121. */
  17122. ;
  17123. _proto.seekToLiveEdge = function seekToLiveEdge() {
  17124. this.seekedBehindLive_ = false;
  17125. if (this.atLiveEdge()) {
  17126. return;
  17127. }
  17128. this.nextSeekedFromUser_ = false;
  17129. this.player_.currentTime(this.liveCurrentTime());
  17130. }
  17131. /**
  17132. * Dispose of liveTracker
  17133. */
  17134. ;
  17135. _proto.dispose = function dispose() {
  17136. this.off(document, 'visibilitychange', this.handleVisibilityChange_);
  17137. this.stopTracking();
  17138. _Component.prototype.dispose.call(this);
  17139. };
  17140. return LiveTracker;
  17141. }(Component$1);
  17142. Component$1.registerComponent('LiveTracker', LiveTracker);
  17143. /**
  17144. * This function is used to fire a sourceset when there is something
  17145. * similar to `mediaEl.load()` being called. It will try to find the source via
  17146. * the `src` attribute and then the `<source>` elements. It will then fire `sourceset`
  17147. * with the source that was found or empty string if we cannot know. If it cannot
  17148. * find a source then `sourceset` will not be fired.
  17149. *
  17150. * @param {Html5} tech
  17151. * The tech object that sourceset was setup on
  17152. *
  17153. * @return {boolean}
  17154. * returns false if the sourceset was not fired and true otherwise.
  17155. */
  17156. var sourcesetLoad = function sourcesetLoad(tech) {
  17157. var el = tech.el(); // if `el.src` is set, that source will be loaded.
  17158. if (el.hasAttribute('src')) {
  17159. tech.triggerSourceset(el.src);
  17160. return true;
  17161. }
  17162. /**
  17163. * Since there isn't a src property on the media element, source elements will be used for
  17164. * implementing the source selection algorithm. This happens asynchronously and
  17165. * for most cases were there is more than one source we cannot tell what source will
  17166. * be loaded, without re-implementing the source selection algorithm. At this time we are not
  17167. * going to do that. There are three special cases that we do handle here though:
  17168. *
  17169. * 1. If there are no sources, do not fire `sourceset`.
  17170. * 2. If there is only one `<source>` with a `src` property/attribute that is our `src`
  17171. * 3. If there is more than one `<source>` but all of them have the same `src` url.
  17172. * That will be our src.
  17173. */
  17174. var sources = tech.$$('source');
  17175. var srcUrls = [];
  17176. var src = ''; // if there are no sources, do not fire sourceset
  17177. if (!sources.length) {
  17178. return false;
  17179. } // only count valid/non-duplicate source elements
  17180. for (var i = 0; i < sources.length; i++) {
  17181. var url = sources[i].src;
  17182. if (url && srcUrls.indexOf(url) === -1) {
  17183. srcUrls.push(url);
  17184. }
  17185. } // there were no valid sources
  17186. if (!srcUrls.length) {
  17187. return false;
  17188. } // there is only one valid source element url
  17189. // use that
  17190. if (srcUrls.length === 1) {
  17191. src = srcUrls[0];
  17192. }
  17193. tech.triggerSourceset(src);
  17194. return true;
  17195. };
  17196. /**
  17197. * our implementation of an `innerHTML` descriptor for browsers
  17198. * that do not have one.
  17199. */
  17200. var innerHTMLDescriptorPolyfill = Object.defineProperty({}, 'innerHTML', {
  17201. get: function get() {
  17202. return this.cloneNode(true).innerHTML;
  17203. },
  17204. set: function set(v) {
  17205. // make a dummy node to use innerHTML on
  17206. var dummy = document.createElement(this.nodeName.toLowerCase()); // set innerHTML to the value provided
  17207. dummy.innerHTML = v; // make a document fragment to hold the nodes from dummy
  17208. var docFrag = document.createDocumentFragment(); // copy all of the nodes created by the innerHTML on dummy
  17209. // to the document fragment
  17210. while (dummy.childNodes.length) {
  17211. docFrag.appendChild(dummy.childNodes[0]);
  17212. } // remove content
  17213. this.innerText = ''; // now we add all of that html in one by appending the
  17214. // document fragment. This is how innerHTML does it.
  17215. window.Element.prototype.appendChild.call(this, docFrag); // then return the result that innerHTML's setter would
  17216. return this.innerHTML;
  17217. }
  17218. });
  17219. /**
  17220. * Get a property descriptor given a list of priorities and the
  17221. * property to get.
  17222. */
  17223. var getDescriptor = function getDescriptor(priority, prop) {
  17224. var descriptor = {};
  17225. for (var i = 0; i < priority.length; i++) {
  17226. descriptor = Object.getOwnPropertyDescriptor(priority[i], prop);
  17227. if (descriptor && descriptor.set && descriptor.get) {
  17228. break;
  17229. }
  17230. }
  17231. descriptor.enumerable = true;
  17232. descriptor.configurable = true;
  17233. return descriptor;
  17234. };
  17235. var getInnerHTMLDescriptor = function getInnerHTMLDescriptor(tech) {
  17236. return getDescriptor([tech.el(), window.HTMLMediaElement.prototype, window.Element.prototype, innerHTMLDescriptorPolyfill], 'innerHTML');
  17237. };
  17238. /**
  17239. * Patches browser internal functions so that we can tell synchronously
  17240. * if a `<source>` was appended to the media element. For some reason this
  17241. * causes a `sourceset` if the the media element is ready and has no source.
  17242. * This happens when:
  17243. * - The page has just loaded and the media element does not have a source.
  17244. * - The media element was emptied of all sources, then `load()` was called.
  17245. *
  17246. * It does this by patching the following functions/properties when they are supported:
  17247. *
  17248. * - `append()` - can be used to add a `<source>` element to the media element
  17249. * - `appendChild()` - can be used to add a `<source>` element to the media element
  17250. * - `insertAdjacentHTML()` - can be used to add a `<source>` element to the media element
  17251. * - `innerHTML` - can be used to add a `<source>` element to the media element
  17252. *
  17253. * @param {Html5} tech
  17254. * The tech object that sourceset is being setup on.
  17255. */
  17256. var firstSourceWatch = function firstSourceWatch(tech) {
  17257. var el = tech.el(); // make sure firstSourceWatch isn't setup twice.
  17258. if (el.resetSourceWatch_) {
  17259. return;
  17260. }
  17261. var old = {};
  17262. var innerDescriptor = getInnerHTMLDescriptor(tech);
  17263. var appendWrapper = function appendWrapper(appendFn) {
  17264. return function () {
  17265. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  17266. args[_key] = arguments[_key];
  17267. }
  17268. var retval = appendFn.apply(el, args);
  17269. sourcesetLoad(tech);
  17270. return retval;
  17271. };
  17272. };
  17273. ['append', 'appendChild', 'insertAdjacentHTML'].forEach(function (k) {
  17274. if (!el[k]) {
  17275. return;
  17276. } // store the old function
  17277. old[k] = el[k]; // call the old function with a sourceset if a source
  17278. // was loaded
  17279. el[k] = appendWrapper(old[k]);
  17280. });
  17281. Object.defineProperty(el, 'innerHTML', mergeOptions$3(innerDescriptor, {
  17282. set: appendWrapper(innerDescriptor.set)
  17283. }));
  17284. el.resetSourceWatch_ = function () {
  17285. el.resetSourceWatch_ = null;
  17286. Object.keys(old).forEach(function (k) {
  17287. el[k] = old[k];
  17288. });
  17289. Object.defineProperty(el, 'innerHTML', innerDescriptor);
  17290. }; // on the first sourceset, we need to revert our changes
  17291. tech.one('sourceset', el.resetSourceWatch_);
  17292. };
  17293. /**
  17294. * our implementation of a `src` descriptor for browsers
  17295. * that do not have one.
  17296. */
  17297. var srcDescriptorPolyfill = Object.defineProperty({}, 'src', {
  17298. get: function get() {
  17299. if (this.hasAttribute('src')) {
  17300. return getAbsoluteURL(window.Element.prototype.getAttribute.call(this, 'src'));
  17301. }
  17302. return '';
  17303. },
  17304. set: function set(v) {
  17305. window.Element.prototype.setAttribute.call(this, 'src', v);
  17306. return v;
  17307. }
  17308. });
  17309. var getSrcDescriptor = function getSrcDescriptor(tech) {
  17310. return getDescriptor([tech.el(), window.HTMLMediaElement.prototype, srcDescriptorPolyfill], 'src');
  17311. };
  17312. /**
  17313. * setup `sourceset` handling on the `Html5` tech. This function
  17314. * patches the following element properties/functions:
  17315. *
  17316. * - `src` - to determine when `src` is set
  17317. * - `setAttribute()` - to determine when `src` is set
  17318. * - `load()` - this re-triggers the source selection algorithm, and can
  17319. * cause a sourceset.
  17320. *
  17321. * If there is no source when we are adding `sourceset` support or during a `load()`
  17322. * we also patch the functions listed in `firstSourceWatch`.
  17323. *
  17324. * @param {Html5} tech
  17325. * The tech to patch
  17326. */
  17327. var setupSourceset = function setupSourceset(tech) {
  17328. if (!tech.featuresSourceset) {
  17329. return;
  17330. }
  17331. var el = tech.el(); // make sure sourceset isn't setup twice.
  17332. if (el.resetSourceset_) {
  17333. return;
  17334. }
  17335. var srcDescriptor = getSrcDescriptor(tech);
  17336. var oldSetAttribute = el.setAttribute;
  17337. var oldLoad = el.load;
  17338. Object.defineProperty(el, 'src', mergeOptions$3(srcDescriptor, {
  17339. set: function set(v) {
  17340. var retval = srcDescriptor.set.call(el, v); // we use the getter here to get the actual value set on src
  17341. tech.triggerSourceset(el.src);
  17342. return retval;
  17343. }
  17344. }));
  17345. el.setAttribute = function (n, v) {
  17346. var retval = oldSetAttribute.call(el, n, v);
  17347. if (/src/i.test(n)) {
  17348. tech.triggerSourceset(el.src);
  17349. }
  17350. return retval;
  17351. };
  17352. el.load = function () {
  17353. var retval = oldLoad.call(el); // if load was called, but there was no source to fire
  17354. // sourceset on. We have to watch for a source append
  17355. // as that can trigger a `sourceset` when the media element
  17356. // has no source
  17357. if (!sourcesetLoad(tech)) {
  17358. tech.triggerSourceset('');
  17359. firstSourceWatch(tech);
  17360. }
  17361. return retval;
  17362. };
  17363. if (el.currentSrc) {
  17364. tech.triggerSourceset(el.currentSrc);
  17365. } else if (!sourcesetLoad(tech)) {
  17366. firstSourceWatch(tech);
  17367. }
  17368. el.resetSourceset_ = function () {
  17369. el.resetSourceset_ = null;
  17370. el.load = oldLoad;
  17371. el.setAttribute = oldSetAttribute;
  17372. Object.defineProperty(el, 'src', srcDescriptor);
  17373. if (el.resetSourceWatch_) {
  17374. el.resetSourceWatch_();
  17375. }
  17376. };
  17377. };
  17378. /**
  17379. * Object.defineProperty but "lazy", which means that the value is only set after
  17380. * it retrieved the first time, rather than being set right away.
  17381. *
  17382. * @param {Object} obj the object to set the property on
  17383. * @param {string} key the key for the property to set
  17384. * @param {Function} getValue the function used to get the value when it is needed.
  17385. * @param {boolean} setter wether a setter shoould be allowed or not
  17386. */
  17387. var defineLazyProperty = function defineLazyProperty(obj, key, getValue, setter) {
  17388. if (setter === void 0) {
  17389. setter = true;
  17390. }
  17391. var set = function set(value) {
  17392. return Object.defineProperty(obj, key, {
  17393. value: value,
  17394. enumerable: true,
  17395. writable: true
  17396. });
  17397. };
  17398. var options = {
  17399. configurable: true,
  17400. enumerable: true,
  17401. get: function get() {
  17402. var value = getValue();
  17403. set(value);
  17404. return value;
  17405. }
  17406. };
  17407. if (setter) {
  17408. options.set = set;
  17409. }
  17410. return Object.defineProperty(obj, key, options);
  17411. };
  17412. /**
  17413. * HTML5 Media Controller - Wrapper for HTML5 Media API
  17414. *
  17415. * @mixes Tech~SourceHandlerAdditions
  17416. * @extends Tech
  17417. */
  17418. var Html5 = /*#__PURE__*/function (_Tech) {
  17419. inheritsLoose(Html5, _Tech);
  17420. /**
  17421. * Create an instance of this Tech.
  17422. *
  17423. * @param {Object} [options]
  17424. * The key/value store of player options.
  17425. *
  17426. * @param {Component~ReadyCallback} ready
  17427. * Callback function to call when the `HTML5` Tech is ready.
  17428. */
  17429. function Html5(options, ready) {
  17430. var _this;
  17431. _this = _Tech.call(this, options, ready) || this;
  17432. var source = options.source;
  17433. var crossoriginTracks = false;
  17434. _this.featuresVideoFrameCallback = _this.featuresVideoFrameCallback && _this.el_.tagName === 'VIDEO'; // Set the source if one is provided
  17435. // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted)
  17436. // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source
  17437. // anyway so the error gets fired.
  17438. if (source && (_this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) {
  17439. _this.setSource(source);
  17440. } else {
  17441. _this.handleLateInit_(_this.el_);
  17442. } // setup sourceset after late sourceset/init
  17443. if (options.enableSourceset) {
  17444. _this.setupSourcesetHandling_();
  17445. }
  17446. _this.isScrubbing_ = false;
  17447. if (_this.el_.hasChildNodes()) {
  17448. var nodes = _this.el_.childNodes;
  17449. var nodesLength = nodes.length;
  17450. var removeNodes = [];
  17451. while (nodesLength--) {
  17452. var node = nodes[nodesLength];
  17453. var nodeName = node.nodeName.toLowerCase();
  17454. if (nodeName === 'track') {
  17455. if (!_this.featuresNativeTextTracks) {
  17456. // Empty video tag tracks so the built-in player doesn't use them also.
  17457. // This may not be fast enough to stop HTML5 browsers from reading the tags
  17458. // so we'll need to turn off any default tracks if we're manually doing
  17459. // captions and subtitles. videoElement.textTracks
  17460. removeNodes.push(node);
  17461. } else {
  17462. // store HTMLTrackElement and TextTrack to remote list
  17463. _this.remoteTextTrackEls().addTrackElement_(node);
  17464. _this.remoteTextTracks().addTrack(node.track);
  17465. _this.textTracks().addTrack(node.track);
  17466. if (!crossoriginTracks && !_this.el_.hasAttribute('crossorigin') && isCrossOrigin(node.src)) {
  17467. crossoriginTracks = true;
  17468. }
  17469. }
  17470. }
  17471. }
  17472. for (var i = 0; i < removeNodes.length; i++) {
  17473. _this.el_.removeChild(removeNodes[i]);
  17474. }
  17475. }
  17476. _this.proxyNativeTracks_();
  17477. if (_this.featuresNativeTextTracks && crossoriginTracks) {
  17478. 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.');
  17479. } // prevent iOS Safari from disabling metadata text tracks during native playback
  17480. _this.restoreMetadataTracksInIOSNativePlayer_(); // Determine if native controls should be used
  17481. // Our goal should be to get the custom controls on mobile solid everywhere
  17482. // so we can remove this all together. Right now this will block custom
  17483. // controls on touch enabled laptops like the Chrome Pixel
  17484. if ((TOUCH_ENABLED || IS_IPHONE || IS_NATIVE_ANDROID) && options.nativeControlsForTouch === true) {
  17485. _this.setControls(true);
  17486. } // on iOS, we want to proxy `webkitbeginfullscreen` and `webkitendfullscreen`
  17487. // into a `fullscreenchange` event
  17488. _this.proxyWebkitFullscreen_();
  17489. _this.triggerReady();
  17490. return _this;
  17491. }
  17492. /**
  17493. * Dispose of `HTML5` media element and remove all tracks.
  17494. */
  17495. var _proto = Html5.prototype;
  17496. _proto.dispose = function dispose() {
  17497. if (this.el_ && this.el_.resetSourceset_) {
  17498. this.el_.resetSourceset_();
  17499. }
  17500. Html5.disposeMediaElement(this.el_);
  17501. this.options_ = null; // tech will handle clearing of the emulated track list
  17502. _Tech.prototype.dispose.call(this);
  17503. }
  17504. /**
  17505. * Modify the media element so that we can detect when
  17506. * the source is changed. Fires `sourceset` just after the source has changed
  17507. */
  17508. ;
  17509. _proto.setupSourcesetHandling_ = function setupSourcesetHandling_() {
  17510. setupSourceset(this);
  17511. }
  17512. /**
  17513. * When a captions track is enabled in the iOS Safari native player, all other
  17514. * tracks are disabled (including metadata tracks), which nulls all of their
  17515. * associated cue points. This will restore metadata tracks to their pre-fullscreen
  17516. * state in those cases so that cue points are not needlessly lost.
  17517. *
  17518. * @private
  17519. */
  17520. ;
  17521. _proto.restoreMetadataTracksInIOSNativePlayer_ = function restoreMetadataTracksInIOSNativePlayer_() {
  17522. var textTracks = this.textTracks();
  17523. var metadataTracksPreFullscreenState; // captures a snapshot of every metadata track's current state
  17524. var takeMetadataTrackSnapshot = function takeMetadataTrackSnapshot() {
  17525. metadataTracksPreFullscreenState = [];
  17526. for (var i = 0; i < textTracks.length; i++) {
  17527. var track = textTracks[i];
  17528. if (track.kind === 'metadata') {
  17529. metadataTracksPreFullscreenState.push({
  17530. track: track,
  17531. storedMode: track.mode
  17532. });
  17533. }
  17534. }
  17535. }; // snapshot each metadata track's initial state, and update the snapshot
  17536. // each time there is a track 'change' event
  17537. takeMetadataTrackSnapshot();
  17538. textTracks.addEventListener('change', takeMetadataTrackSnapshot);
  17539. this.on('dispose', function () {
  17540. return textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
  17541. });
  17542. var restoreTrackMode = function restoreTrackMode() {
  17543. for (var i = 0; i < metadataTracksPreFullscreenState.length; i++) {
  17544. var storedTrack = metadataTracksPreFullscreenState[i];
  17545. if (storedTrack.track.mode === 'disabled' && storedTrack.track.mode !== storedTrack.storedMode) {
  17546. storedTrack.track.mode = storedTrack.storedMode;
  17547. }
  17548. } // we only want this handler to be executed on the first 'change' event
  17549. textTracks.removeEventListener('change', restoreTrackMode);
  17550. }; // when we enter fullscreen playback, stop updating the snapshot and
  17551. // restore all track modes to their pre-fullscreen state
  17552. this.on('webkitbeginfullscreen', function () {
  17553. textTracks.removeEventListener('change', takeMetadataTrackSnapshot); // remove the listener before adding it just in case it wasn't previously removed
  17554. textTracks.removeEventListener('change', restoreTrackMode);
  17555. textTracks.addEventListener('change', restoreTrackMode);
  17556. }); // start updating the snapshot again after leaving fullscreen
  17557. this.on('webkitendfullscreen', function () {
  17558. // remove the listener before adding it just in case it wasn't previously removed
  17559. textTracks.removeEventListener('change', takeMetadataTrackSnapshot);
  17560. textTracks.addEventListener('change', takeMetadataTrackSnapshot); // remove the restoreTrackMode handler in case it wasn't triggered during fullscreen playback
  17561. textTracks.removeEventListener('change', restoreTrackMode);
  17562. });
  17563. }
  17564. /**
  17565. * Attempt to force override of tracks for the given type
  17566. *
  17567. * @param {string} type - Track type to override, possible values include 'Audio',
  17568. * 'Video', and 'Text'.
  17569. * @param {boolean} override - If set to true native audio/video will be overridden,
  17570. * otherwise native audio/video will potentially be used.
  17571. * @private
  17572. */
  17573. ;
  17574. _proto.overrideNative_ = function overrideNative_(type, override) {
  17575. var _this2 = this;
  17576. // If there is no behavioral change don't add/remove listeners
  17577. if (override !== this["featuresNative" + type + "Tracks"]) {
  17578. return;
  17579. }
  17580. var lowerCaseType = type.toLowerCase();
  17581. if (this[lowerCaseType + "TracksListeners_"]) {
  17582. Object.keys(this[lowerCaseType + "TracksListeners_"]).forEach(function (eventName) {
  17583. var elTracks = _this2.el()[lowerCaseType + "Tracks"];
  17584. elTracks.removeEventListener(eventName, _this2[lowerCaseType + "TracksListeners_"][eventName]);
  17585. });
  17586. }
  17587. this["featuresNative" + type + "Tracks"] = !override;
  17588. this[lowerCaseType + "TracksListeners_"] = null;
  17589. this.proxyNativeTracksForType_(lowerCaseType);
  17590. }
  17591. /**
  17592. * Attempt to force override of native audio tracks.
  17593. *
  17594. * @param {boolean} override - If set to true native audio will be overridden,
  17595. * otherwise native audio will potentially be used.
  17596. */
  17597. ;
  17598. _proto.overrideNativeAudioTracks = function overrideNativeAudioTracks(override) {
  17599. this.overrideNative_('Audio', override);
  17600. }
  17601. /**
  17602. * Attempt to force override of native video tracks.
  17603. *
  17604. * @param {boolean} override - If set to true native video will be overridden,
  17605. * otherwise native video will potentially be used.
  17606. */
  17607. ;
  17608. _proto.overrideNativeVideoTracks = function overrideNativeVideoTracks(override) {
  17609. this.overrideNative_('Video', override);
  17610. }
  17611. /**
  17612. * Proxy native track list events for the given type to our track
  17613. * lists if the browser we are playing in supports that type of track list.
  17614. *
  17615. * @param {string} name - Track type; values include 'audio', 'video', and 'text'
  17616. * @private
  17617. */
  17618. ;
  17619. _proto.proxyNativeTracksForType_ = function proxyNativeTracksForType_(name) {
  17620. var _this3 = this;
  17621. var props = NORMAL[name];
  17622. var elTracks = this.el()[props.getterName];
  17623. var techTracks = this[props.getterName]();
  17624. if (!this["featuresNative" + props.capitalName + "Tracks"] || !elTracks || !elTracks.addEventListener) {
  17625. return;
  17626. }
  17627. var listeners = {
  17628. change: function change(e) {
  17629. var event = {
  17630. type: 'change',
  17631. target: techTracks,
  17632. currentTarget: techTracks,
  17633. srcElement: techTracks
  17634. };
  17635. techTracks.trigger(event); // if we are a text track change event, we should also notify the
  17636. // remote text track list. This can potentially cause a false positive
  17637. // if we were to get a change event on a non-remote track and
  17638. // we triggered the event on the remote text track list which doesn't
  17639. // contain that track. However, best practices mean looping through the
  17640. // list of tracks and searching for the appropriate mode value, so,
  17641. // this shouldn't pose an issue
  17642. if (name === 'text') {
  17643. _this3[REMOTE.remoteText.getterName]().trigger(event);
  17644. }
  17645. },
  17646. addtrack: function addtrack(e) {
  17647. techTracks.addTrack(e.track);
  17648. },
  17649. removetrack: function removetrack(e) {
  17650. techTracks.removeTrack(e.track);
  17651. }
  17652. };
  17653. var removeOldTracks = function removeOldTracks() {
  17654. var removeTracks = [];
  17655. for (var i = 0; i < techTracks.length; i++) {
  17656. var found = false;
  17657. for (var j = 0; j < elTracks.length; j++) {
  17658. if (elTracks[j] === techTracks[i]) {
  17659. found = true;
  17660. break;
  17661. }
  17662. }
  17663. if (!found) {
  17664. removeTracks.push(techTracks[i]);
  17665. }
  17666. }
  17667. while (removeTracks.length) {
  17668. techTracks.removeTrack(removeTracks.shift());
  17669. }
  17670. };
  17671. this[props.getterName + 'Listeners_'] = listeners;
  17672. Object.keys(listeners).forEach(function (eventName) {
  17673. var listener = listeners[eventName];
  17674. elTracks.addEventListener(eventName, listener);
  17675. _this3.on('dispose', function (e) {
  17676. return elTracks.removeEventListener(eventName, listener);
  17677. });
  17678. }); // Remove (native) tracks that are not used anymore
  17679. this.on('loadstart', removeOldTracks);
  17680. this.on('dispose', function (e) {
  17681. return _this3.off('loadstart', removeOldTracks);
  17682. });
  17683. }
  17684. /**
  17685. * Proxy all native track list events to our track lists if the browser we are playing
  17686. * in supports that type of track list.
  17687. *
  17688. * @private
  17689. */
  17690. ;
  17691. _proto.proxyNativeTracks_ = function proxyNativeTracks_() {
  17692. var _this4 = this;
  17693. NORMAL.names.forEach(function (name) {
  17694. _this4.proxyNativeTracksForType_(name);
  17695. });
  17696. }
  17697. /**
  17698. * Create the `Html5` Tech's DOM element.
  17699. *
  17700. * @return {Element}
  17701. * The element that gets created.
  17702. */
  17703. ;
  17704. _proto.createEl = function createEl() {
  17705. var el = this.options_.tag; // Check if this browser supports moving the element into the box.
  17706. // On the iPhone video will break if you move the element,
  17707. // So we have to create a brand new element.
  17708. // If we ingested the player div, we do not need to move the media element.
  17709. if (!el || !(this.options_.playerElIngest || this.movingMediaElementInDOM)) {
  17710. // If the original tag is still there, clone and remove it.
  17711. if (el) {
  17712. var clone = el.cloneNode(true);
  17713. if (el.parentNode) {
  17714. el.parentNode.insertBefore(clone, el);
  17715. }
  17716. Html5.disposeMediaElement(el);
  17717. el = clone;
  17718. } else {
  17719. el = document.createElement('video'); // determine if native controls should be used
  17720. var tagAttributes = this.options_.tag && getAttributes(this.options_.tag);
  17721. var attributes = mergeOptions$3({}, tagAttributes);
  17722. if (!TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) {
  17723. delete attributes.controls;
  17724. }
  17725. setAttributes(el, assign$1(attributes, {
  17726. id: this.options_.techId,
  17727. "class": 'vjs-tech'
  17728. }));
  17729. }
  17730. el.playerId = this.options_.playerId;
  17731. }
  17732. if (typeof this.options_.preload !== 'undefined') {
  17733. setAttribute(el, 'preload', this.options_.preload);
  17734. }
  17735. if (this.options_.disablePictureInPicture !== undefined) {
  17736. el.disablePictureInPicture = this.options_.disablePictureInPicture;
  17737. } // Update specific tag settings, in case they were overridden
  17738. // `autoplay` has to be *last* so that `muted` and `playsinline` are present
  17739. // when iOS/Safari or other browsers attempt to autoplay.
  17740. var settingsAttrs = ['loop', 'muted', 'playsinline', 'autoplay'];
  17741. for (var i = 0; i < settingsAttrs.length; i++) {
  17742. var attr = settingsAttrs[i];
  17743. var value = this.options_[attr];
  17744. if (typeof value !== 'undefined') {
  17745. if (value) {
  17746. setAttribute(el, attr, attr);
  17747. } else {
  17748. removeAttribute(el, attr);
  17749. }
  17750. el[attr] = value;
  17751. }
  17752. }
  17753. return el;
  17754. }
  17755. /**
  17756. * This will be triggered if the loadstart event has already fired, before videojs was
  17757. * ready. Two known examples of when this can happen are:
  17758. * 1. If we're loading the playback object after it has started loading
  17759. * 2. The media is already playing the (often with autoplay on) then
  17760. *
  17761. * This function will fire another loadstart so that videojs can catchup.
  17762. *
  17763. * @fires Tech#loadstart
  17764. *
  17765. * @return {undefined}
  17766. * returns nothing.
  17767. */
  17768. ;
  17769. _proto.handleLateInit_ = function handleLateInit_(el) {
  17770. if (el.networkState === 0 || el.networkState === 3) {
  17771. // The video element hasn't started loading the source yet
  17772. // or didn't find a source
  17773. return;
  17774. }
  17775. if (el.readyState === 0) {
  17776. // NetworkState is set synchronously BUT loadstart is fired at the
  17777. // end of the current stack, usually before setInterval(fn, 0).
  17778. // So at this point we know loadstart may have already fired or is
  17779. // about to fire, and either way the player hasn't seen it yet.
  17780. // We don't want to fire loadstart prematurely here and cause a
  17781. // double loadstart so we'll wait and see if it happens between now
  17782. // and the next loop, and fire it if not.
  17783. // HOWEVER, we also want to make sure it fires before loadedmetadata
  17784. // which could also happen between now and the next loop, so we'll
  17785. // watch for that also.
  17786. var loadstartFired = false;
  17787. var setLoadstartFired = function setLoadstartFired() {
  17788. loadstartFired = true;
  17789. };
  17790. this.on('loadstart', setLoadstartFired);
  17791. var triggerLoadstart = function triggerLoadstart() {
  17792. // We did miss the original loadstart. Make sure the player
  17793. // sees loadstart before loadedmetadata
  17794. if (!loadstartFired) {
  17795. this.trigger('loadstart');
  17796. }
  17797. };
  17798. this.on('loadedmetadata', triggerLoadstart);
  17799. this.ready(function () {
  17800. this.off('loadstart', setLoadstartFired);
  17801. this.off('loadedmetadata', triggerLoadstart);
  17802. if (!loadstartFired) {
  17803. // We did miss the original native loadstart. Fire it now.
  17804. this.trigger('loadstart');
  17805. }
  17806. });
  17807. return;
  17808. } // From here on we know that loadstart already fired and we missed it.
  17809. // The other readyState events aren't as much of a problem if we double
  17810. // them, so not going to go to as much trouble as loadstart to prevent
  17811. // that unless we find reason to.
  17812. var eventsToTrigger = ['loadstart']; // loadedmetadata: newly equal to HAVE_METADATA (1) or greater
  17813. eventsToTrigger.push('loadedmetadata'); // loadeddata: newly increased to HAVE_CURRENT_DATA (2) or greater
  17814. if (el.readyState >= 2) {
  17815. eventsToTrigger.push('loadeddata');
  17816. } // canplay: newly increased to HAVE_FUTURE_DATA (3) or greater
  17817. if (el.readyState >= 3) {
  17818. eventsToTrigger.push('canplay');
  17819. } // canplaythrough: newly equal to HAVE_ENOUGH_DATA (4)
  17820. if (el.readyState >= 4) {
  17821. eventsToTrigger.push('canplaythrough');
  17822. } // We still need to give the player time to add event listeners
  17823. this.ready(function () {
  17824. eventsToTrigger.forEach(function (type) {
  17825. this.trigger(type);
  17826. }, this);
  17827. });
  17828. }
  17829. /**
  17830. * Set whether we are scrubbing or not.
  17831. * This is used to decide whether we should use `fastSeek` or not.
  17832. * `fastSeek` is used to provide trick play on Safari browsers.
  17833. *
  17834. * @param {boolean} isScrubbing
  17835. * - true for we are currently scrubbing
  17836. * - false for we are no longer scrubbing
  17837. */
  17838. ;
  17839. _proto.setScrubbing = function setScrubbing(isScrubbing) {
  17840. this.isScrubbing_ = isScrubbing;
  17841. }
  17842. /**
  17843. * Get whether we are scrubbing or not.
  17844. *
  17845. * @return {boolean} isScrubbing
  17846. * - true for we are currently scrubbing
  17847. * - false for we are no longer scrubbing
  17848. */
  17849. ;
  17850. _proto.scrubbing = function scrubbing() {
  17851. return this.isScrubbing_;
  17852. }
  17853. /**
  17854. * Set current time for the `HTML5` tech.
  17855. *
  17856. * @param {number} seconds
  17857. * Set the current time of the media to this.
  17858. */
  17859. ;
  17860. _proto.setCurrentTime = function setCurrentTime(seconds) {
  17861. try {
  17862. if (this.isScrubbing_ && this.el_.fastSeek && IS_ANY_SAFARI) {
  17863. this.el_.fastSeek(seconds);
  17864. } else {
  17865. this.el_.currentTime = seconds;
  17866. }
  17867. } catch (e) {
  17868. log$1(e, 'Video is not ready. (Video.js)'); // this.warning(VideoJS.warnings.videoNotReady);
  17869. }
  17870. }
  17871. /**
  17872. * Get the current duration of the HTML5 media element.
  17873. *
  17874. * @return {number}
  17875. * The duration of the media or 0 if there is no duration.
  17876. */
  17877. ;
  17878. _proto.duration = function duration() {
  17879. var _this5 = this;
  17880. // Android Chrome will report duration as Infinity for VOD HLS until after
  17881. // playback has started, which triggers the live display erroneously.
  17882. // Return NaN if playback has not started and trigger a durationupdate once
  17883. // the duration can be reliably known.
  17884. if (this.el_.duration === Infinity && IS_ANDROID && IS_CHROME && this.el_.currentTime === 0) {
  17885. // Wait for the first `timeupdate` with currentTime > 0 - there may be
  17886. // several with 0
  17887. var checkProgress = function checkProgress() {
  17888. if (_this5.el_.currentTime > 0) {
  17889. // Trigger durationchange for genuinely live video
  17890. if (_this5.el_.duration === Infinity) {
  17891. _this5.trigger('durationchange');
  17892. }
  17893. _this5.off('timeupdate', checkProgress);
  17894. }
  17895. };
  17896. this.on('timeupdate', checkProgress);
  17897. return NaN;
  17898. }
  17899. return this.el_.duration || NaN;
  17900. }
  17901. /**
  17902. * Get the current width of the HTML5 media element.
  17903. *
  17904. * @return {number}
  17905. * The width of the HTML5 media element.
  17906. */
  17907. ;
  17908. _proto.width = function width() {
  17909. return this.el_.offsetWidth;
  17910. }
  17911. /**
  17912. * Get the current height of the HTML5 media element.
  17913. *
  17914. * @return {number}
  17915. * The height of the HTML5 media element.
  17916. */
  17917. ;
  17918. _proto.height = function height() {
  17919. return this.el_.offsetHeight;
  17920. }
  17921. /**
  17922. * Proxy iOS `webkitbeginfullscreen` and `webkitendfullscreen` into
  17923. * `fullscreenchange` event.
  17924. *
  17925. * @private
  17926. * @fires fullscreenchange
  17927. * @listens webkitendfullscreen
  17928. * @listens webkitbeginfullscreen
  17929. * @listens webkitbeginfullscreen
  17930. */
  17931. ;
  17932. _proto.proxyWebkitFullscreen_ = function proxyWebkitFullscreen_() {
  17933. var _this6 = this;
  17934. if (!('webkitDisplayingFullscreen' in this.el_)) {
  17935. return;
  17936. }
  17937. var endFn = function endFn() {
  17938. this.trigger('fullscreenchange', {
  17939. isFullscreen: false
  17940. }); // Safari will sometimes set contols on the videoelement when existing fullscreen.
  17941. if (this.el_.controls && !this.options_.nativeControlsForTouch && this.controls()) {
  17942. this.el_.controls = false;
  17943. }
  17944. };
  17945. var beginFn = function beginFn() {
  17946. if ('webkitPresentationMode' in this.el_ && this.el_.webkitPresentationMode !== 'picture-in-picture') {
  17947. this.one('webkitendfullscreen', endFn);
  17948. this.trigger('fullscreenchange', {
  17949. isFullscreen: true,
  17950. // set a flag in case another tech triggers fullscreenchange
  17951. nativeIOSFullscreen: true
  17952. });
  17953. }
  17954. };
  17955. this.on('webkitbeginfullscreen', beginFn);
  17956. this.on('dispose', function () {
  17957. _this6.off('webkitbeginfullscreen', beginFn);
  17958. _this6.off('webkitendfullscreen', endFn);
  17959. });
  17960. }
  17961. /**
  17962. * Check if fullscreen is supported on the current playback device.
  17963. *
  17964. * @return {boolean}
  17965. * - True if fullscreen is supported.
  17966. * - False if fullscreen is not supported.
  17967. */
  17968. ;
  17969. _proto.supportsFullScreen = function supportsFullScreen() {
  17970. if (typeof this.el_.webkitEnterFullScreen === 'function') {
  17971. var userAgent = window.navigator && window.navigator.userAgent || ''; // Seems to be broken in Chromium/Chrome && Safari in Leopard
  17972. if (/Android/.test(userAgent) || !/Chrome|Mac OS X 10.5/.test(userAgent)) {
  17973. return true;
  17974. }
  17975. }
  17976. return false;
  17977. }
  17978. /**
  17979. * Request that the `HTML5` Tech enter fullscreen.
  17980. */
  17981. ;
  17982. _proto.enterFullScreen = function enterFullScreen() {
  17983. var video = this.el_;
  17984. if (video.paused && video.networkState <= video.HAVE_METADATA) {
  17985. // attempt to prime the video element for programmatic access
  17986. // this isn't necessary on the desktop but shouldn't hurt
  17987. silencePromise(this.el_.play()); // playing and pausing synchronously during the transition to fullscreen
  17988. // can get iOS ~6.1 devices into a play/pause loop
  17989. this.setTimeout(function () {
  17990. video.pause();
  17991. try {
  17992. video.webkitEnterFullScreen();
  17993. } catch (e) {
  17994. this.trigger('fullscreenerror', e);
  17995. }
  17996. }, 0);
  17997. } else {
  17998. try {
  17999. video.webkitEnterFullScreen();
  18000. } catch (e) {
  18001. this.trigger('fullscreenerror', e);
  18002. }
  18003. }
  18004. }
  18005. /**
  18006. * Request that the `HTML5` Tech exit fullscreen.
  18007. */
  18008. ;
  18009. _proto.exitFullScreen = function exitFullScreen() {
  18010. if (!this.el_.webkitDisplayingFullscreen) {
  18011. this.trigger('fullscreenerror', new Error('The video is not fullscreen'));
  18012. return;
  18013. }
  18014. this.el_.webkitExitFullScreen();
  18015. }
  18016. /**
  18017. * Create a floating video window always on top of other windows so that users may
  18018. * continue consuming media while they interact with other content sites, or
  18019. * applications on their device.
  18020. *
  18021. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  18022. *
  18023. * @return {Promise}
  18024. * A promise with a Picture-in-Picture window.
  18025. */
  18026. ;
  18027. _proto.requestPictureInPicture = function requestPictureInPicture() {
  18028. return this.el_.requestPictureInPicture();
  18029. }
  18030. /**
  18031. * Native requestVideoFrameCallback if supported by browser/tech, or fallback
  18032. * Don't use rVCF on Safari when DRM is playing, as it doesn't fire
  18033. * Needs to be checked later than the constructor
  18034. * This will be a false positive for clear sources loaded after a Fairplay source
  18035. *
  18036. * @param {function} cb function to call
  18037. * @return {number} id of request
  18038. */
  18039. ;
  18040. _proto.requestVideoFrameCallback = function requestVideoFrameCallback(cb) {
  18041. if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
  18042. return this.el_.requestVideoFrameCallback(cb);
  18043. }
  18044. return _Tech.prototype.requestVideoFrameCallback.call(this, cb);
  18045. }
  18046. /**
  18047. * Native or fallback requestVideoFrameCallback
  18048. *
  18049. * @param {number} id request id to cancel
  18050. */
  18051. ;
  18052. _proto.cancelVideoFrameCallback = function cancelVideoFrameCallback(id) {
  18053. if (this.featuresVideoFrameCallback && !this.el_.webkitKeys) {
  18054. this.el_.cancelVideoFrameCallback(id);
  18055. } else {
  18056. _Tech.prototype.cancelVideoFrameCallback.call(this, id);
  18057. }
  18058. }
  18059. /**
  18060. * A getter/setter for the `Html5` Tech's source object.
  18061. * > Note: Please use {@link Html5#setSource}
  18062. *
  18063. * @param {Tech~SourceObject} [src]
  18064. * The source object you want to set on the `HTML5` techs element.
  18065. *
  18066. * @return {Tech~SourceObject|undefined}
  18067. * - The current source object when a source is not passed in.
  18068. * - undefined when setting
  18069. *
  18070. * @deprecated Since version 5.
  18071. */
  18072. ;
  18073. _proto.src = function src(_src) {
  18074. if (_src === undefined) {
  18075. return this.el_.src;
  18076. } // Setting src through `src` instead of `setSrc` will be deprecated
  18077. this.setSrc(_src);
  18078. }
  18079. /**
  18080. * Reset the tech by removing all sources and then calling
  18081. * {@link Html5.resetMediaElement}.
  18082. */
  18083. ;
  18084. _proto.reset = function reset() {
  18085. Html5.resetMediaElement(this.el_);
  18086. }
  18087. /**
  18088. * Get the current source on the `HTML5` Tech. Falls back to returning the source from
  18089. * the HTML5 media element.
  18090. *
  18091. * @return {Tech~SourceObject}
  18092. * The current source object from the HTML5 tech. With a fallback to the
  18093. * elements source.
  18094. */
  18095. ;
  18096. _proto.currentSrc = function currentSrc() {
  18097. if (this.currentSource_) {
  18098. return this.currentSource_.src;
  18099. }
  18100. return this.el_.currentSrc;
  18101. }
  18102. /**
  18103. * Set controls attribute for the HTML5 media Element.
  18104. *
  18105. * @param {string} val
  18106. * Value to set the controls attribute to
  18107. */
  18108. ;
  18109. _proto.setControls = function setControls(val) {
  18110. this.el_.controls = !!val;
  18111. }
  18112. /**
  18113. * Create and returns a remote {@link TextTrack} object.
  18114. *
  18115. * @param {string} kind
  18116. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata)
  18117. *
  18118. * @param {string} [label]
  18119. * Label to identify the text track
  18120. *
  18121. * @param {string} [language]
  18122. * Two letter language abbreviation
  18123. *
  18124. * @return {TextTrack}
  18125. * The TextTrack that gets created.
  18126. */
  18127. ;
  18128. _proto.addTextTrack = function addTextTrack(kind, label, language) {
  18129. if (!this.featuresNativeTextTracks) {
  18130. return _Tech.prototype.addTextTrack.call(this, kind, label, language);
  18131. }
  18132. return this.el_.addTextTrack(kind, label, language);
  18133. }
  18134. /**
  18135. * Creates either native TextTrack or an emulated TextTrack depending
  18136. * on the value of `featuresNativeTextTracks`
  18137. *
  18138. * @param {Object} options
  18139. * The object should contain the options to initialize the TextTrack with.
  18140. *
  18141. * @param {string} [options.kind]
  18142. * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata).
  18143. *
  18144. * @param {string} [options.label]
  18145. * Label to identify the text track
  18146. *
  18147. * @param {string} [options.language]
  18148. * Two letter language abbreviation.
  18149. *
  18150. * @param {boolean} [options.default]
  18151. * Default this track to on.
  18152. *
  18153. * @param {string} [options.id]
  18154. * The internal id to assign this track.
  18155. *
  18156. * @param {string} [options.src]
  18157. * A source url for the track.
  18158. *
  18159. * @return {HTMLTrackElement}
  18160. * The track element that gets created.
  18161. */
  18162. ;
  18163. _proto.createRemoteTextTrack = function createRemoteTextTrack(options) {
  18164. if (!this.featuresNativeTextTracks) {
  18165. return _Tech.prototype.createRemoteTextTrack.call(this, options);
  18166. }
  18167. var htmlTrackElement = document.createElement('track');
  18168. if (options.kind) {
  18169. htmlTrackElement.kind = options.kind;
  18170. }
  18171. if (options.label) {
  18172. htmlTrackElement.label = options.label;
  18173. }
  18174. if (options.language || options.srclang) {
  18175. htmlTrackElement.srclang = options.language || options.srclang;
  18176. }
  18177. if (options["default"]) {
  18178. htmlTrackElement["default"] = options["default"];
  18179. }
  18180. if (options.id) {
  18181. htmlTrackElement.id = options.id;
  18182. }
  18183. if (options.src) {
  18184. htmlTrackElement.src = options.src;
  18185. }
  18186. return htmlTrackElement;
  18187. }
  18188. /**
  18189. * Creates a remote text track object and returns an html track element.
  18190. *
  18191. * @param {Object} options The object should contain values for
  18192. * kind, language, label, and src (location of the WebVTT file)
  18193. * @param {boolean} [manualCleanup=true] if set to false, the TextTrack will be
  18194. * automatically removed from the video element whenever the source changes
  18195. * @return {HTMLTrackElement} An Html Track Element.
  18196. * This can be an emulated {@link HTMLTrackElement} or a native one.
  18197. * @deprecated The default value of the "manualCleanup" parameter will default
  18198. * to "false" in upcoming versions of Video.js
  18199. */
  18200. ;
  18201. _proto.addRemoteTextTrack = function addRemoteTextTrack(options, manualCleanup) {
  18202. var htmlTrackElement = _Tech.prototype.addRemoteTextTrack.call(this, options, manualCleanup);
  18203. if (this.featuresNativeTextTracks) {
  18204. this.el().appendChild(htmlTrackElement);
  18205. }
  18206. return htmlTrackElement;
  18207. }
  18208. /**
  18209. * Remove remote `TextTrack` from `TextTrackList` object
  18210. *
  18211. * @param {TextTrack} track
  18212. * `TextTrack` object to remove
  18213. */
  18214. ;
  18215. _proto.removeRemoteTextTrack = function removeRemoteTextTrack(track) {
  18216. _Tech.prototype.removeRemoteTextTrack.call(this, track);
  18217. if (this.featuresNativeTextTracks) {
  18218. var tracks = this.$$('track');
  18219. var i = tracks.length;
  18220. while (i--) {
  18221. if (track === tracks[i] || track === tracks[i].track) {
  18222. this.el().removeChild(tracks[i]);
  18223. }
  18224. }
  18225. }
  18226. }
  18227. /**
  18228. * Gets available media playback quality metrics as specified by the W3C's Media
  18229. * Playback Quality API.
  18230. *
  18231. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  18232. *
  18233. * @return {Object}
  18234. * An object with supported media playback quality metrics
  18235. */
  18236. ;
  18237. _proto.getVideoPlaybackQuality = function getVideoPlaybackQuality() {
  18238. if (typeof this.el().getVideoPlaybackQuality === 'function') {
  18239. return this.el().getVideoPlaybackQuality();
  18240. }
  18241. var videoPlaybackQuality = {};
  18242. if (typeof this.el().webkitDroppedFrameCount !== 'undefined' && typeof this.el().webkitDecodedFrameCount !== 'undefined') {
  18243. videoPlaybackQuality.droppedVideoFrames = this.el().webkitDroppedFrameCount;
  18244. videoPlaybackQuality.totalVideoFrames = this.el().webkitDecodedFrameCount;
  18245. }
  18246. if (window.performance && typeof window.performance.now === 'function') {
  18247. videoPlaybackQuality.creationTime = window.performance.now();
  18248. } else if (window.performance && window.performance.timing && typeof window.performance.timing.navigationStart === 'number') {
  18249. videoPlaybackQuality.creationTime = window.Date.now() - window.performance.timing.navigationStart;
  18250. }
  18251. return videoPlaybackQuality;
  18252. };
  18253. return Html5;
  18254. }(Tech);
  18255. /* HTML5 Support Testing ---------------------------------------------------- */
  18256. /**
  18257. * Element for testing browser HTML5 media capabilities
  18258. *
  18259. * @type {Element}
  18260. * @constant
  18261. * @private
  18262. */
  18263. defineLazyProperty(Html5, 'TEST_VID', function () {
  18264. if (!isReal()) {
  18265. return;
  18266. }
  18267. var video = document.createElement('video');
  18268. var track = document.createElement('track');
  18269. track.kind = 'captions';
  18270. track.srclang = 'en';
  18271. track.label = 'English';
  18272. video.appendChild(track);
  18273. return video;
  18274. });
  18275. /**
  18276. * Check if HTML5 media is supported by this browser/device.
  18277. *
  18278. * @return {boolean}
  18279. * - True if HTML5 media is supported.
  18280. * - False if HTML5 media is not supported.
  18281. */
  18282. Html5.isSupported = function () {
  18283. // IE with no Media Player is a LIAR! (#984)
  18284. try {
  18285. Html5.TEST_VID.volume = 0.5;
  18286. } catch (e) {
  18287. return false;
  18288. }
  18289. return !!(Html5.TEST_VID && Html5.TEST_VID.canPlayType);
  18290. };
  18291. /**
  18292. * Check if the tech can support the given type
  18293. *
  18294. * @param {string} type
  18295. * The mimetype to check
  18296. * @return {string} 'probably', 'maybe', or '' (empty string)
  18297. */
  18298. Html5.canPlayType = function (type) {
  18299. return Html5.TEST_VID.canPlayType(type);
  18300. };
  18301. /**
  18302. * Check if the tech can support the given source
  18303. *
  18304. * @param {Object} srcObj
  18305. * The source object
  18306. * @param {Object} options
  18307. * The options passed to the tech
  18308. * @return {string} 'probably', 'maybe', or '' (empty string)
  18309. */
  18310. Html5.canPlaySource = function (srcObj, options) {
  18311. return Html5.canPlayType(srcObj.type);
  18312. };
  18313. /**
  18314. * Check if the volume can be changed in this browser/device.
  18315. * Volume cannot be changed in a lot of mobile devices.
  18316. * Specifically, it can't be changed from 1 on iOS.
  18317. *
  18318. * @return {boolean}
  18319. * - True if volume can be controlled
  18320. * - False otherwise
  18321. */
  18322. Html5.canControlVolume = function () {
  18323. // IE will error if Windows Media Player not installed #3315
  18324. try {
  18325. var volume = Html5.TEST_VID.volume;
  18326. Html5.TEST_VID.volume = volume / 2 + 0.1;
  18327. var canControl = volume !== Html5.TEST_VID.volume; // With the introduction of iOS 15, there are cases where the volume is read as
  18328. // changed but reverts back to its original state at the start of the next tick.
  18329. // To determine whether volume can be controlled on iOS,
  18330. // a timeout is set and the volume is checked asynchronously.
  18331. // Since `features` doesn't currently work asynchronously, the value is manually set.
  18332. if (canControl && IS_IOS) {
  18333. window.setTimeout(function () {
  18334. if (Html5 && Html5.prototype) {
  18335. Html5.prototype.featuresVolumeControl = volume !== Html5.TEST_VID.volume;
  18336. }
  18337. }); // default iOS to false, which will be updated in the timeout above.
  18338. return false;
  18339. }
  18340. return canControl;
  18341. } catch (e) {
  18342. return false;
  18343. }
  18344. };
  18345. /**
  18346. * Check if the volume can be muted in this browser/device.
  18347. * Some devices, e.g. iOS, don't allow changing volume
  18348. * but permits muting/unmuting.
  18349. *
  18350. * @return {bolean}
  18351. * - True if volume can be muted
  18352. * - False otherwise
  18353. */
  18354. Html5.canMuteVolume = function () {
  18355. try {
  18356. var muted = Html5.TEST_VID.muted; // in some versions of iOS muted property doesn't always
  18357. // work, so we want to set both property and attribute
  18358. Html5.TEST_VID.muted = !muted;
  18359. if (Html5.TEST_VID.muted) {
  18360. setAttribute(Html5.TEST_VID, 'muted', 'muted');
  18361. } else {
  18362. removeAttribute(Html5.TEST_VID, 'muted', 'muted');
  18363. }
  18364. return muted !== Html5.TEST_VID.muted;
  18365. } catch (e) {
  18366. return false;
  18367. }
  18368. };
  18369. /**
  18370. * Check if the playback rate can be changed in this browser/device.
  18371. *
  18372. * @return {boolean}
  18373. * - True if playback rate can be controlled
  18374. * - False otherwise
  18375. */
  18376. Html5.canControlPlaybackRate = function () {
  18377. // Playback rate API is implemented in Android Chrome, but doesn't do anything
  18378. // https://github.com/videojs/video.js/issues/3180
  18379. if (IS_ANDROID && IS_CHROME && CHROME_VERSION < 58) {
  18380. return false;
  18381. } // IE will error if Windows Media Player not installed #3315
  18382. try {
  18383. var playbackRate = Html5.TEST_VID.playbackRate;
  18384. Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1;
  18385. return playbackRate !== Html5.TEST_VID.playbackRate;
  18386. } catch (e) {
  18387. return false;
  18388. }
  18389. };
  18390. /**
  18391. * Check if we can override a video/audio elements attributes, with
  18392. * Object.defineProperty.
  18393. *
  18394. * @return {boolean}
  18395. * - True if builtin attributes can be overridden
  18396. * - False otherwise
  18397. */
  18398. Html5.canOverrideAttributes = function () {
  18399. // if we cannot overwrite the src/innerHTML property, there is no support
  18400. // iOS 7 safari for instance cannot do this.
  18401. try {
  18402. var noop = function noop() {};
  18403. Object.defineProperty(document.createElement('video'), 'src', {
  18404. get: noop,
  18405. set: noop
  18406. });
  18407. Object.defineProperty(document.createElement('audio'), 'src', {
  18408. get: noop,
  18409. set: noop
  18410. });
  18411. Object.defineProperty(document.createElement('video'), 'innerHTML', {
  18412. get: noop,
  18413. set: noop
  18414. });
  18415. Object.defineProperty(document.createElement('audio'), 'innerHTML', {
  18416. get: noop,
  18417. set: noop
  18418. });
  18419. } catch (e) {
  18420. return false;
  18421. }
  18422. return true;
  18423. };
  18424. /**
  18425. * Check to see if native `TextTrack`s are supported by this browser/device.
  18426. *
  18427. * @return {boolean}
  18428. * - True if native `TextTrack`s are supported.
  18429. * - False otherwise
  18430. */
  18431. Html5.supportsNativeTextTracks = function () {
  18432. return IS_ANY_SAFARI || IS_IOS && IS_CHROME;
  18433. };
  18434. /**
  18435. * Check to see if native `VideoTrack`s are supported by this browser/device
  18436. *
  18437. * @return {boolean}
  18438. * - True if native `VideoTrack`s are supported.
  18439. * - False otherwise
  18440. */
  18441. Html5.supportsNativeVideoTracks = function () {
  18442. return !!(Html5.TEST_VID && Html5.TEST_VID.videoTracks);
  18443. };
  18444. /**
  18445. * Check to see if native `AudioTrack`s are supported by this browser/device
  18446. *
  18447. * @return {boolean}
  18448. * - True if native `AudioTrack`s are supported.
  18449. * - False otherwise
  18450. */
  18451. Html5.supportsNativeAudioTracks = function () {
  18452. return !!(Html5.TEST_VID && Html5.TEST_VID.audioTracks);
  18453. };
  18454. /**
  18455. * An array of events available on the Html5 tech.
  18456. *
  18457. * @private
  18458. * @type {Array}
  18459. */
  18460. 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'];
  18461. /**
  18462. * Boolean indicating whether the `Tech` supports volume control.
  18463. *
  18464. * @type {boolean}
  18465. * @default {@link Html5.canControlVolume}
  18466. */
  18467. /**
  18468. * Boolean indicating whether the `Tech` supports muting volume.
  18469. *
  18470. * @type {bolean}
  18471. * @default {@link Html5.canMuteVolume}
  18472. */
  18473. /**
  18474. * Boolean indicating whether the `Tech` supports changing the speed at which the media
  18475. * plays. Examples:
  18476. * - Set player to play 2x (twice) as fast
  18477. * - Set player to play 0.5x (half) as fast
  18478. *
  18479. * @type {boolean}
  18480. * @default {@link Html5.canControlPlaybackRate}
  18481. */
  18482. /**
  18483. * Boolean indicating whether the `Tech` supports the `sourceset` event.
  18484. *
  18485. * @type {boolean}
  18486. * @default
  18487. */
  18488. /**
  18489. * Boolean indicating whether the `HTML5` tech currently supports native `TextTrack`s.
  18490. *
  18491. * @type {boolean}
  18492. * @default {@link Html5.supportsNativeTextTracks}
  18493. */
  18494. /**
  18495. * Boolean indicating whether the `HTML5` tech currently supports native `VideoTrack`s.
  18496. *
  18497. * @type {boolean}
  18498. * @default {@link Html5.supportsNativeVideoTracks}
  18499. */
  18500. /**
  18501. * Boolean indicating whether the `HTML5` tech currently supports native `AudioTrack`s.
  18502. *
  18503. * @type {boolean}
  18504. * @default {@link Html5.supportsNativeAudioTracks}
  18505. */
  18506. [['featuresMuteControl', 'canMuteVolume'], ['featuresPlaybackRate', 'canControlPlaybackRate'], ['featuresSourceset', 'canOverrideAttributes'], ['featuresNativeTextTracks', 'supportsNativeTextTracks'], ['featuresNativeVideoTracks', 'supportsNativeVideoTracks'], ['featuresNativeAudioTracks', 'supportsNativeAudioTracks']].forEach(function (_ref) {
  18507. var key = _ref[0],
  18508. fn = _ref[1];
  18509. defineLazyProperty(Html5.prototype, key, function () {
  18510. return Html5[fn]();
  18511. }, true);
  18512. });
  18513. Html5.prototype.featuresVolumeControl = Html5.canControlVolume();
  18514. /**
  18515. * Boolean indicating whether the `HTML5` tech currently supports the media element
  18516. * moving in the DOM. iOS breaks if you move the media element, so this is set this to
  18517. * false there. Everywhere else this should be true.
  18518. *
  18519. * @type {boolean}
  18520. * @default
  18521. */
  18522. Html5.prototype.movingMediaElementInDOM = !IS_IOS; // TODO: Previous comment: No longer appears to be used. Can probably be removed.
  18523. // Is this true?
  18524. /**
  18525. * Boolean indicating whether the `HTML5` tech currently supports automatic media resize
  18526. * when going into fullscreen.
  18527. *
  18528. * @type {boolean}
  18529. * @default
  18530. */
  18531. Html5.prototype.featuresFullscreenResize = true;
  18532. /**
  18533. * Boolean indicating whether the `HTML5` tech currently supports the progress event.
  18534. * If this is false, manual `progress` events will be triggered instead.
  18535. *
  18536. * @type {boolean}
  18537. * @default
  18538. */
  18539. Html5.prototype.featuresProgressEvents = true;
  18540. /**
  18541. * Boolean indicating whether the `HTML5` tech currently supports the timeupdate event.
  18542. * If this is false, manual `timeupdate` events will be triggered instead.
  18543. *
  18544. * @default
  18545. */
  18546. Html5.prototype.featuresTimeupdateEvents = true;
  18547. /**
  18548. * Whether the HTML5 el supports `requestVideoFrameCallback`
  18549. *
  18550. * @type {boolean}
  18551. */
  18552. Html5.prototype.featuresVideoFrameCallback = !!(Html5.TEST_VID && Html5.TEST_VID.requestVideoFrameCallback); // HTML5 Feature detection and Device Fixes --------------------------------- //
  18553. var canPlayType;
  18554. Html5.patchCanPlayType = function () {
  18555. // Android 4.0 and above can play HLS to some extent but it reports being unable to do so
  18556. // Firefox and Chrome report correctly
  18557. if (ANDROID_VERSION >= 4.0 && !IS_FIREFOX && !IS_CHROME) {
  18558. canPlayType = Html5.TEST_VID && Html5.TEST_VID.constructor.prototype.canPlayType;
  18559. Html5.TEST_VID.constructor.prototype.canPlayType = function (type) {
  18560. var mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i;
  18561. if (type && mpegurlRE.test(type)) {
  18562. return 'maybe';
  18563. }
  18564. return canPlayType.call(this, type);
  18565. };
  18566. }
  18567. };
  18568. Html5.unpatchCanPlayType = function () {
  18569. var r = Html5.TEST_VID.constructor.prototype.canPlayType;
  18570. if (canPlayType) {
  18571. Html5.TEST_VID.constructor.prototype.canPlayType = canPlayType;
  18572. }
  18573. return r;
  18574. }; // by default, patch the media element
  18575. Html5.patchCanPlayType();
  18576. Html5.disposeMediaElement = function (el) {
  18577. if (!el) {
  18578. return;
  18579. }
  18580. if (el.parentNode) {
  18581. el.parentNode.removeChild(el);
  18582. } // remove any child track or source nodes to prevent their loading
  18583. while (el.hasChildNodes()) {
  18584. el.removeChild(el.firstChild);
  18585. } // remove any src reference. not setting `src=''` because that causes a warning
  18586. // in firefox
  18587. el.removeAttribute('src'); // force the media element to update its loading state by calling load()
  18588. // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793)
  18589. if (typeof el.load === 'function') {
  18590. // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
  18591. (function () {
  18592. try {
  18593. el.load();
  18594. } catch (e) {// not supported
  18595. }
  18596. })();
  18597. }
  18598. };
  18599. Html5.resetMediaElement = function (el) {
  18600. if (!el) {
  18601. return;
  18602. }
  18603. var sources = el.querySelectorAll('source');
  18604. var i = sources.length;
  18605. while (i--) {
  18606. el.removeChild(sources[i]);
  18607. } // remove any src reference.
  18608. // not setting `src=''` because that throws an error
  18609. el.removeAttribute('src');
  18610. if (typeof el.load === 'function') {
  18611. // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473)
  18612. (function () {
  18613. try {
  18614. el.load();
  18615. } catch (e) {// satisfy linter
  18616. }
  18617. })();
  18618. }
  18619. };
  18620. /* Native HTML5 element property wrapping ----------------------------------- */
  18621. // Wrap native boolean attributes with getters that check both property and attribute
  18622. // The list is as followed:
  18623. // muted, defaultMuted, autoplay, controls, loop, playsinline
  18624. [
  18625. /**
  18626. * Get the value of `muted` from the media element. `muted` indicates
  18627. * that the volume for the media should be set to silent. This does not actually change
  18628. * the `volume` attribute.
  18629. *
  18630. * @method Html5#muted
  18631. * @return {boolean}
  18632. * - True if the value of `volume` should be ignored and the audio set to silent.
  18633. * - False if the value of `volume` should be used.
  18634. *
  18635. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
  18636. */
  18637. 'muted',
  18638. /**
  18639. * Get the value of `defaultMuted` from the media element. `defaultMuted` indicates
  18640. * whether the media should start muted or not. Only changes the default state of the
  18641. * media. `muted` and `defaultMuted` can have different values. {@link Html5#muted} indicates the
  18642. * current state.
  18643. *
  18644. * @method Html5#defaultMuted
  18645. * @return {boolean}
  18646. * - The value of `defaultMuted` from the media element.
  18647. * - True indicates that the media should start muted.
  18648. * - False indicates that the media should not start muted
  18649. *
  18650. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
  18651. */
  18652. 'defaultMuted',
  18653. /**
  18654. * Get the value of `autoplay` from the media element. `autoplay` indicates
  18655. * that the media should start to play as soon as the page is ready.
  18656. *
  18657. * @method Html5#autoplay
  18658. * @return {boolean}
  18659. * - The value of `autoplay` from the media element.
  18660. * - True indicates that the media should start as soon as the page loads.
  18661. * - False indicates that the media should not start as soon as the page loads.
  18662. *
  18663. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
  18664. */
  18665. 'autoplay',
  18666. /**
  18667. * Get the value of `controls` from the media element. `controls` indicates
  18668. * whether the native media controls should be shown or hidden.
  18669. *
  18670. * @method Html5#controls
  18671. * @return {boolean}
  18672. * - The value of `controls` from the media element.
  18673. * - True indicates that native controls should be showing.
  18674. * - False indicates that native controls should be hidden.
  18675. *
  18676. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-controls}
  18677. */
  18678. 'controls',
  18679. /**
  18680. * Get the value of `loop` from the media element. `loop` indicates
  18681. * that the media should return to the start of the media and continue playing once
  18682. * it reaches the end.
  18683. *
  18684. * @method Html5#loop
  18685. * @return {boolean}
  18686. * - The value of `loop` from the media element.
  18687. * - True indicates that playback should seek back to start once
  18688. * the end of a media is reached.
  18689. * - False indicates that playback should not loop back to the start when the
  18690. * end of the media is reached.
  18691. *
  18692. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
  18693. */
  18694. 'loop',
  18695. /**
  18696. * Get the value of `playsinline` from the media element. `playsinline` indicates
  18697. * to the browser that non-fullscreen playback is preferred when fullscreen
  18698. * playback is the native default, such as in iOS Safari.
  18699. *
  18700. * @method Html5#playsinline
  18701. * @return {boolean}
  18702. * - The value of `playsinline` from the media element.
  18703. * - True indicates that the media should play inline.
  18704. * - False indicates that the media should not play inline.
  18705. *
  18706. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  18707. */
  18708. 'playsinline'].forEach(function (prop) {
  18709. Html5.prototype[prop] = function () {
  18710. return this.el_[prop] || this.el_.hasAttribute(prop);
  18711. };
  18712. }); // Wrap native boolean attributes with setters that set both property and attribute
  18713. // The list is as followed:
  18714. // setMuted, setDefaultMuted, setAutoplay, setLoop, setPlaysinline
  18715. // setControls is special-cased above
  18716. [
  18717. /**
  18718. * Set the value of `muted` on the media element. `muted` indicates that the current
  18719. * audio level should be silent.
  18720. *
  18721. * @method Html5#setMuted
  18722. * @param {boolean} muted
  18723. * - True if the audio should be set to silent
  18724. * - False otherwise
  18725. *
  18726. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-muted}
  18727. */
  18728. 'muted',
  18729. /**
  18730. * Set the value of `defaultMuted` on the media element. `defaultMuted` indicates that the current
  18731. * audio level should be silent, but will only effect the muted level on initial playback..
  18732. *
  18733. * @method Html5.prototype.setDefaultMuted
  18734. * @param {boolean} defaultMuted
  18735. * - True if the audio should be set to silent
  18736. * - False otherwise
  18737. *
  18738. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultmuted}
  18739. */
  18740. 'defaultMuted',
  18741. /**
  18742. * Set the value of `autoplay` on the media element. `autoplay` indicates
  18743. * that the media should start to play as soon as the page is ready.
  18744. *
  18745. * @method Html5#setAutoplay
  18746. * @param {boolean} autoplay
  18747. * - True indicates that the media should start as soon as the page loads.
  18748. * - False indicates that the media should not start as soon as the page loads.
  18749. *
  18750. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-autoplay}
  18751. */
  18752. 'autoplay',
  18753. /**
  18754. * Set the value of `loop` on the media element. `loop` indicates
  18755. * that the media should return to the start of the media and continue playing once
  18756. * it reaches the end.
  18757. *
  18758. * @method Html5#setLoop
  18759. * @param {boolean} loop
  18760. * - True indicates that playback should seek back to start once
  18761. * the end of a media is reached.
  18762. * - False indicates that playback should not loop back to the start when the
  18763. * end of the media is reached.
  18764. *
  18765. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-loop}
  18766. */
  18767. 'loop',
  18768. /**
  18769. * Set the value of `playsinline` from the media element. `playsinline` indicates
  18770. * to the browser that non-fullscreen playback is preferred when fullscreen
  18771. * playback is the native default, such as in iOS Safari.
  18772. *
  18773. * @method Html5#setPlaysinline
  18774. * @param {boolean} playsinline
  18775. * - True indicates that the media should play inline.
  18776. * - False indicates that the media should not play inline.
  18777. *
  18778. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  18779. */
  18780. 'playsinline'].forEach(function (prop) {
  18781. Html5.prototype['set' + toTitleCase$1(prop)] = function (v) {
  18782. this.el_[prop] = v;
  18783. if (v) {
  18784. this.el_.setAttribute(prop, prop);
  18785. } else {
  18786. this.el_.removeAttribute(prop);
  18787. }
  18788. };
  18789. }); // Wrap native properties with a getter
  18790. // The list is as followed
  18791. // paused, currentTime, buffered, volume, poster, preload, error, seeking
  18792. // seekable, ended, playbackRate, defaultPlaybackRate, disablePictureInPicture
  18793. // played, networkState, readyState, videoWidth, videoHeight, crossOrigin
  18794. [
  18795. /**
  18796. * Get the value of `paused` from the media element. `paused` indicates whether the media element
  18797. * is currently paused or not.
  18798. *
  18799. * @method Html5#paused
  18800. * @return {boolean}
  18801. * The value of `paused` from the media element.
  18802. *
  18803. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-paused}
  18804. */
  18805. 'paused',
  18806. /**
  18807. * Get the value of `currentTime` from the media element. `currentTime` indicates
  18808. * the current second that the media is at in playback.
  18809. *
  18810. * @method Html5#currentTime
  18811. * @return {number}
  18812. * The value of `currentTime` from the media element.
  18813. *
  18814. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-currenttime}
  18815. */
  18816. 'currentTime',
  18817. /**
  18818. * Get the value of `buffered` from the media element. `buffered` is a `TimeRange`
  18819. * object that represents the parts of the media that are already downloaded and
  18820. * available for playback.
  18821. *
  18822. * @method Html5#buffered
  18823. * @return {TimeRange}
  18824. * The value of `buffered` from the media element.
  18825. *
  18826. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-buffered}
  18827. */
  18828. 'buffered',
  18829. /**
  18830. * Get the value of `volume` from the media element. `volume` indicates
  18831. * the current playback volume of audio for a media. `volume` will be a value from 0
  18832. * (silent) to 1 (loudest and default).
  18833. *
  18834. * @method Html5#volume
  18835. * @return {number}
  18836. * The value of `volume` from the media element. Value will be between 0-1.
  18837. *
  18838. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
  18839. */
  18840. 'volume',
  18841. /**
  18842. * Get the value of `poster` from the media element. `poster` indicates
  18843. * that the url of an image file that can/will be shown when no media data is available.
  18844. *
  18845. * @method Html5#poster
  18846. * @return {string}
  18847. * The value of `poster` from the media element. Value will be a url to an
  18848. * image.
  18849. *
  18850. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-video-poster}
  18851. */
  18852. 'poster',
  18853. /**
  18854. * Get the value of `preload` from the media element. `preload` indicates
  18855. * what should download before the media is interacted with. It can have the following
  18856. * values:
  18857. * - none: nothing should be downloaded
  18858. * - metadata: poster and the first few frames of the media may be downloaded to get
  18859. * media dimensions and other metadata
  18860. * - auto: allow the media and metadata for the media to be downloaded before
  18861. * interaction
  18862. *
  18863. * @method Html5#preload
  18864. * @return {string}
  18865. * The value of `preload` from the media element. Will be 'none', 'metadata',
  18866. * or 'auto'.
  18867. *
  18868. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
  18869. */
  18870. 'preload',
  18871. /**
  18872. * Get the value of the `error` from the media element. `error` indicates any
  18873. * MediaError that may have occurred during playback. If error returns null there is no
  18874. * current error.
  18875. *
  18876. * @method Html5#error
  18877. * @return {MediaError|null}
  18878. * The value of `error` from the media element. Will be `MediaError` if there
  18879. * is a current error and null otherwise.
  18880. *
  18881. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-error}
  18882. */
  18883. 'error',
  18884. /**
  18885. * Get the value of `seeking` from the media element. `seeking` indicates whether the
  18886. * media is currently seeking to a new position or not.
  18887. *
  18888. * @method Html5#seeking
  18889. * @return {boolean}
  18890. * - The value of `seeking` from the media element.
  18891. * - True indicates that the media is currently seeking to a new position.
  18892. * - False indicates that the media is not seeking to a new position at this time.
  18893. *
  18894. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seeking}
  18895. */
  18896. 'seeking',
  18897. /**
  18898. * Get the value of `seekable` from the media element. `seekable` returns a
  18899. * `TimeRange` object indicating ranges of time that can currently be `seeked` to.
  18900. *
  18901. * @method Html5#seekable
  18902. * @return {TimeRange}
  18903. * The value of `seekable` from the media element. A `TimeRange` object
  18904. * indicating the current ranges of time that can be seeked to.
  18905. *
  18906. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-seekable}
  18907. */
  18908. 'seekable',
  18909. /**
  18910. * Get the value of `ended` from the media element. `ended` indicates whether
  18911. * the media has reached the end or not.
  18912. *
  18913. * @method Html5#ended
  18914. * @return {boolean}
  18915. * - The value of `ended` from the media element.
  18916. * - True indicates that the media has ended.
  18917. * - False indicates that the media has not ended.
  18918. *
  18919. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-ended}
  18920. */
  18921. 'ended',
  18922. /**
  18923. * Get the value of `playbackRate` from the media element. `playbackRate` indicates
  18924. * the rate at which the media is currently playing back. Examples:
  18925. * - if playbackRate is set to 2, media will play twice as fast.
  18926. * - if playbackRate is set to 0.5, media will play half as fast.
  18927. *
  18928. * @method Html5#playbackRate
  18929. * @return {number}
  18930. * The value of `playbackRate` from the media element. A number indicating
  18931. * the current playback speed of the media, where 1 is normal speed.
  18932. *
  18933. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  18934. */
  18935. 'playbackRate',
  18936. /**
  18937. * Get the value of `defaultPlaybackRate` from the media element. `defaultPlaybackRate` indicates
  18938. * the rate at which the media is currently playing back. This value will not indicate the current
  18939. * `playbackRate` after playback has started, use {@link Html5#playbackRate} for that.
  18940. *
  18941. * Examples:
  18942. * - if defaultPlaybackRate is set to 2, media will play twice as fast.
  18943. * - if defaultPlaybackRate is set to 0.5, media will play half as fast.
  18944. *
  18945. * @method Html5.prototype.defaultPlaybackRate
  18946. * @return {number}
  18947. * The value of `defaultPlaybackRate` from the media element. A number indicating
  18948. * the current playback speed of the media, where 1 is normal speed.
  18949. *
  18950. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  18951. */
  18952. 'defaultPlaybackRate',
  18953. /**
  18954. * Get the value of 'disablePictureInPicture' from the video element.
  18955. *
  18956. * @method Html5#disablePictureInPicture
  18957. * @return {boolean} value
  18958. * - The value of `disablePictureInPicture` from the video element.
  18959. * - True indicates that the video can't be played in Picture-In-Picture mode
  18960. * - False indicates that the video can be played in Picture-In-Picture mode
  18961. *
  18962. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
  18963. */
  18964. 'disablePictureInPicture',
  18965. /**
  18966. * Get the value of `played` from the media element. `played` returns a `TimeRange`
  18967. * object representing points in the media timeline that have been played.
  18968. *
  18969. * @method Html5#played
  18970. * @return {TimeRange}
  18971. * The value of `played` from the media element. A `TimeRange` object indicating
  18972. * the ranges of time that have been played.
  18973. *
  18974. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-played}
  18975. */
  18976. 'played',
  18977. /**
  18978. * Get the value of `networkState` from the media element. `networkState` indicates
  18979. * the current network state. It returns an enumeration from the following list:
  18980. * - 0: NETWORK_EMPTY
  18981. * - 1: NETWORK_IDLE
  18982. * - 2: NETWORK_LOADING
  18983. * - 3: NETWORK_NO_SOURCE
  18984. *
  18985. * @method Html5#networkState
  18986. * @return {number}
  18987. * The value of `networkState` from the media element. This will be a number
  18988. * from the list in the description.
  18989. *
  18990. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-networkstate}
  18991. */
  18992. 'networkState',
  18993. /**
  18994. * Get the value of `readyState` from the media element. `readyState` indicates
  18995. * the current state of the media element. It returns an enumeration from the
  18996. * following list:
  18997. * - 0: HAVE_NOTHING
  18998. * - 1: HAVE_METADATA
  18999. * - 2: HAVE_CURRENT_DATA
  19000. * - 3: HAVE_FUTURE_DATA
  19001. * - 4: HAVE_ENOUGH_DATA
  19002. *
  19003. * @method Html5#readyState
  19004. * @return {number}
  19005. * The value of `readyState` from the media element. This will be a number
  19006. * from the list in the description.
  19007. *
  19008. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#ready-states}
  19009. */
  19010. 'readyState',
  19011. /**
  19012. * Get the value of `videoWidth` from the video element. `videoWidth` indicates
  19013. * the current width of the video in css pixels.
  19014. *
  19015. * @method Html5#videoWidth
  19016. * @return {number}
  19017. * The value of `videoWidth` from the video element. This will be a number
  19018. * in css pixels.
  19019. *
  19020. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
  19021. */
  19022. 'videoWidth',
  19023. /**
  19024. * Get the value of `videoHeight` from the video element. `videoHeight` indicates
  19025. * the current height of the video in css pixels.
  19026. *
  19027. * @method Html5#videoHeight
  19028. * @return {number}
  19029. * The value of `videoHeight` from the video element. This will be a number
  19030. * in css pixels.
  19031. *
  19032. * @see [Spec] {@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-video-videowidth}
  19033. */
  19034. 'videoHeight',
  19035. /**
  19036. * Get the value of `crossOrigin` from the media element. `crossOrigin` indicates
  19037. * to the browser that should sent the cookies along with the requests for the
  19038. * different assets/playlists
  19039. *
  19040. * @method Html5#crossOrigin
  19041. * @return {string}
  19042. * - anonymous indicates that the media should not sent cookies.
  19043. * - use-credentials indicates that the media should sent cookies along the requests.
  19044. *
  19045. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
  19046. */
  19047. 'crossOrigin'].forEach(function (prop) {
  19048. Html5.prototype[prop] = function () {
  19049. return this.el_[prop];
  19050. };
  19051. }); // Wrap native properties with a setter in this format:
  19052. // set + toTitleCase(name)
  19053. // The list is as follows:
  19054. // setVolume, setSrc, setPoster, setPreload, setPlaybackRate, setDefaultPlaybackRate,
  19055. // setDisablePictureInPicture, setCrossOrigin
  19056. [
  19057. /**
  19058. * Set the value of `volume` on the media element. `volume` indicates the current
  19059. * audio level as a percentage in decimal form. This means that 1 is 100%, 0.5 is 50%, and
  19060. * so on.
  19061. *
  19062. * @method Html5#setVolume
  19063. * @param {number} percentAsDecimal
  19064. * The volume percent as a decimal. Valid range is from 0-1.
  19065. *
  19066. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-a-volume}
  19067. */
  19068. 'volume',
  19069. /**
  19070. * Set the value of `src` on the media element. `src` indicates the current
  19071. * {@link Tech~SourceObject} for the media.
  19072. *
  19073. * @method Html5#setSrc
  19074. * @param {Tech~SourceObject} src
  19075. * The source object to set as the current source.
  19076. *
  19077. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-src}
  19078. */
  19079. 'src',
  19080. /**
  19081. * Set the value of `poster` on the media element. `poster` is the url to
  19082. * an image file that can/will be shown when no media data is available.
  19083. *
  19084. * @method Html5#setPoster
  19085. * @param {string} poster
  19086. * The url to an image that should be used as the `poster` for the media
  19087. * element.
  19088. *
  19089. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-poster}
  19090. */
  19091. 'poster',
  19092. /**
  19093. * Set the value of `preload` on the media element. `preload` indicates
  19094. * what should download before the media is interacted with. It can have the following
  19095. * values:
  19096. * - none: nothing should be downloaded
  19097. * - metadata: poster and the first few frames of the media may be downloaded to get
  19098. * media dimensions and other metadata
  19099. * - auto: allow the media and metadata for the media to be downloaded before
  19100. * interaction
  19101. *
  19102. * @method Html5#setPreload
  19103. * @param {string} preload
  19104. * The value of `preload` to set on the media element. Must be 'none', 'metadata',
  19105. * or 'auto'.
  19106. *
  19107. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#attr-media-preload}
  19108. */
  19109. 'preload',
  19110. /**
  19111. * Set the value of `playbackRate` on the media element. `playbackRate` indicates
  19112. * the rate at which the media should play back. Examples:
  19113. * - if playbackRate is set to 2, media will play twice as fast.
  19114. * - if playbackRate is set to 0.5, media will play half as fast.
  19115. *
  19116. * @method Html5#setPlaybackRate
  19117. * @return {number}
  19118. * The value of `playbackRate` from the media element. A number indicating
  19119. * the current playback speed of the media, where 1 is normal speed.
  19120. *
  19121. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-playbackrate}
  19122. */
  19123. 'playbackRate',
  19124. /**
  19125. * Set the value of `defaultPlaybackRate` on the media element. `defaultPlaybackRate` indicates
  19126. * the rate at which the media should play back upon initial startup. Changing this value
  19127. * after a video has started will do nothing. Instead you should used {@link Html5#setPlaybackRate}.
  19128. *
  19129. * Example Values:
  19130. * - if playbackRate is set to 2, media will play twice as fast.
  19131. * - if playbackRate is set to 0.5, media will play half as fast.
  19132. *
  19133. * @method Html5.prototype.setDefaultPlaybackRate
  19134. * @return {number}
  19135. * The value of `defaultPlaybackRate` from the media element. A number indicating
  19136. * the current playback speed of the media, where 1 is normal speed.
  19137. *
  19138. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-defaultplaybackrate}
  19139. */
  19140. 'defaultPlaybackRate',
  19141. /**
  19142. * Prevents the browser from suggesting a Picture-in-Picture context menu
  19143. * or to request Picture-in-Picture automatically in some cases.
  19144. *
  19145. * @method Html5#setDisablePictureInPicture
  19146. * @param {boolean} value
  19147. * The true value will disable Picture-in-Picture mode.
  19148. *
  19149. * @see [Spec]{@link https://w3c.github.io/picture-in-picture/#disable-pip}
  19150. */
  19151. 'disablePictureInPicture',
  19152. /**
  19153. * Set the value of `crossOrigin` from the media element. `crossOrigin` indicates
  19154. * to the browser that should sent the cookies along with the requests for the
  19155. * different assets/playlists
  19156. *
  19157. * @method Html5#setCrossOrigin
  19158. * @param {string} crossOrigin
  19159. * - anonymous indicates that the media should not sent cookies.
  19160. * - use-credentials indicates that the media should sent cookies along the requests.
  19161. *
  19162. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-media-crossorigin}
  19163. */
  19164. 'crossOrigin'].forEach(function (prop) {
  19165. Html5.prototype['set' + toTitleCase$1(prop)] = function (v) {
  19166. this.el_[prop] = v;
  19167. };
  19168. }); // wrap native functions with a function
  19169. // The list is as follows:
  19170. // pause, load, play
  19171. [
  19172. /**
  19173. * A wrapper around the media elements `pause` function. This will call the `HTML5`
  19174. * media elements `pause` function.
  19175. *
  19176. * @method Html5#pause
  19177. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-pause}
  19178. */
  19179. 'pause',
  19180. /**
  19181. * A wrapper around the media elements `load` function. This will call the `HTML5`s
  19182. * media element `load` function.
  19183. *
  19184. * @method Html5#load
  19185. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-load}
  19186. */
  19187. 'load',
  19188. /**
  19189. * A wrapper around the media elements `play` function. This will call the `HTML5`s
  19190. * media element `play` function.
  19191. *
  19192. * @method Html5#play
  19193. * @see [Spec]{@link https://www.w3.org/TR/html5/embedded-content-0.html#dom-media-play}
  19194. */
  19195. 'play'].forEach(function (prop) {
  19196. Html5.prototype[prop] = function () {
  19197. return this.el_[prop]();
  19198. };
  19199. });
  19200. Tech.withSourceHandlers(Html5);
  19201. /**
  19202. * Native source handler for Html5, simply passes the source to the media element.
  19203. *
  19204. * @property {Tech~SourceObject} source
  19205. * The source object
  19206. *
  19207. * @property {Html5} tech
  19208. * The instance of the HTML5 tech.
  19209. */
  19210. Html5.nativeSourceHandler = {};
  19211. /**
  19212. * Check if the media element can play the given mime type.
  19213. *
  19214. * @param {string} type
  19215. * The mimetype to check
  19216. *
  19217. * @return {string}
  19218. * 'probably', 'maybe', or '' (empty string)
  19219. */
  19220. Html5.nativeSourceHandler.canPlayType = function (type) {
  19221. // IE without MediaPlayer throws an error (#519)
  19222. try {
  19223. return Html5.TEST_VID.canPlayType(type);
  19224. } catch (e) {
  19225. return '';
  19226. }
  19227. };
  19228. /**
  19229. * Check if the media element can handle a source natively.
  19230. *
  19231. * @param {Tech~SourceObject} source
  19232. * The source object
  19233. *
  19234. * @param {Object} [options]
  19235. * Options to be passed to the tech.
  19236. *
  19237. * @return {string}
  19238. * 'probably', 'maybe', or '' (empty string).
  19239. */
  19240. Html5.nativeSourceHandler.canHandleSource = function (source, options) {
  19241. // If a type was provided we should rely on that
  19242. if (source.type) {
  19243. return Html5.nativeSourceHandler.canPlayType(source.type); // If no type, fall back to checking 'video/[EXTENSION]'
  19244. } else if (source.src) {
  19245. var ext = getFileExtension(source.src);
  19246. return Html5.nativeSourceHandler.canPlayType("video/" + ext);
  19247. }
  19248. return '';
  19249. };
  19250. /**
  19251. * Pass the source to the native media element.
  19252. *
  19253. * @param {Tech~SourceObject} source
  19254. * The source object
  19255. *
  19256. * @param {Html5} tech
  19257. * The instance of the Html5 tech
  19258. *
  19259. * @param {Object} [options]
  19260. * The options to pass to the source
  19261. */
  19262. Html5.nativeSourceHandler.handleSource = function (source, tech, options) {
  19263. tech.setSrc(source.src);
  19264. };
  19265. /**
  19266. * A noop for the native dispose function, as cleanup is not needed.
  19267. */
  19268. Html5.nativeSourceHandler.dispose = function () {}; // Register the native source handler
  19269. Html5.registerSourceHandler(Html5.nativeSourceHandler);
  19270. Tech.registerTech('Html5', Html5);
  19271. // on the player when they happen
  19272. var TECH_EVENTS_RETRIGGER = [
  19273. /**
  19274. * Fired while the user agent is downloading media data.
  19275. *
  19276. * @event Player#progress
  19277. * @type {EventTarget~Event}
  19278. */
  19279. /**
  19280. * Retrigger the `progress` event that was triggered by the {@link Tech}.
  19281. *
  19282. * @private
  19283. * @method Player#handleTechProgress_
  19284. * @fires Player#progress
  19285. * @listens Tech#progress
  19286. */
  19287. 'progress',
  19288. /**
  19289. * Fires when the loading of an audio/video is aborted.
  19290. *
  19291. * @event Player#abort
  19292. * @type {EventTarget~Event}
  19293. */
  19294. /**
  19295. * Retrigger the `abort` event that was triggered by the {@link Tech}.
  19296. *
  19297. * @private
  19298. * @method Player#handleTechAbort_
  19299. * @fires Player#abort
  19300. * @listens Tech#abort
  19301. */
  19302. 'abort',
  19303. /**
  19304. * Fires when the browser is intentionally not getting media data.
  19305. *
  19306. * @event Player#suspend
  19307. * @type {EventTarget~Event}
  19308. */
  19309. /**
  19310. * Retrigger the `suspend` event that was triggered by the {@link Tech}.
  19311. *
  19312. * @private
  19313. * @method Player#handleTechSuspend_
  19314. * @fires Player#suspend
  19315. * @listens Tech#suspend
  19316. */
  19317. 'suspend',
  19318. /**
  19319. * Fires when the current playlist is empty.
  19320. *
  19321. * @event Player#emptied
  19322. * @type {EventTarget~Event}
  19323. */
  19324. /**
  19325. * Retrigger the `emptied` event that was triggered by the {@link Tech}.
  19326. *
  19327. * @private
  19328. * @method Player#handleTechEmptied_
  19329. * @fires Player#emptied
  19330. * @listens Tech#emptied
  19331. */
  19332. 'emptied',
  19333. /**
  19334. * Fires when the browser is trying to get media data, but data is not available.
  19335. *
  19336. * @event Player#stalled
  19337. * @type {EventTarget~Event}
  19338. */
  19339. /**
  19340. * Retrigger the `stalled` event that was triggered by the {@link Tech}.
  19341. *
  19342. * @private
  19343. * @method Player#handleTechStalled_
  19344. * @fires Player#stalled
  19345. * @listens Tech#stalled
  19346. */
  19347. 'stalled',
  19348. /**
  19349. * Fires when the browser has loaded meta data for the audio/video.
  19350. *
  19351. * @event Player#loadedmetadata
  19352. * @type {EventTarget~Event}
  19353. */
  19354. /**
  19355. * Retrigger the `loadedmetadata` event that was triggered by the {@link Tech}.
  19356. *
  19357. * @private
  19358. * @method Player#handleTechLoadedmetadata_
  19359. * @fires Player#loadedmetadata
  19360. * @listens Tech#loadedmetadata
  19361. */
  19362. 'loadedmetadata',
  19363. /**
  19364. * Fires when the browser has loaded the current frame of the audio/video.
  19365. *
  19366. * @event Player#loadeddata
  19367. * @type {event}
  19368. */
  19369. /**
  19370. * Retrigger the `loadeddata` event that was triggered by the {@link Tech}.
  19371. *
  19372. * @private
  19373. * @method Player#handleTechLoaddeddata_
  19374. * @fires Player#loadeddata
  19375. * @listens Tech#loadeddata
  19376. */
  19377. 'loadeddata',
  19378. /**
  19379. * Fires when the current playback position has changed.
  19380. *
  19381. * @event Player#timeupdate
  19382. * @type {event}
  19383. */
  19384. /**
  19385. * Retrigger the `timeupdate` event that was triggered by the {@link Tech}.
  19386. *
  19387. * @private
  19388. * @method Player#handleTechTimeUpdate_
  19389. * @fires Player#timeupdate
  19390. * @listens Tech#timeupdate
  19391. */
  19392. 'timeupdate',
  19393. /**
  19394. * Fires when the video's intrinsic dimensions change
  19395. *
  19396. * @event Player#resize
  19397. * @type {event}
  19398. */
  19399. /**
  19400. * Retrigger the `resize` event that was triggered by the {@link Tech}.
  19401. *
  19402. * @private
  19403. * @method Player#handleTechResize_
  19404. * @fires Player#resize
  19405. * @listens Tech#resize
  19406. */
  19407. 'resize',
  19408. /**
  19409. * Fires when the volume has been changed
  19410. *
  19411. * @event Player#volumechange
  19412. * @type {event}
  19413. */
  19414. /**
  19415. * Retrigger the `volumechange` event that was triggered by the {@link Tech}.
  19416. *
  19417. * @private
  19418. * @method Player#handleTechVolumechange_
  19419. * @fires Player#volumechange
  19420. * @listens Tech#volumechange
  19421. */
  19422. 'volumechange',
  19423. /**
  19424. * Fires when the text track has been changed
  19425. *
  19426. * @event Player#texttrackchange
  19427. * @type {event}
  19428. */
  19429. /**
  19430. * Retrigger the `texttrackchange` event that was triggered by the {@link Tech}.
  19431. *
  19432. * @private
  19433. * @method Player#handleTechTexttrackchange_
  19434. * @fires Player#texttrackchange
  19435. * @listens Tech#texttrackchange
  19436. */
  19437. 'texttrackchange']; // events to queue when playback rate is zero
  19438. // this is a hash for the sole purpose of mapping non-camel-cased event names
  19439. // to camel-cased function names
  19440. var TECH_EVENTS_QUEUE = {
  19441. canplay: 'CanPlay',
  19442. canplaythrough: 'CanPlayThrough',
  19443. playing: 'Playing',
  19444. seeked: 'Seeked'
  19445. };
  19446. var BREAKPOINT_ORDER = ['tiny', 'xsmall', 'small', 'medium', 'large', 'xlarge', 'huge'];
  19447. var BREAKPOINT_CLASSES = {}; // grep: vjs-layout-tiny
  19448. // grep: vjs-layout-x-small
  19449. // grep: vjs-layout-small
  19450. // grep: vjs-layout-medium
  19451. // grep: vjs-layout-large
  19452. // grep: vjs-layout-x-large
  19453. // grep: vjs-layout-huge
  19454. BREAKPOINT_ORDER.forEach(function (k) {
  19455. var v = k.charAt(0) === 'x' ? "x-" + k.substring(1) : k;
  19456. BREAKPOINT_CLASSES[k] = "vjs-layout-" + v;
  19457. });
  19458. var DEFAULT_BREAKPOINTS = {
  19459. tiny: 210,
  19460. xsmall: 320,
  19461. small: 425,
  19462. medium: 768,
  19463. large: 1440,
  19464. xlarge: 2560,
  19465. huge: Infinity
  19466. };
  19467. /**
  19468. * An instance of the `Player` class is created when any of the Video.js setup methods
  19469. * are used to initialize a video.
  19470. *
  19471. * After an instance has been created it can be accessed globally in two ways:
  19472. * 1. By calling `videojs('example_video_1');`
  19473. * 2. By using it directly via `videojs.players.example_video_1;`
  19474. *
  19475. * @extends Component
  19476. */
  19477. var Player = /*#__PURE__*/function (_Component) {
  19478. inheritsLoose(Player, _Component);
  19479. /**
  19480. * Create an instance of this class.
  19481. *
  19482. * @param {Element} tag
  19483. * The original video DOM element used for configuring options.
  19484. *
  19485. * @param {Object} [options]
  19486. * Object of option names and values.
  19487. *
  19488. * @param {Component~ReadyCallback} [ready]
  19489. * Ready callback function.
  19490. */
  19491. function Player(tag, options, ready) {
  19492. var _this;
  19493. // Make sure tag ID exists
  19494. tag.id = tag.id || options.id || "vjs_video_" + newGUID(); // Set Options
  19495. // The options argument overrides options set in the video tag
  19496. // which overrides globally set options.
  19497. // This latter part coincides with the load order
  19498. // (tag must exist before Player)
  19499. options = assign$1(Player.getTagSettings(tag), options); // Delay the initialization of children because we need to set up
  19500. // player properties first, and can't use `this` before `super()`
  19501. options.initChildren = false; // Same with creating the element
  19502. options.createEl = false; // don't auto mixin the evented mixin
  19503. options.evented = false; // we don't want the player to report touch activity on itself
  19504. // see enableTouchActivity in Component
  19505. options.reportTouchActivity = false; // If language is not set, get the closest lang attribute
  19506. if (!options.language) {
  19507. if (typeof tag.closest === 'function') {
  19508. var closest = tag.closest('[lang]');
  19509. if (closest && closest.getAttribute) {
  19510. options.language = closest.getAttribute('lang');
  19511. }
  19512. } else {
  19513. var element = tag;
  19514. while (element && element.nodeType === 1) {
  19515. if (getAttributes(element).hasOwnProperty('lang')) {
  19516. options.language = element.getAttribute('lang');
  19517. break;
  19518. }
  19519. element = element.parentNode;
  19520. }
  19521. }
  19522. } // Run base component initializing with new options
  19523. _this = _Component.call(this, null, options, ready) || this; // Create bound methods for document listeners.
  19524. _this.boundDocumentFullscreenChange_ = function (e) {
  19525. return _this.documentFullscreenChange_(e);
  19526. };
  19527. _this.boundFullWindowOnEscKey_ = function (e) {
  19528. return _this.fullWindowOnEscKey(e);
  19529. };
  19530. _this.boundUpdateStyleEl_ = function (e) {
  19531. return _this.updateStyleEl_(e);
  19532. };
  19533. _this.boundApplyInitTime_ = function (e) {
  19534. return _this.applyInitTime_(e);
  19535. };
  19536. _this.boundUpdateCurrentBreakpoint_ = function (e) {
  19537. return _this.updateCurrentBreakpoint_(e);
  19538. };
  19539. _this.boundHandleTechClick_ = function (e) {
  19540. return _this.handleTechClick_(e);
  19541. };
  19542. _this.boundHandleTechDoubleClick_ = function (e) {
  19543. return _this.handleTechDoubleClick_(e);
  19544. };
  19545. _this.boundHandleTechTouchStart_ = function (e) {
  19546. return _this.handleTechTouchStart_(e);
  19547. };
  19548. _this.boundHandleTechTouchMove_ = function (e) {
  19549. return _this.handleTechTouchMove_(e);
  19550. };
  19551. _this.boundHandleTechTouchEnd_ = function (e) {
  19552. return _this.handleTechTouchEnd_(e);
  19553. };
  19554. _this.boundHandleTechTap_ = function (e) {
  19555. return _this.handleTechTap_(e);
  19556. }; // default isFullscreen_ to false
  19557. _this.isFullscreen_ = false; // create logger
  19558. _this.log = createLogger(_this.id_); // Hold our own reference to fullscreen api so it can be mocked in tests
  19559. _this.fsApi_ = FullscreenApi; // Tracks when a tech changes the poster
  19560. _this.isPosterFromTech_ = false; // Holds callback info that gets queued when playback rate is zero
  19561. // and a seek is happening
  19562. _this.queuedCallbacks_ = []; // Turn off API access because we're loading a new tech that might load asynchronously
  19563. _this.isReady_ = false; // Init state hasStarted_
  19564. _this.hasStarted_ = false; // Init state userActive_
  19565. _this.userActive_ = false; // Init debugEnabled_
  19566. _this.debugEnabled_ = false; // Init state audioOnlyMode_
  19567. _this.audioOnlyMode_ = false; // Init state audioPosterMode_
  19568. _this.audioPosterMode_ = false; // Init state audioOnlyCache_
  19569. _this.audioOnlyCache_ = {
  19570. playerHeight: null,
  19571. hiddenChildren: []
  19572. }; // if the global option object was accidentally blown away by
  19573. // someone, bail early with an informative error
  19574. if (!_this.options_ || !_this.options_.techOrder || !_this.options_.techOrder.length) {
  19575. throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?');
  19576. } // Store the original tag used to set options
  19577. _this.tag = tag; // Store the tag attributes used to restore html5 element
  19578. _this.tagAttributes = tag && getAttributes(tag); // Update current language
  19579. _this.language(_this.options_.language); // Update Supported Languages
  19580. if (options.languages) {
  19581. // Normalise player option languages to lowercase
  19582. var languagesToLower = {};
  19583. Object.getOwnPropertyNames(options.languages).forEach(function (name) {
  19584. languagesToLower[name.toLowerCase()] = options.languages[name];
  19585. });
  19586. _this.languages_ = languagesToLower;
  19587. } else {
  19588. _this.languages_ = Player.prototype.options_.languages;
  19589. }
  19590. _this.resetCache_(); // Set poster
  19591. _this.poster_ = options.poster || ''; // Set controls
  19592. _this.controls_ = !!options.controls; // Original tag settings stored in options
  19593. // now remove immediately so native controls don't flash.
  19594. // May be turned back on by HTML5 tech if nativeControlsForTouch is true
  19595. tag.controls = false;
  19596. tag.removeAttribute('controls');
  19597. _this.changingSrc_ = false;
  19598. _this.playCallbacks_ = [];
  19599. _this.playTerminatedQueue_ = []; // the attribute overrides the option
  19600. if (tag.hasAttribute('autoplay')) {
  19601. _this.autoplay(true);
  19602. } else {
  19603. // otherwise use the setter to validate and
  19604. // set the correct value.
  19605. _this.autoplay(_this.options_.autoplay);
  19606. } // check plugins
  19607. if (options.plugins) {
  19608. Object.keys(options.plugins).forEach(function (name) {
  19609. if (typeof _this[name] !== 'function') {
  19610. throw new Error("plugin \"" + name + "\" does not exist");
  19611. }
  19612. });
  19613. }
  19614. /*
  19615. * Store the internal state of scrubbing
  19616. *
  19617. * @private
  19618. * @return {Boolean} True if the user is scrubbing
  19619. */
  19620. _this.scrubbing_ = false;
  19621. _this.el_ = _this.createEl(); // Make this an evented object and use `el_` as its event bus.
  19622. evented(assertThisInitialized(_this), {
  19623. eventBusKey: 'el_'
  19624. }); // listen to document and player fullscreenchange handlers so we receive those events
  19625. // before a user can receive them so we can update isFullscreen appropriately.
  19626. // make sure that we listen to fullscreenchange events before everything else to make sure that
  19627. // our isFullscreen method is updated properly for internal components as well as external.
  19628. if (_this.fsApi_.requestFullscreen) {
  19629. on(document, _this.fsApi_.fullscreenchange, _this.boundDocumentFullscreenChange_);
  19630. _this.on(_this.fsApi_.fullscreenchange, _this.boundDocumentFullscreenChange_);
  19631. }
  19632. if (_this.fluid_) {
  19633. _this.on(['playerreset', 'resize'], _this.boundUpdateStyleEl_);
  19634. } // We also want to pass the original player options to each component and plugin
  19635. // as well so they don't need to reach back into the player for options later.
  19636. // We also need to do another copy of this.options_ so we don't end up with
  19637. // an infinite loop.
  19638. var playerOptionsCopy = mergeOptions$3(_this.options_); // Load plugins
  19639. if (options.plugins) {
  19640. Object.keys(options.plugins).forEach(function (name) {
  19641. _this[name](options.plugins[name]);
  19642. });
  19643. } // Enable debug mode to fire debugon event for all plugins.
  19644. if (options.debug) {
  19645. _this.debug(true);
  19646. }
  19647. _this.options_.playerOptions = playerOptionsCopy;
  19648. _this.middleware_ = [];
  19649. _this.playbackRates(options.playbackRates);
  19650. _this.initChildren(); // Set isAudio based on whether or not an audio tag was used
  19651. _this.isAudio(tag.nodeName.toLowerCase() === 'audio'); // Update controls className. Can't do this when the controls are initially
  19652. // set because the element doesn't exist yet.
  19653. if (_this.controls()) {
  19654. _this.addClass('vjs-controls-enabled');
  19655. } else {
  19656. _this.addClass('vjs-controls-disabled');
  19657. } // Set ARIA label and region role depending on player type
  19658. _this.el_.setAttribute('role', 'region');
  19659. if (_this.isAudio()) {
  19660. _this.el_.setAttribute('aria-label', _this.localize('Audio Player'));
  19661. } else {
  19662. _this.el_.setAttribute('aria-label', _this.localize('Video Player'));
  19663. }
  19664. if (_this.isAudio()) {
  19665. _this.addClass('vjs-audio');
  19666. }
  19667. if (_this.flexNotSupported_()) {
  19668. _this.addClass('vjs-no-flex');
  19669. } // TODO: Make this smarter. Toggle user state between touching/mousing
  19670. // using events, since devices can have both touch and mouse events.
  19671. // TODO: Make this check be performed again when the window switches between monitors
  19672. // (See https://github.com/videojs/video.js/issues/5683)
  19673. if (TOUCH_ENABLED) {
  19674. _this.addClass('vjs-touch-enabled');
  19675. } // iOS Safari has broken hover handling
  19676. if (!IS_IOS) {
  19677. _this.addClass('vjs-workinghover');
  19678. } // Make player easily findable by ID
  19679. Player.players[_this.id_] = assertThisInitialized(_this); // Add a major version class to aid css in plugins
  19680. var majorVersion = version$5.split('.')[0];
  19681. _this.addClass("vjs-v" + majorVersion); // When the player is first initialized, trigger activity so components
  19682. // like the control bar show themselves if needed
  19683. _this.userActive(true);
  19684. _this.reportUserActivity();
  19685. _this.one('play', function (e) {
  19686. return _this.listenForUserActivity_(e);
  19687. });
  19688. _this.on('stageclick', function (e) {
  19689. return _this.handleStageClick_(e);
  19690. });
  19691. _this.on('keydown', function (e) {
  19692. return _this.handleKeyDown(e);
  19693. });
  19694. _this.on('languagechange', function (e) {
  19695. return _this.handleLanguagechange(e);
  19696. });
  19697. _this.breakpoints(_this.options_.breakpoints);
  19698. _this.responsive(_this.options_.responsive); // Calling both the audio mode methods after the player is fully
  19699. // setup to be able to listen to the events triggered by them
  19700. _this.on('ready', function () {
  19701. // Calling the audioPosterMode method first so that
  19702. // the audioOnlyMode can take precedence when both options are set to true
  19703. _this.audioPosterMode(_this.options_.audioPosterMode);
  19704. _this.audioOnlyMode(_this.options_.audioOnlyMode);
  19705. });
  19706. return _this;
  19707. }
  19708. /**
  19709. * Destroys the video player and does any necessary cleanup.
  19710. *
  19711. * This is especially helpful if you are dynamically adding and removing videos
  19712. * to/from the DOM.
  19713. *
  19714. * @fires Player#dispose
  19715. */
  19716. var _proto = Player.prototype;
  19717. _proto.dispose = function dispose() {
  19718. var _this2 = this;
  19719. /**
  19720. * Called when the player is being disposed of.
  19721. *
  19722. * @event Player#dispose
  19723. * @type {EventTarget~Event}
  19724. */
  19725. this.trigger('dispose'); // prevent dispose from being called twice
  19726. this.off('dispose'); // Make sure all player-specific document listeners are unbound. This is
  19727. off(document, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
  19728. off(document, 'keydown', this.boundFullWindowOnEscKey_);
  19729. if (this.styleEl_ && this.styleEl_.parentNode) {
  19730. this.styleEl_.parentNode.removeChild(this.styleEl_);
  19731. this.styleEl_ = null;
  19732. } // Kill reference to this player
  19733. Player.players[this.id_] = null;
  19734. if (this.tag && this.tag.player) {
  19735. this.tag.player = null;
  19736. }
  19737. if (this.el_ && this.el_.player) {
  19738. this.el_.player = null;
  19739. }
  19740. if (this.tech_) {
  19741. this.tech_.dispose();
  19742. this.isPosterFromTech_ = false;
  19743. this.poster_ = '';
  19744. }
  19745. if (this.playerElIngest_) {
  19746. this.playerElIngest_ = null;
  19747. }
  19748. if (this.tag) {
  19749. this.tag = null;
  19750. }
  19751. clearCacheForPlayer(this); // remove all event handlers for track lists
  19752. // all tracks and track listeners are removed on
  19753. // tech dispose
  19754. ALL.names.forEach(function (name) {
  19755. var props = ALL[name];
  19756. var list = _this2[props.getterName](); // if it is not a native list
  19757. // we have to manually remove event listeners
  19758. if (list && list.off) {
  19759. list.off();
  19760. }
  19761. }); // the actual .el_ is removed here, or replaced if
  19762. _Component.prototype.dispose.call(this, {
  19763. restoreEl: this.options_.restoreEl
  19764. });
  19765. }
  19766. /**
  19767. * Create the `Player`'s DOM element.
  19768. *
  19769. * @return {Element}
  19770. * The DOM element that gets created.
  19771. */
  19772. ;
  19773. _proto.createEl = function createEl() {
  19774. var tag = this.tag;
  19775. var el;
  19776. var playerElIngest = this.playerElIngest_ = tag.parentNode && tag.parentNode.hasAttribute && tag.parentNode.hasAttribute('data-vjs-player');
  19777. var divEmbed = this.tag.tagName.toLowerCase() === 'video-js';
  19778. if (playerElIngest) {
  19779. el = this.el_ = tag.parentNode;
  19780. } else if (!divEmbed) {
  19781. el = this.el_ = _Component.prototype.createEl.call(this, 'div');
  19782. } // Copy over all the attributes from the tag, including ID and class
  19783. // ID will now reference player box, not the video tag
  19784. var attrs = getAttributes(tag);
  19785. if (divEmbed) {
  19786. el = this.el_ = tag;
  19787. tag = this.tag = document.createElement('video');
  19788. while (el.children.length) {
  19789. tag.appendChild(el.firstChild);
  19790. }
  19791. if (!hasClass(el, 'video-js')) {
  19792. addClass(el, 'video-js');
  19793. }
  19794. el.appendChild(tag);
  19795. playerElIngest = this.playerElIngest_ = el; // move properties over from our custom `video-js` element
  19796. // to our new `video` element. This will move things like
  19797. // `src` or `controls` that were set via js before the player
  19798. // was initialized.
  19799. Object.keys(el).forEach(function (k) {
  19800. try {
  19801. tag[k] = el[k];
  19802. } catch (e) {// we got a a property like outerHTML which we can't actually copy, ignore it
  19803. }
  19804. });
  19805. } // set tabindex to -1 to remove the video element from the focus order
  19806. tag.setAttribute('tabindex', '-1');
  19807. attrs.tabindex = '-1'; // Workaround for #4583 (JAWS+IE doesn't announce BPB or play button), and
  19808. // for the same issue with Chrome (on Windows) with JAWS.
  19809. // See https://github.com/FreedomScientific/VFO-standards-support/issues/78
  19810. // Note that we can't detect if JAWS is being used, but this ARIA attribute
  19811. // doesn't change behavior of IE11 or Chrome if JAWS is not being used
  19812. if (IE_VERSION || IS_CHROME && IS_WINDOWS) {
  19813. tag.setAttribute('role', 'application');
  19814. attrs.role = 'application';
  19815. } // Remove width/height attrs from tag so CSS can make it 100% width/height
  19816. tag.removeAttribute('width');
  19817. tag.removeAttribute('height');
  19818. if ('width' in attrs) {
  19819. delete attrs.width;
  19820. }
  19821. if ('height' in attrs) {
  19822. delete attrs.height;
  19823. }
  19824. Object.getOwnPropertyNames(attrs).forEach(function (attr) {
  19825. // don't copy over the class attribute to the player element when we're in a div embed
  19826. // the class is already set up properly in the divEmbed case
  19827. // and we want to make sure that the `video-js` class doesn't get lost
  19828. if (!(divEmbed && attr === 'class')) {
  19829. el.setAttribute(attr, attrs[attr]);
  19830. }
  19831. if (divEmbed) {
  19832. tag.setAttribute(attr, attrs[attr]);
  19833. }
  19834. }); // Update tag id/class for use as HTML5 playback tech
  19835. // Might think we should do this after embedding in container so .vjs-tech class
  19836. // doesn't flash 100% width/height, but class only applies with .video-js parent
  19837. tag.playerId = tag.id;
  19838. tag.id += '_html5_api';
  19839. tag.className = 'vjs-tech'; // Make player findable on elements
  19840. tag.player = el.player = this; // Default state of video is paused
  19841. this.addClass('vjs-paused'); // Add a style element in the player that we'll use to set the width/height
  19842. // of the player in a way that's still overrideable by CSS, just like the
  19843. // video element
  19844. if (window.VIDEOJS_NO_DYNAMIC_STYLE !== true) {
  19845. this.styleEl_ = createStyleElement('vjs-styles-dimensions');
  19846. var defaultsStyleEl = $('.vjs-styles-defaults');
  19847. var head = $('head');
  19848. head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild);
  19849. }
  19850. this.fill_ = false;
  19851. this.fluid_ = false; // Pass in the width/height/aspectRatio options which will update the style el
  19852. this.width(this.options_.width);
  19853. this.height(this.options_.height);
  19854. this.fill(this.options_.fill);
  19855. this.fluid(this.options_.fluid);
  19856. this.aspectRatio(this.options_.aspectRatio); // support both crossOrigin and crossorigin to reduce confusion and issues around the name
  19857. this.crossOrigin(this.options_.crossOrigin || this.options_.crossorigin); // Hide any links within the video/audio tag,
  19858. // because IE doesn't hide them completely from screen readers.
  19859. var links = tag.getElementsByTagName('a');
  19860. for (var i = 0; i < links.length; i++) {
  19861. var linkEl = links.item(i);
  19862. addClass(linkEl, 'vjs-hidden');
  19863. linkEl.setAttribute('hidden', 'hidden');
  19864. } // insertElFirst seems to cause the networkState to flicker from 3 to 2, so
  19865. // keep track of the original for later so we can know if the source originally failed
  19866. tag.initNetworkState_ = tag.networkState; // Wrap video tag in div (el/box) container
  19867. if (tag.parentNode && !playerElIngest) {
  19868. tag.parentNode.insertBefore(el, tag);
  19869. } // insert the tag as the first child of the player element
  19870. // then manually add it to the children array so that this.addChild
  19871. // will work properly for other components
  19872. //
  19873. // Breaks iPhone, fixed in HTML5 setup.
  19874. prependTo(tag, el);
  19875. this.children_.unshift(tag); // Set lang attr on player to ensure CSS :lang() in consistent with player
  19876. // if it's been set to something different to the doc
  19877. this.el_.setAttribute('lang', this.language_);
  19878. this.el_.setAttribute('translate', 'no');
  19879. this.el_ = el;
  19880. return el;
  19881. }
  19882. /**
  19883. * Get or set the `Player`'s crossOrigin option. For the HTML5 player, this
  19884. * sets the `crossOrigin` property on the `<video>` tag to control the CORS
  19885. * behavior.
  19886. *
  19887. * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
  19888. *
  19889. * @param {string} [value]
  19890. * The value to set the `Player`'s crossOrigin to. If an argument is
  19891. * given, must be one of `anonymous` or `use-credentials`.
  19892. *
  19893. * @return {string|undefined}
  19894. * - The current crossOrigin value of the `Player` when getting.
  19895. * - undefined when setting
  19896. */
  19897. ;
  19898. _proto.crossOrigin = function crossOrigin(value) {
  19899. if (!value) {
  19900. return this.techGet_('crossOrigin');
  19901. }
  19902. if (value !== 'anonymous' && value !== 'use-credentials') {
  19903. log$1.warn("crossOrigin must be \"anonymous\" or \"use-credentials\", given \"" + value + "\"");
  19904. return;
  19905. }
  19906. this.techCall_('setCrossOrigin', value);
  19907. return;
  19908. }
  19909. /**
  19910. * A getter/setter for the `Player`'s width. Returns the player's configured value.
  19911. * To get the current width use `currentWidth()`.
  19912. *
  19913. * @param {number} [value]
  19914. * The value to set the `Player`'s width to.
  19915. *
  19916. * @return {number}
  19917. * The current width of the `Player` when getting.
  19918. */
  19919. ;
  19920. _proto.width = function width(value) {
  19921. return this.dimension('width', value);
  19922. }
  19923. /**
  19924. * A getter/setter for the `Player`'s height. Returns the player's configured value.
  19925. * To get the current height use `currentheight()`.
  19926. *
  19927. * @param {number} [value]
  19928. * The value to set the `Player`'s heigth to.
  19929. *
  19930. * @return {number}
  19931. * The current height of the `Player` when getting.
  19932. */
  19933. ;
  19934. _proto.height = function height(value) {
  19935. return this.dimension('height', value);
  19936. }
  19937. /**
  19938. * A getter/setter for the `Player`'s width & height.
  19939. *
  19940. * @param {string} dimension
  19941. * This string can be:
  19942. * - 'width'
  19943. * - 'height'
  19944. *
  19945. * @param {number} [value]
  19946. * Value for dimension specified in the first argument.
  19947. *
  19948. * @return {number}
  19949. * The dimension arguments value when getting (width/height).
  19950. */
  19951. ;
  19952. _proto.dimension = function dimension(_dimension, value) {
  19953. var privDimension = _dimension + '_';
  19954. if (value === undefined) {
  19955. return this[privDimension] || 0;
  19956. }
  19957. if (value === '' || value === 'auto') {
  19958. // If an empty string is given, reset the dimension to be automatic
  19959. this[privDimension] = undefined;
  19960. this.updateStyleEl_();
  19961. return;
  19962. }
  19963. var parsedVal = parseFloat(value);
  19964. if (isNaN(parsedVal)) {
  19965. log$1.error("Improper value \"" + value + "\" supplied for for " + _dimension);
  19966. return;
  19967. }
  19968. this[privDimension] = parsedVal;
  19969. this.updateStyleEl_();
  19970. }
  19971. /**
  19972. * A getter/setter/toggler for the vjs-fluid `className` on the `Player`.
  19973. *
  19974. * Turning this on will turn off fill mode.
  19975. *
  19976. * @param {boolean} [bool]
  19977. * - A value of true adds the class.
  19978. * - A value of false removes the class.
  19979. * - No value will be a getter.
  19980. *
  19981. * @return {boolean|undefined}
  19982. * - The value of fluid when getting.
  19983. * - `undefined` when setting.
  19984. */
  19985. ;
  19986. _proto.fluid = function fluid(bool) {
  19987. var _this3 = this;
  19988. if (bool === undefined) {
  19989. return !!this.fluid_;
  19990. }
  19991. this.fluid_ = !!bool;
  19992. if (isEvented(this)) {
  19993. this.off(['playerreset', 'resize'], this.boundUpdateStyleEl_);
  19994. }
  19995. if (bool) {
  19996. this.addClass('vjs-fluid');
  19997. this.fill(false);
  19998. addEventedCallback(this, function () {
  19999. _this3.on(['playerreset', 'resize'], _this3.boundUpdateStyleEl_);
  20000. });
  20001. } else {
  20002. this.removeClass('vjs-fluid');
  20003. }
  20004. this.updateStyleEl_();
  20005. }
  20006. /**
  20007. * A getter/setter/toggler for the vjs-fill `className` on the `Player`.
  20008. *
  20009. * Turning this on will turn off fluid mode.
  20010. *
  20011. * @param {boolean} [bool]
  20012. * - A value of true adds the class.
  20013. * - A value of false removes the class.
  20014. * - No value will be a getter.
  20015. *
  20016. * @return {boolean|undefined}
  20017. * - The value of fluid when getting.
  20018. * - `undefined` when setting.
  20019. */
  20020. ;
  20021. _proto.fill = function fill(bool) {
  20022. if (bool === undefined) {
  20023. return !!this.fill_;
  20024. }
  20025. this.fill_ = !!bool;
  20026. if (bool) {
  20027. this.addClass('vjs-fill');
  20028. this.fluid(false);
  20029. } else {
  20030. this.removeClass('vjs-fill');
  20031. }
  20032. }
  20033. /**
  20034. * Get/Set the aspect ratio
  20035. *
  20036. * @param {string} [ratio]
  20037. * Aspect ratio for player
  20038. *
  20039. * @return {string|undefined}
  20040. * returns the current aspect ratio when getting
  20041. */
  20042. /**
  20043. * A getter/setter for the `Player`'s aspect ratio.
  20044. *
  20045. * @param {string} [ratio]
  20046. * The value to set the `Player`'s aspect ratio to.
  20047. *
  20048. * @return {string|undefined}
  20049. * - The current aspect ratio of the `Player` when getting.
  20050. * - undefined when setting
  20051. */
  20052. ;
  20053. _proto.aspectRatio = function aspectRatio(ratio) {
  20054. if (ratio === undefined) {
  20055. return this.aspectRatio_;
  20056. } // Check for width:height format
  20057. if (!/^\d+\:\d+$/.test(ratio)) {
  20058. throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.');
  20059. }
  20060. this.aspectRatio_ = ratio; // We're assuming if you set an aspect ratio you want fluid mode,
  20061. // because in fixed mode you could calculate width and height yourself.
  20062. this.fluid(true);
  20063. this.updateStyleEl_();
  20064. }
  20065. /**
  20066. * Update styles of the `Player` element (height, width and aspect ratio).
  20067. *
  20068. * @private
  20069. * @listens Tech#loadedmetadata
  20070. */
  20071. ;
  20072. _proto.updateStyleEl_ = function updateStyleEl_() {
  20073. if (window.VIDEOJS_NO_DYNAMIC_STYLE === true) {
  20074. var _width = typeof this.width_ === 'number' ? this.width_ : this.options_.width;
  20075. var _height = typeof this.height_ === 'number' ? this.height_ : this.options_.height;
  20076. var techEl = this.tech_ && this.tech_.el();
  20077. if (techEl) {
  20078. if (_width >= 0) {
  20079. techEl.width = _width;
  20080. }
  20081. if (_height >= 0) {
  20082. techEl.height = _height;
  20083. }
  20084. }
  20085. return;
  20086. }
  20087. var width;
  20088. var height;
  20089. var aspectRatio;
  20090. var idClass; // The aspect ratio is either used directly or to calculate width and height.
  20091. if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') {
  20092. // Use any aspectRatio that's been specifically set
  20093. aspectRatio = this.aspectRatio_;
  20094. } else if (this.videoWidth() > 0) {
  20095. // Otherwise try to get the aspect ratio from the video metadata
  20096. aspectRatio = this.videoWidth() + ':' + this.videoHeight();
  20097. } else {
  20098. // Or use a default. The video element's is 2:1, but 16:9 is more common.
  20099. aspectRatio = '16:9';
  20100. } // Get the ratio as a decimal we can use to calculate dimensions
  20101. var ratioParts = aspectRatio.split(':');
  20102. var ratioMultiplier = ratioParts[1] / ratioParts[0];
  20103. if (this.width_ !== undefined) {
  20104. // Use any width that's been specifically set
  20105. width = this.width_;
  20106. } else if (this.height_ !== undefined) {
  20107. // Or calulate the width from the aspect ratio if a height has been set
  20108. width = this.height_ / ratioMultiplier;
  20109. } else {
  20110. // Or use the video's metadata, or use the video el's default of 300
  20111. width = this.videoWidth() || 300;
  20112. }
  20113. if (this.height_ !== undefined) {
  20114. // Use any height that's been specifically set
  20115. height = this.height_;
  20116. } else {
  20117. // Otherwise calculate the height from the ratio and the width
  20118. height = width * ratioMultiplier;
  20119. } // Ensure the CSS class is valid by starting with an alpha character
  20120. if (/^[^a-zA-Z]/.test(this.id())) {
  20121. idClass = 'dimensions-' + this.id();
  20122. } else {
  20123. idClass = this.id() + '-dimensions';
  20124. } // Ensure the right class is still on the player for the style element
  20125. this.addClass(idClass);
  20126. 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 ");
  20127. }
  20128. /**
  20129. * Load/Create an instance of playback {@link Tech} including element
  20130. * and API methods. Then append the `Tech` element in `Player` as a child.
  20131. *
  20132. * @param {string} techName
  20133. * name of the playback technology
  20134. *
  20135. * @param {string} source
  20136. * video source
  20137. *
  20138. * @private
  20139. */
  20140. ;
  20141. _proto.loadTech_ = function loadTech_(techName, source) {
  20142. var _this4 = this;
  20143. // Pause and remove current playback technology
  20144. if (this.tech_) {
  20145. this.unloadTech_();
  20146. }
  20147. var titleTechName = toTitleCase$1(techName);
  20148. var camelTechName = techName.charAt(0).toLowerCase() + techName.slice(1); // get rid of the HTML5 video tag as soon as we are using another tech
  20149. if (titleTechName !== 'Html5' && this.tag) {
  20150. Tech.getTech('Html5').disposeMediaElement(this.tag);
  20151. this.tag.player = null;
  20152. this.tag = null;
  20153. }
  20154. this.techName_ = titleTechName; // Turn off API access because we're loading a new tech that might load asynchronously
  20155. this.isReady_ = false;
  20156. var autoplay = this.autoplay(); // if autoplay is a string (or `true` with normalizeAutoplay: true) we pass false to the tech
  20157. // because the player is going to handle autoplay on `loadstart`
  20158. if (typeof this.autoplay() === 'string' || this.autoplay() === true && this.options_.normalizeAutoplay) {
  20159. autoplay = false;
  20160. } // Grab tech-specific options from player options and add source and parent element to use.
  20161. var techOptions = {
  20162. source: source,
  20163. autoplay: autoplay,
  20164. 'nativeControlsForTouch': this.options_.nativeControlsForTouch,
  20165. 'playerId': this.id(),
  20166. 'techId': this.id() + "_" + camelTechName + "_api",
  20167. 'playsinline': this.options_.playsinline,
  20168. 'preload': this.options_.preload,
  20169. 'loop': this.options_.loop,
  20170. 'disablePictureInPicture': this.options_.disablePictureInPicture,
  20171. 'muted': this.options_.muted,
  20172. 'poster': this.poster(),
  20173. 'language': this.language(),
  20174. 'playerElIngest': this.playerElIngest_ || false,
  20175. 'vtt.js': this.options_['vtt.js'],
  20176. 'canOverridePoster': !!this.options_.techCanOverridePoster,
  20177. 'enableSourceset': this.options_.enableSourceset,
  20178. 'Promise': this.options_.Promise
  20179. };
  20180. ALL.names.forEach(function (name) {
  20181. var props = ALL[name];
  20182. techOptions[props.getterName] = _this4[props.privateName];
  20183. });
  20184. assign$1(techOptions, this.options_[titleTechName]);
  20185. assign$1(techOptions, this.options_[camelTechName]);
  20186. assign$1(techOptions, this.options_[techName.toLowerCase()]);
  20187. if (this.tag) {
  20188. techOptions.tag = this.tag;
  20189. }
  20190. if (source && source.src === this.cache_.src && this.cache_.currentTime > 0) {
  20191. techOptions.startTime = this.cache_.currentTime;
  20192. } // Initialize tech instance
  20193. var TechClass = Tech.getTech(techName);
  20194. if (!TechClass) {
  20195. throw new Error("No Tech named '" + titleTechName + "' exists! '" + titleTechName + "' should be registered using videojs.registerTech()'");
  20196. }
  20197. this.tech_ = new TechClass(techOptions); // player.triggerReady is always async, so don't need this to be async
  20198. this.tech_.ready(bind(this, this.handleTechReady_), true);
  20199. textTrackConverter.jsonToTextTracks(this.textTracksJson_ || [], this.tech_); // Listen to all HTML5-defined events and trigger them on the player
  20200. TECH_EVENTS_RETRIGGER.forEach(function (event) {
  20201. _this4.on(_this4.tech_, event, function (e) {
  20202. return _this4["handleTech" + toTitleCase$1(event) + "_"](e);
  20203. });
  20204. });
  20205. Object.keys(TECH_EVENTS_QUEUE).forEach(function (event) {
  20206. _this4.on(_this4.tech_, event, function (eventObj) {
  20207. if (_this4.tech_.playbackRate() === 0 && _this4.tech_.seeking()) {
  20208. _this4.queuedCallbacks_.push({
  20209. callback: _this4["handleTech" + TECH_EVENTS_QUEUE[event] + "_"].bind(_this4),
  20210. event: eventObj
  20211. });
  20212. return;
  20213. }
  20214. _this4["handleTech" + TECH_EVENTS_QUEUE[event] + "_"](eventObj);
  20215. });
  20216. });
  20217. this.on(this.tech_, 'loadstart', function (e) {
  20218. return _this4.handleTechLoadStart_(e);
  20219. });
  20220. this.on(this.tech_, 'sourceset', function (e) {
  20221. return _this4.handleTechSourceset_(e);
  20222. });
  20223. this.on(this.tech_, 'waiting', function (e) {
  20224. return _this4.handleTechWaiting_(e);
  20225. });
  20226. this.on(this.tech_, 'ended', function (e) {
  20227. return _this4.handleTechEnded_(e);
  20228. });
  20229. this.on(this.tech_, 'seeking', function (e) {
  20230. return _this4.handleTechSeeking_(e);
  20231. });
  20232. this.on(this.tech_, 'play', function (e) {
  20233. return _this4.handleTechPlay_(e);
  20234. });
  20235. this.on(this.tech_, 'firstplay', function (e) {
  20236. return _this4.handleTechFirstPlay_(e);
  20237. });
  20238. this.on(this.tech_, 'pause', function (e) {
  20239. return _this4.handleTechPause_(e);
  20240. });
  20241. this.on(this.tech_, 'durationchange', function (e) {
  20242. return _this4.handleTechDurationChange_(e);
  20243. });
  20244. this.on(this.tech_, 'fullscreenchange', function (e, data) {
  20245. return _this4.handleTechFullscreenChange_(e, data);
  20246. });
  20247. this.on(this.tech_, 'fullscreenerror', function (e, err) {
  20248. return _this4.handleTechFullscreenError_(e, err);
  20249. });
  20250. this.on(this.tech_, 'enterpictureinpicture', function (e) {
  20251. return _this4.handleTechEnterPictureInPicture_(e);
  20252. });
  20253. this.on(this.tech_, 'leavepictureinpicture', function (e) {
  20254. return _this4.handleTechLeavePictureInPicture_(e);
  20255. });
  20256. this.on(this.tech_, 'error', function (e) {
  20257. return _this4.handleTechError_(e);
  20258. });
  20259. this.on(this.tech_, 'posterchange', function (e) {
  20260. return _this4.handleTechPosterChange_(e);
  20261. });
  20262. this.on(this.tech_, 'textdata', function (e) {
  20263. return _this4.handleTechTextData_(e);
  20264. });
  20265. this.on(this.tech_, 'ratechange', function (e) {
  20266. return _this4.handleTechRateChange_(e);
  20267. });
  20268. this.on(this.tech_, 'loadedmetadata', this.boundUpdateStyleEl_);
  20269. this.usingNativeControls(this.techGet_('controls'));
  20270. if (this.controls() && !this.usingNativeControls()) {
  20271. this.addTechControlsListeners_();
  20272. } // Add the tech element in the DOM if it was not already there
  20273. // Make sure to not insert the original video element if using Html5
  20274. if (this.tech_.el().parentNode !== this.el() && (titleTechName !== 'Html5' || !this.tag)) {
  20275. prependTo(this.tech_.el(), this.el());
  20276. } // Get rid of the original video tag reference after the first tech is loaded
  20277. if (this.tag) {
  20278. this.tag.player = null;
  20279. this.tag = null;
  20280. }
  20281. }
  20282. /**
  20283. * Unload and dispose of the current playback {@link Tech}.
  20284. *
  20285. * @private
  20286. */
  20287. ;
  20288. _proto.unloadTech_ = function unloadTech_() {
  20289. var _this5 = this;
  20290. // Save the current text tracks so that we can reuse the same text tracks with the next tech
  20291. ALL.names.forEach(function (name) {
  20292. var props = ALL[name];
  20293. _this5[props.privateName] = _this5[props.getterName]();
  20294. });
  20295. this.textTracksJson_ = textTrackConverter.textTracksToJson(this.tech_);
  20296. this.isReady_ = false;
  20297. this.tech_.dispose();
  20298. this.tech_ = false;
  20299. if (this.isPosterFromTech_) {
  20300. this.poster_ = '';
  20301. this.trigger('posterchange');
  20302. }
  20303. this.isPosterFromTech_ = false;
  20304. }
  20305. /**
  20306. * Return a reference to the current {@link Tech}.
  20307. * It will print a warning by default about the danger of using the tech directly
  20308. * but any argument that is passed in will silence the warning.
  20309. *
  20310. * @param {*} [safety]
  20311. * Anything passed in to silence the warning
  20312. *
  20313. * @return {Tech}
  20314. * The Tech
  20315. */
  20316. ;
  20317. _proto.tech = function tech(safety) {
  20318. if (safety === undefined) {
  20319. 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');
  20320. }
  20321. return this.tech_;
  20322. }
  20323. /**
  20324. * Set up click and touch listeners for the playback element
  20325. *
  20326. * - On desktops: a click on the video itself will toggle playback
  20327. * - On mobile devices: a click on the video toggles controls
  20328. * which is done by toggling the user state between active and
  20329. * inactive
  20330. * - A tap can signal that a user has become active or has become inactive
  20331. * e.g. a quick tap on an iPhone movie should reveal the controls. Another
  20332. * quick tap should hide them again (signaling the user is in an inactive
  20333. * viewing state)
  20334. * - In addition to this, we still want the user to be considered inactive after
  20335. * a few seconds of inactivity.
  20336. *
  20337. * > Note: the only part of iOS interaction we can't mimic with this setup
  20338. * is a touch and hold on the video element counting as activity in order to
  20339. * keep the controls showing, but that shouldn't be an issue. A touch and hold
  20340. * on any controls will still keep the user active
  20341. *
  20342. * @private
  20343. */
  20344. ;
  20345. _proto.addTechControlsListeners_ = function addTechControlsListeners_() {
  20346. // Make sure to remove all the previous listeners in case we are called multiple times.
  20347. this.removeTechControlsListeners_();
  20348. this.on(this.tech_, 'click', this.boundHandleTechClick_);
  20349. this.on(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_); // If the controls were hidden we don't want that to change without a tap event
  20350. // so we'll check if the controls were already showing before reporting user
  20351. // activity
  20352. this.on(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);
  20353. this.on(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);
  20354. this.on(this.tech_, 'touchend', this.boundHandleTechTouchEnd_); // The tap listener needs to come after the touchend listener because the tap
  20355. // listener cancels out any reportedUserActivity when setting userActive(false)
  20356. this.on(this.tech_, 'tap', this.boundHandleTechTap_);
  20357. }
  20358. /**
  20359. * Remove the listeners used for click and tap controls. This is needed for
  20360. * toggling to controls disabled, where a tap/touch should do nothing.
  20361. *
  20362. * @private
  20363. */
  20364. ;
  20365. _proto.removeTechControlsListeners_ = function removeTechControlsListeners_() {
  20366. // We don't want to just use `this.off()` because there might be other needed
  20367. // listeners added by techs that extend this.
  20368. this.off(this.tech_, 'tap', this.boundHandleTechTap_);
  20369. this.off(this.tech_, 'touchstart', this.boundHandleTechTouchStart_);
  20370. this.off(this.tech_, 'touchmove', this.boundHandleTechTouchMove_);
  20371. this.off(this.tech_, 'touchend', this.boundHandleTechTouchEnd_);
  20372. this.off(this.tech_, 'click', this.boundHandleTechClick_);
  20373. this.off(this.tech_, 'dblclick', this.boundHandleTechDoubleClick_);
  20374. }
  20375. /**
  20376. * Player waits for the tech to be ready
  20377. *
  20378. * @private
  20379. */
  20380. ;
  20381. _proto.handleTechReady_ = function handleTechReady_() {
  20382. this.triggerReady(); // Keep the same volume as before
  20383. if (this.cache_.volume) {
  20384. this.techCall_('setVolume', this.cache_.volume);
  20385. } // Look if the tech found a higher resolution poster while loading
  20386. this.handleTechPosterChange_(); // Update the duration if available
  20387. this.handleTechDurationChange_();
  20388. }
  20389. /**
  20390. * Retrigger the `loadstart` event that was triggered by the {@link Tech}. This
  20391. * function will also trigger {@link Player#firstplay} if it is the first loadstart
  20392. * for a video.
  20393. *
  20394. * @fires Player#loadstart
  20395. * @fires Player#firstplay
  20396. * @listens Tech#loadstart
  20397. * @private
  20398. */
  20399. ;
  20400. _proto.handleTechLoadStart_ = function handleTechLoadStart_() {
  20401. // TODO: Update to use `emptied` event instead. See #1277.
  20402. this.removeClass('vjs-ended');
  20403. this.removeClass('vjs-seeking'); // reset the error state
  20404. this.error(null); // Update the duration
  20405. this.handleTechDurationChange_(); // If it's already playing we want to trigger a firstplay event now.
  20406. // The firstplay event relies on both the play and loadstart events
  20407. // which can happen in any order for a new source
  20408. if (!this.paused()) {
  20409. /**
  20410. * Fired when the user agent begins looking for media data
  20411. *
  20412. * @event Player#loadstart
  20413. * @type {EventTarget~Event}
  20414. */
  20415. this.trigger('loadstart');
  20416. this.trigger('firstplay');
  20417. } else {
  20418. // reset the hasStarted state
  20419. this.hasStarted(false);
  20420. this.trigger('loadstart');
  20421. } // autoplay happens after loadstart for the browser,
  20422. // so we mimic that behavior
  20423. this.manualAutoplay_(this.autoplay() === true && this.options_.normalizeAutoplay ? 'play' : this.autoplay());
  20424. }
  20425. /**
  20426. * Handle autoplay string values, rather than the typical boolean
  20427. * values that should be handled by the tech. Note that this is not
  20428. * part of any specification. Valid values and what they do can be
  20429. * found on the autoplay getter at Player#autoplay()
  20430. */
  20431. ;
  20432. _proto.manualAutoplay_ = function manualAutoplay_(type) {
  20433. var _this6 = this;
  20434. if (!this.tech_ || typeof type !== 'string') {
  20435. return;
  20436. } // Save original muted() value, set muted to true, and attempt to play().
  20437. // On promise rejection, restore muted from saved value
  20438. var resolveMuted = function resolveMuted() {
  20439. var previouslyMuted = _this6.muted();
  20440. _this6.muted(true);
  20441. var restoreMuted = function restoreMuted() {
  20442. _this6.muted(previouslyMuted);
  20443. }; // restore muted on play terminatation
  20444. _this6.playTerminatedQueue_.push(restoreMuted);
  20445. var mutedPromise = _this6.play();
  20446. if (!isPromise(mutedPromise)) {
  20447. return;
  20448. }
  20449. return mutedPromise["catch"](function (err) {
  20450. restoreMuted();
  20451. throw new Error("Rejection at manualAutoplay. Restoring muted value. " + (err ? err : ''));
  20452. });
  20453. };
  20454. var promise; // if muted defaults to true
  20455. // the only thing we can do is call play
  20456. if (type === 'any' && !this.muted()) {
  20457. promise = this.play();
  20458. if (isPromise(promise)) {
  20459. promise = promise["catch"](resolveMuted);
  20460. }
  20461. } else if (type === 'muted' && !this.muted()) {
  20462. promise = resolveMuted();
  20463. } else {
  20464. promise = this.play();
  20465. }
  20466. if (!isPromise(promise)) {
  20467. return;
  20468. }
  20469. return promise.then(function () {
  20470. _this6.trigger({
  20471. type: 'autoplay-success',
  20472. autoplay: type
  20473. });
  20474. })["catch"](function () {
  20475. _this6.trigger({
  20476. type: 'autoplay-failure',
  20477. autoplay: type
  20478. });
  20479. });
  20480. }
  20481. /**
  20482. * Update the internal source caches so that we return the correct source from
  20483. * `src()`, `currentSource()`, and `currentSources()`.
  20484. *
  20485. * > Note: `currentSources` will not be updated if the source that is passed in exists
  20486. * in the current `currentSources` cache.
  20487. *
  20488. *
  20489. * @param {Tech~SourceObject} srcObj
  20490. * A string or object source to update our caches to.
  20491. */
  20492. ;
  20493. _proto.updateSourceCaches_ = function updateSourceCaches_(srcObj) {
  20494. if (srcObj === void 0) {
  20495. srcObj = '';
  20496. }
  20497. var src = srcObj;
  20498. var type = '';
  20499. if (typeof src !== 'string') {
  20500. src = srcObj.src;
  20501. type = srcObj.type;
  20502. } // make sure all the caches are set to default values
  20503. // to prevent null checking
  20504. this.cache_.source = this.cache_.source || {};
  20505. this.cache_.sources = this.cache_.sources || []; // try to get the type of the src that was passed in
  20506. if (src && !type) {
  20507. type = findMimetype(this, src);
  20508. } // update `currentSource` cache always
  20509. this.cache_.source = mergeOptions$3({}, srcObj, {
  20510. src: src,
  20511. type: type
  20512. });
  20513. var matchingSources = this.cache_.sources.filter(function (s) {
  20514. return s.src && s.src === src;
  20515. });
  20516. var sourceElSources = [];
  20517. var sourceEls = this.$$('source');
  20518. var matchingSourceEls = [];
  20519. for (var i = 0; i < sourceEls.length; i++) {
  20520. var sourceObj = getAttributes(sourceEls[i]);
  20521. sourceElSources.push(sourceObj);
  20522. if (sourceObj.src && sourceObj.src === src) {
  20523. matchingSourceEls.push(sourceObj.src);
  20524. }
  20525. } // if we have matching source els but not matching sources
  20526. // the current source cache is not up to date
  20527. if (matchingSourceEls.length && !matchingSources.length) {
  20528. this.cache_.sources = sourceElSources; // if we don't have matching source or source els set the
  20529. // sources cache to the `currentSource` cache
  20530. } else if (!matchingSources.length) {
  20531. this.cache_.sources = [this.cache_.source];
  20532. } // update the tech `src` cache
  20533. this.cache_.src = src;
  20534. }
  20535. /**
  20536. * *EXPERIMENTAL* Fired when the source is set or changed on the {@link Tech}
  20537. * causing the media element to reload.
  20538. *
  20539. * It will fire for the initial source and each subsequent source.
  20540. * This event is a custom event from Video.js and is triggered by the {@link Tech}.
  20541. *
  20542. * The event object for this event contains a `src` property that will contain the source
  20543. * that was available when the event was triggered. This is generally only necessary if Video.js
  20544. * is switching techs while the source was being changed.
  20545. *
  20546. * It is also fired when `load` is called on the player (or media element)
  20547. * because the {@link https://html.spec.whatwg.org/multipage/media.html#dom-media-load|specification for `load`}
  20548. * says that the resource selection algorithm needs to be aborted and restarted.
  20549. * In this case, it is very likely that the `src` property will be set to the
  20550. * empty string `""` to indicate we do not know what the source will be but
  20551. * that it is changing.
  20552. *
  20553. * *This event is currently still experimental and may change in minor releases.*
  20554. * __To use this, pass `enableSourceset` option to the player.__
  20555. *
  20556. * @event Player#sourceset
  20557. * @type {EventTarget~Event}
  20558. * @prop {string} src
  20559. * The source url available when the `sourceset` was triggered.
  20560. * It will be an empty string if we cannot know what the source is
  20561. * but know that the source will change.
  20562. */
  20563. /**
  20564. * Retrigger the `sourceset` event that was triggered by the {@link Tech}.
  20565. *
  20566. * @fires Player#sourceset
  20567. * @listens Tech#sourceset
  20568. * @private
  20569. */
  20570. ;
  20571. _proto.handleTechSourceset_ = function handleTechSourceset_(event) {
  20572. var _this7 = this;
  20573. // only update the source cache when the source
  20574. // was not updated using the player api
  20575. if (!this.changingSrc_) {
  20576. var updateSourceCaches = function updateSourceCaches(src) {
  20577. return _this7.updateSourceCaches_(src);
  20578. };
  20579. var playerSrc = this.currentSource().src;
  20580. var eventSrc = event.src; // if we have a playerSrc that is not a blob, and a tech src that is a blob
  20581. if (playerSrc && !/^blob:/.test(playerSrc) && /^blob:/.test(eventSrc)) {
  20582. // if both the tech source and the player source were updated we assume
  20583. // something like @videojs/http-streaming did the sourceset and skip updating the source cache.
  20584. if (!this.lastSource_ || this.lastSource_.tech !== eventSrc && this.lastSource_.player !== playerSrc) {
  20585. updateSourceCaches = function updateSourceCaches() {};
  20586. }
  20587. } // update the source to the initial source right away
  20588. // in some cases this will be empty string
  20589. updateSourceCaches(eventSrc); // if the `sourceset` `src` was an empty string
  20590. // wait for a `loadstart` to update the cache to `currentSrc`.
  20591. // If a sourceset happens before a `loadstart`, we reset the state
  20592. if (!event.src) {
  20593. this.tech_.any(['sourceset', 'loadstart'], function (e) {
  20594. // if a sourceset happens before a `loadstart` there
  20595. // is nothing to do as this `handleTechSourceset_`
  20596. // will be called again and this will be handled there.
  20597. if (e.type === 'sourceset') {
  20598. return;
  20599. }
  20600. var techSrc = _this7.techGet('currentSrc');
  20601. _this7.lastSource_.tech = techSrc;
  20602. _this7.updateSourceCaches_(techSrc);
  20603. });
  20604. }
  20605. }
  20606. this.lastSource_ = {
  20607. player: this.currentSource().src,
  20608. tech: event.src
  20609. };
  20610. this.trigger({
  20611. src: event.src,
  20612. type: 'sourceset'
  20613. });
  20614. }
  20615. /**
  20616. * Add/remove the vjs-has-started class
  20617. *
  20618. * @fires Player#firstplay
  20619. *
  20620. * @param {boolean} request
  20621. * - true: adds the class
  20622. * - false: remove the class
  20623. *
  20624. * @return {boolean}
  20625. * the boolean value of hasStarted_
  20626. */
  20627. ;
  20628. _proto.hasStarted = function hasStarted(request) {
  20629. if (request === undefined) {
  20630. // act as getter, if we have no request to change
  20631. return this.hasStarted_;
  20632. }
  20633. if (request === this.hasStarted_) {
  20634. return;
  20635. }
  20636. this.hasStarted_ = request;
  20637. if (this.hasStarted_) {
  20638. this.addClass('vjs-has-started');
  20639. this.trigger('firstplay');
  20640. } else {
  20641. this.removeClass('vjs-has-started');
  20642. }
  20643. }
  20644. /**
  20645. * Fired whenever the media begins or resumes playback
  20646. *
  20647. * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play}
  20648. * @fires Player#play
  20649. * @listens Tech#play
  20650. * @private
  20651. */
  20652. ;
  20653. _proto.handleTechPlay_ = function handleTechPlay_() {
  20654. this.removeClass('vjs-ended');
  20655. this.removeClass('vjs-paused');
  20656. this.addClass('vjs-playing'); // hide the poster when the user hits play
  20657. this.hasStarted(true);
  20658. /**
  20659. * Triggered whenever an {@link Tech#play} event happens. Indicates that
  20660. * playback has started or resumed.
  20661. *
  20662. * @event Player#play
  20663. * @type {EventTarget~Event}
  20664. */
  20665. this.trigger('play');
  20666. }
  20667. /**
  20668. * Retrigger the `ratechange` event that was triggered by the {@link Tech}.
  20669. *
  20670. * If there were any events queued while the playback rate was zero, fire
  20671. * those events now.
  20672. *
  20673. * @private
  20674. * @method Player#handleTechRateChange_
  20675. * @fires Player#ratechange
  20676. * @listens Tech#ratechange
  20677. */
  20678. ;
  20679. _proto.handleTechRateChange_ = function handleTechRateChange_() {
  20680. if (this.tech_.playbackRate() > 0 && this.cache_.lastPlaybackRate === 0) {
  20681. this.queuedCallbacks_.forEach(function (queued) {
  20682. return queued.callback(queued.event);
  20683. });
  20684. this.queuedCallbacks_ = [];
  20685. }
  20686. this.cache_.lastPlaybackRate = this.tech_.playbackRate();
  20687. /**
  20688. * Fires when the playing speed of the audio/video is changed
  20689. *
  20690. * @event Player#ratechange
  20691. * @type {event}
  20692. */
  20693. this.trigger('ratechange');
  20694. }
  20695. /**
  20696. * Retrigger the `waiting` event that was triggered by the {@link Tech}.
  20697. *
  20698. * @fires Player#waiting
  20699. * @listens Tech#waiting
  20700. * @private
  20701. */
  20702. ;
  20703. _proto.handleTechWaiting_ = function handleTechWaiting_() {
  20704. var _this8 = this;
  20705. this.addClass('vjs-waiting');
  20706. /**
  20707. * A readyState change on the DOM element has caused playback to stop.
  20708. *
  20709. * @event Player#waiting
  20710. * @type {EventTarget~Event}
  20711. */
  20712. this.trigger('waiting'); // Browsers may emit a timeupdate event after a waiting event. In order to prevent
  20713. // premature removal of the waiting class, wait for the time to change.
  20714. var timeWhenWaiting = this.currentTime();
  20715. var timeUpdateListener = function timeUpdateListener() {
  20716. if (timeWhenWaiting !== _this8.currentTime()) {
  20717. _this8.removeClass('vjs-waiting');
  20718. _this8.off('timeupdate', timeUpdateListener);
  20719. }
  20720. };
  20721. this.on('timeupdate', timeUpdateListener);
  20722. }
  20723. /**
  20724. * Retrigger the `canplay` event that was triggered by the {@link Tech}.
  20725. * > Note: This is not consistent between browsers. See #1351
  20726. *
  20727. * @fires Player#canplay
  20728. * @listens Tech#canplay
  20729. * @private
  20730. */
  20731. ;
  20732. _proto.handleTechCanPlay_ = function handleTechCanPlay_() {
  20733. this.removeClass('vjs-waiting');
  20734. /**
  20735. * The media has a readyState of HAVE_FUTURE_DATA or greater.
  20736. *
  20737. * @event Player#canplay
  20738. * @type {EventTarget~Event}
  20739. */
  20740. this.trigger('canplay');
  20741. }
  20742. /**
  20743. * Retrigger the `canplaythrough` event that was triggered by the {@link Tech}.
  20744. *
  20745. * @fires Player#canplaythrough
  20746. * @listens Tech#canplaythrough
  20747. * @private
  20748. */
  20749. ;
  20750. _proto.handleTechCanPlayThrough_ = function handleTechCanPlayThrough_() {
  20751. this.removeClass('vjs-waiting');
  20752. /**
  20753. * The media has a readyState of HAVE_ENOUGH_DATA or greater. This means that the
  20754. * entire media file can be played without buffering.
  20755. *
  20756. * @event Player#canplaythrough
  20757. * @type {EventTarget~Event}
  20758. */
  20759. this.trigger('canplaythrough');
  20760. }
  20761. /**
  20762. * Retrigger the `playing` event that was triggered by the {@link Tech}.
  20763. *
  20764. * @fires Player#playing
  20765. * @listens Tech#playing
  20766. * @private
  20767. */
  20768. ;
  20769. _proto.handleTechPlaying_ = function handleTechPlaying_() {
  20770. this.removeClass('vjs-waiting');
  20771. /**
  20772. * The media is no longer blocked from playback, and has started playing.
  20773. *
  20774. * @event Player#playing
  20775. * @type {EventTarget~Event}
  20776. */
  20777. this.trigger('playing');
  20778. }
  20779. /**
  20780. * Retrigger the `seeking` event that was triggered by the {@link Tech}.
  20781. *
  20782. * @fires Player#seeking
  20783. * @listens Tech#seeking
  20784. * @private
  20785. */
  20786. ;
  20787. _proto.handleTechSeeking_ = function handleTechSeeking_() {
  20788. this.addClass('vjs-seeking');
  20789. /**
  20790. * Fired whenever the player is jumping to a new time
  20791. *
  20792. * @event Player#seeking
  20793. * @type {EventTarget~Event}
  20794. */
  20795. this.trigger('seeking');
  20796. }
  20797. /**
  20798. * Retrigger the `seeked` event that was triggered by the {@link Tech}.
  20799. *
  20800. * @fires Player#seeked
  20801. * @listens Tech#seeked
  20802. * @private
  20803. */
  20804. ;
  20805. _proto.handleTechSeeked_ = function handleTechSeeked_() {
  20806. this.removeClass('vjs-seeking');
  20807. this.removeClass('vjs-ended');
  20808. /**
  20809. * Fired when the player has finished jumping to a new time
  20810. *
  20811. * @event Player#seeked
  20812. * @type {EventTarget~Event}
  20813. */
  20814. this.trigger('seeked');
  20815. }
  20816. /**
  20817. * Retrigger the `firstplay` event that was triggered by the {@link Tech}.
  20818. *
  20819. * @fires Player#firstplay
  20820. * @listens Tech#firstplay
  20821. * @deprecated As of 6.0 firstplay event is deprecated.
  20822. * As of 6.0 passing the `starttime` option to the player and the firstplay event are deprecated.
  20823. * @private
  20824. */
  20825. ;
  20826. _proto.handleTechFirstPlay_ = function handleTechFirstPlay_() {
  20827. // If the first starttime attribute is specified
  20828. // then we will start at the given offset in seconds
  20829. if (this.options_.starttime) {
  20830. log$1.warn('Passing the `starttime` option to the player will be deprecated in 6.0');
  20831. this.currentTime(this.options_.starttime);
  20832. }
  20833. this.addClass('vjs-has-started');
  20834. /**
  20835. * Fired the first time a video is played. Not part of the HLS spec, and this is
  20836. * probably not the best implementation yet, so use sparingly. If you don't have a
  20837. * reason to prevent playback, use `myPlayer.one('play');` instead.
  20838. *
  20839. * @event Player#firstplay
  20840. * @deprecated As of 6.0 firstplay event is deprecated.
  20841. * @type {EventTarget~Event}
  20842. */
  20843. this.trigger('firstplay');
  20844. }
  20845. /**
  20846. * Retrigger the `pause` event that was triggered by the {@link Tech}.
  20847. *
  20848. * @fires Player#pause
  20849. * @listens Tech#pause
  20850. * @private
  20851. */
  20852. ;
  20853. _proto.handleTechPause_ = function handleTechPause_() {
  20854. this.removeClass('vjs-playing');
  20855. this.addClass('vjs-paused');
  20856. /**
  20857. * Fired whenever the media has been paused
  20858. *
  20859. * @event Player#pause
  20860. * @type {EventTarget~Event}
  20861. */
  20862. this.trigger('pause');
  20863. }
  20864. /**
  20865. * Retrigger the `ended` event that was triggered by the {@link Tech}.
  20866. *
  20867. * @fires Player#ended
  20868. * @listens Tech#ended
  20869. * @private
  20870. */
  20871. ;
  20872. _proto.handleTechEnded_ = function handleTechEnded_() {
  20873. this.addClass('vjs-ended');
  20874. this.removeClass('vjs-waiting');
  20875. if (this.options_.loop) {
  20876. this.currentTime(0);
  20877. this.play();
  20878. } else if (!this.paused()) {
  20879. this.pause();
  20880. }
  20881. /**
  20882. * Fired when the end of the media resource is reached (currentTime == duration)
  20883. *
  20884. * @event Player#ended
  20885. * @type {EventTarget~Event}
  20886. */
  20887. this.trigger('ended');
  20888. }
  20889. /**
  20890. * Fired when the duration of the media resource is first known or changed
  20891. *
  20892. * @listens Tech#durationchange
  20893. * @private
  20894. */
  20895. ;
  20896. _proto.handleTechDurationChange_ = function handleTechDurationChange_() {
  20897. this.duration(this.techGet_('duration'));
  20898. }
  20899. /**
  20900. * Handle a click on the media element to play/pause
  20901. *
  20902. * @param {EventTarget~Event} event
  20903. * the event that caused this function to trigger
  20904. *
  20905. * @listens Tech#click
  20906. * @private
  20907. */
  20908. ;
  20909. _proto.handleTechClick_ = function handleTechClick_(event) {
  20910. // When controls are disabled a click should not toggle playback because
  20911. // the click is considered a control
  20912. if (!this.controls_) {
  20913. return;
  20914. }
  20915. if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.click === undefined || this.options_.userActions.click !== false) {
  20916. if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.click === 'function') {
  20917. this.options_.userActions.click.call(this, event);
  20918. } else if (this.paused()) {
  20919. silencePromise(this.play());
  20920. } else {
  20921. this.pause();
  20922. }
  20923. }
  20924. }
  20925. /**
  20926. * Handle a double-click on the media element to enter/exit fullscreen
  20927. *
  20928. * @param {EventTarget~Event} event
  20929. * the event that caused this function to trigger
  20930. *
  20931. * @listens Tech#dblclick
  20932. * @private
  20933. */
  20934. ;
  20935. _proto.handleTechDoubleClick_ = function handleTechDoubleClick_(event) {
  20936. if (!this.controls_) {
  20937. return;
  20938. } // we do not want to toggle fullscreen state
  20939. // when double-clicking inside a control bar or a modal
  20940. var inAllowedEls = Array.prototype.some.call(this.$$('.vjs-control-bar, .vjs-modal-dialog'), function (el) {
  20941. return el.contains(event.target);
  20942. });
  20943. if (!inAllowedEls) {
  20944. /*
  20945. * options.userActions.doubleClick
  20946. *
  20947. * If `undefined` or `true`, double-click toggles fullscreen if controls are present
  20948. * Set to `false` to disable double-click handling
  20949. * Set to a function to substitute an external double-click handler
  20950. */
  20951. if (this.options_ === undefined || this.options_.userActions === undefined || this.options_.userActions.doubleClick === undefined || this.options_.userActions.doubleClick !== false) {
  20952. if (this.options_ !== undefined && this.options_.userActions !== undefined && typeof this.options_.userActions.doubleClick === 'function') {
  20953. this.options_.userActions.doubleClick.call(this, event);
  20954. } else if (this.isFullscreen()) {
  20955. this.exitFullscreen();
  20956. } else {
  20957. this.requestFullscreen();
  20958. }
  20959. }
  20960. }
  20961. }
  20962. /**
  20963. * Handle a tap on the media element. It will toggle the user
  20964. * activity state, which hides and shows the controls.
  20965. *
  20966. * @listens Tech#tap
  20967. * @private
  20968. */
  20969. ;
  20970. _proto.handleTechTap_ = function handleTechTap_() {
  20971. this.userActive(!this.userActive());
  20972. }
  20973. /**
  20974. * Handle touch to start
  20975. *
  20976. * @listens Tech#touchstart
  20977. * @private
  20978. */
  20979. ;
  20980. _proto.handleTechTouchStart_ = function handleTechTouchStart_() {
  20981. this.userWasActive = this.userActive();
  20982. }
  20983. /**
  20984. * Handle touch to move
  20985. *
  20986. * @listens Tech#touchmove
  20987. * @private
  20988. */
  20989. ;
  20990. _proto.handleTechTouchMove_ = function handleTechTouchMove_() {
  20991. if (this.userWasActive) {
  20992. this.reportUserActivity();
  20993. }
  20994. }
  20995. /**
  20996. * Handle touch to end
  20997. *
  20998. * @param {EventTarget~Event} event
  20999. * the touchend event that triggered
  21000. * this function
  21001. *
  21002. * @listens Tech#touchend
  21003. * @private
  21004. */
  21005. ;
  21006. _proto.handleTechTouchEnd_ = function handleTechTouchEnd_(event) {
  21007. // Stop the mouse events from also happening
  21008. if (event.cancelable) {
  21009. event.preventDefault();
  21010. }
  21011. }
  21012. /**
  21013. * native click events on the SWF aren't triggered on IE11, Win8.1RT
  21014. * use stageclick events triggered from inside the SWF instead
  21015. *
  21016. * @private
  21017. * @listens stageclick
  21018. */
  21019. ;
  21020. _proto.handleStageClick_ = function handleStageClick_() {
  21021. this.reportUserActivity();
  21022. }
  21023. /**
  21024. * @private
  21025. */
  21026. ;
  21027. _proto.toggleFullscreenClass_ = function toggleFullscreenClass_() {
  21028. if (this.isFullscreen()) {
  21029. this.addClass('vjs-fullscreen');
  21030. } else {
  21031. this.removeClass('vjs-fullscreen');
  21032. }
  21033. }
  21034. /**
  21035. * when the document fschange event triggers it calls this
  21036. */
  21037. ;
  21038. _proto.documentFullscreenChange_ = function documentFullscreenChange_(e) {
  21039. var targetPlayer = e.target.player; // if another player was fullscreen
  21040. // do a null check for targetPlayer because older firefox's would put document as e.target
  21041. if (targetPlayer && targetPlayer !== this) {
  21042. return;
  21043. }
  21044. var el = this.el();
  21045. var isFs = document[this.fsApi_.fullscreenElement] === el;
  21046. if (!isFs && el.matches) {
  21047. isFs = el.matches(':' + this.fsApi_.fullscreen);
  21048. } else if (!isFs && el.msMatchesSelector) {
  21049. isFs = el.msMatchesSelector(':' + this.fsApi_.fullscreen);
  21050. }
  21051. this.isFullscreen(isFs);
  21052. }
  21053. /**
  21054. * Handle Tech Fullscreen Change
  21055. *
  21056. * @param {EventTarget~Event} event
  21057. * the fullscreenchange event that triggered this function
  21058. *
  21059. * @param {Object} data
  21060. * the data that was sent with the event
  21061. *
  21062. * @private
  21063. * @listens Tech#fullscreenchange
  21064. * @fires Player#fullscreenchange
  21065. */
  21066. ;
  21067. _proto.handleTechFullscreenChange_ = function handleTechFullscreenChange_(event, data) {
  21068. var _this9 = this;
  21069. if (data) {
  21070. if (data.nativeIOSFullscreen) {
  21071. this.addClass('vjs-ios-native-fs');
  21072. this.tech_.one('webkitendfullscreen', function () {
  21073. _this9.removeClass('vjs-ios-native-fs');
  21074. });
  21075. }
  21076. this.isFullscreen(data.isFullscreen);
  21077. }
  21078. };
  21079. _proto.handleTechFullscreenError_ = function handleTechFullscreenError_(event, err) {
  21080. this.trigger('fullscreenerror', err);
  21081. }
  21082. /**
  21083. * @private
  21084. */
  21085. ;
  21086. _proto.togglePictureInPictureClass_ = function togglePictureInPictureClass_() {
  21087. if (this.isInPictureInPicture()) {
  21088. this.addClass('vjs-picture-in-picture');
  21089. } else {
  21090. this.removeClass('vjs-picture-in-picture');
  21091. }
  21092. }
  21093. /**
  21094. * Handle Tech Enter Picture-in-Picture.
  21095. *
  21096. * @param {EventTarget~Event} event
  21097. * the enterpictureinpicture event that triggered this function
  21098. *
  21099. * @private
  21100. * @listens Tech#enterpictureinpicture
  21101. */
  21102. ;
  21103. _proto.handleTechEnterPictureInPicture_ = function handleTechEnterPictureInPicture_(event) {
  21104. this.isInPictureInPicture(true);
  21105. }
  21106. /**
  21107. * Handle Tech Leave Picture-in-Picture.
  21108. *
  21109. * @param {EventTarget~Event} event
  21110. * the leavepictureinpicture event that triggered this function
  21111. *
  21112. * @private
  21113. * @listens Tech#leavepictureinpicture
  21114. */
  21115. ;
  21116. _proto.handleTechLeavePictureInPicture_ = function handleTechLeavePictureInPicture_(event) {
  21117. this.isInPictureInPicture(false);
  21118. }
  21119. /**
  21120. * Fires when an error occurred during the loading of an audio/video.
  21121. *
  21122. * @private
  21123. * @listens Tech#error
  21124. */
  21125. ;
  21126. _proto.handleTechError_ = function handleTechError_() {
  21127. var error = this.tech_.error();
  21128. this.error(error);
  21129. }
  21130. /**
  21131. * Retrigger the `textdata` event that was triggered by the {@link Tech}.
  21132. *
  21133. * @fires Player#textdata
  21134. * @listens Tech#textdata
  21135. * @private
  21136. */
  21137. ;
  21138. _proto.handleTechTextData_ = function handleTechTextData_() {
  21139. var data = null;
  21140. if (arguments.length > 1) {
  21141. data = arguments[1];
  21142. }
  21143. /**
  21144. * Fires when we get a textdata event from tech
  21145. *
  21146. * @event Player#textdata
  21147. * @type {EventTarget~Event}
  21148. */
  21149. this.trigger('textdata', data);
  21150. }
  21151. /**
  21152. * Get object for cached values.
  21153. *
  21154. * @return {Object}
  21155. * get the current object cache
  21156. */
  21157. ;
  21158. _proto.getCache = function getCache() {
  21159. return this.cache_;
  21160. }
  21161. /**
  21162. * Resets the internal cache object.
  21163. *
  21164. * Using this function outside the player constructor or reset method may
  21165. * have unintended side-effects.
  21166. *
  21167. * @private
  21168. */
  21169. ;
  21170. _proto.resetCache_ = function resetCache_() {
  21171. this.cache_ = {
  21172. // Right now, the currentTime is not _really_ cached because it is always
  21173. // retrieved from the tech (see: currentTime). However, for completeness,
  21174. // we set it to zero here to ensure that if we do start actually caching
  21175. // it, we reset it along with everything else.
  21176. currentTime: 0,
  21177. initTime: 0,
  21178. inactivityTimeout: this.options_.inactivityTimeout,
  21179. duration: NaN,
  21180. lastVolume: 1,
  21181. lastPlaybackRate: this.defaultPlaybackRate(),
  21182. media: null,
  21183. src: '',
  21184. source: {},
  21185. sources: [],
  21186. playbackRates: [],
  21187. volume: 1
  21188. };
  21189. }
  21190. /**
  21191. * Pass values to the playback tech
  21192. *
  21193. * @param {string} [method]
  21194. * the method to call
  21195. *
  21196. * @param {Object} arg
  21197. * the argument to pass
  21198. *
  21199. * @private
  21200. */
  21201. ;
  21202. _proto.techCall_ = function techCall_(method, arg) {
  21203. // If it's not ready yet, call method when it is
  21204. this.ready(function () {
  21205. if (method in allowedSetters) {
  21206. return set(this.middleware_, this.tech_, method, arg);
  21207. } else if (method in allowedMediators) {
  21208. return mediate(this.middleware_, this.tech_, method, arg);
  21209. }
  21210. try {
  21211. if (this.tech_) {
  21212. this.tech_[method](arg);
  21213. }
  21214. } catch (e) {
  21215. log$1(e);
  21216. throw e;
  21217. }
  21218. }, true);
  21219. }
  21220. /**
  21221. * Get calls can't wait for the tech, and sometimes don't need to.
  21222. *
  21223. * @param {string} method
  21224. * Tech method
  21225. *
  21226. * @return {Function|undefined}
  21227. * the method or undefined
  21228. *
  21229. * @private
  21230. */
  21231. ;
  21232. _proto.techGet_ = function techGet_(method) {
  21233. if (!this.tech_ || !this.tech_.isReady_) {
  21234. return;
  21235. }
  21236. if (method in allowedGetters) {
  21237. return get(this.middleware_, this.tech_, method);
  21238. } else if (method in allowedMediators) {
  21239. return mediate(this.middleware_, this.tech_, method);
  21240. } // Flash likes to die and reload when you hide or reposition it.
  21241. // In these cases the object methods go away and we get errors.
  21242. // TODO: Is this needed for techs other than Flash?
  21243. // When that happens we'll catch the errors and inform tech that it's not ready any more.
  21244. try {
  21245. return this.tech_[method]();
  21246. } catch (e) {
  21247. // When building additional tech libs, an expected method may not be defined yet
  21248. if (this.tech_[method] === undefined) {
  21249. log$1("Video.js: " + method + " method not defined for " + this.techName_ + " playback technology.", e);
  21250. throw e;
  21251. } // When a method isn't available on the object it throws a TypeError
  21252. if (e.name === 'TypeError') {
  21253. log$1("Video.js: " + method + " unavailable on " + this.techName_ + " playback technology element.", e);
  21254. this.tech_.isReady_ = false;
  21255. throw e;
  21256. } // If error unknown, just log and throw
  21257. log$1(e);
  21258. throw e;
  21259. }
  21260. }
  21261. /**
  21262. * Attempt to begin playback at the first opportunity.
  21263. *
  21264. * @return {Promise|undefined}
  21265. * Returns a promise if the browser supports Promises (or one
  21266. * was passed in as an option). This promise will be resolved on
  21267. * the return value of play. If this is undefined it will fulfill the
  21268. * promise chain otherwise the promise chain will be fulfilled when
  21269. * the promise from play is fulfilled.
  21270. */
  21271. ;
  21272. _proto.play = function play() {
  21273. var _this10 = this;
  21274. var PromiseClass = this.options_.Promise || window.Promise;
  21275. if (PromiseClass) {
  21276. return new PromiseClass(function (resolve) {
  21277. _this10.play_(resolve);
  21278. });
  21279. }
  21280. return this.play_();
  21281. }
  21282. /**
  21283. * The actual logic for play, takes a callback that will be resolved on the
  21284. * return value of play. This allows us to resolve to the play promise if there
  21285. * is one on modern browsers.
  21286. *
  21287. * @private
  21288. * @param {Function} [callback]
  21289. * The callback that should be called when the techs play is actually called
  21290. */
  21291. ;
  21292. _proto.play_ = function play_(callback) {
  21293. var _this11 = this;
  21294. if (callback === void 0) {
  21295. callback = silencePromise;
  21296. }
  21297. this.playCallbacks_.push(callback);
  21298. var isSrcReady = Boolean(!this.changingSrc_ && (this.src() || this.currentSrc()));
  21299. var isSafariOrIOS = Boolean(IS_ANY_SAFARI || IS_IOS); // treat calls to play_ somewhat like the `one` event function
  21300. if (this.waitToPlay_) {
  21301. this.off(['ready', 'loadstart'], this.waitToPlay_);
  21302. this.waitToPlay_ = null;
  21303. } // if the player/tech is not ready or the src itself is not ready
  21304. // queue up a call to play on `ready` or `loadstart`
  21305. if (!this.isReady_ || !isSrcReady) {
  21306. this.waitToPlay_ = function (e) {
  21307. _this11.play_();
  21308. };
  21309. this.one(['ready', 'loadstart'], this.waitToPlay_); // if we are in Safari, there is a high chance that loadstart will trigger after the gesture timeperiod
  21310. // in that case, we need to prime the video element by calling load so it'll be ready in time
  21311. if (!isSrcReady && isSafariOrIOS) {
  21312. this.load();
  21313. }
  21314. return;
  21315. } // If the player/tech is ready and we have a source, we can attempt playback.
  21316. var val = this.techGet_('play'); // For native playback, reset the progress bar if we get a play call from a replay.
  21317. var isNativeReplay = isSafariOrIOS && this.hasClass('vjs-ended');
  21318. if (isNativeReplay) {
  21319. this.resetProgressBar_();
  21320. } // play was terminated if the returned value is null
  21321. if (val === null) {
  21322. this.runPlayTerminatedQueue_();
  21323. } else {
  21324. this.runPlayCallbacks_(val);
  21325. }
  21326. }
  21327. /**
  21328. * These functions will be run when if play is terminated. If play
  21329. * runPlayCallbacks_ is run these function will not be run. This allows us
  21330. * to differenciate between a terminated play and an actual call to play.
  21331. */
  21332. ;
  21333. _proto.runPlayTerminatedQueue_ = function runPlayTerminatedQueue_() {
  21334. var queue = this.playTerminatedQueue_.slice(0);
  21335. this.playTerminatedQueue_ = [];
  21336. queue.forEach(function (q) {
  21337. q();
  21338. });
  21339. }
  21340. /**
  21341. * When a callback to play is delayed we have to run these
  21342. * callbacks when play is actually called on the tech. This function
  21343. * runs the callbacks that were delayed and accepts the return value
  21344. * from the tech.
  21345. *
  21346. * @param {undefined|Promise} val
  21347. * The return value from the tech.
  21348. */
  21349. ;
  21350. _proto.runPlayCallbacks_ = function runPlayCallbacks_(val) {
  21351. var callbacks = this.playCallbacks_.slice(0);
  21352. this.playCallbacks_ = []; // clear play terminatedQueue since we finished a real play
  21353. this.playTerminatedQueue_ = [];
  21354. callbacks.forEach(function (cb) {
  21355. cb(val);
  21356. });
  21357. }
  21358. /**
  21359. * Pause the video playback
  21360. *
  21361. * @return {Player}
  21362. * A reference to the player object this function was called on
  21363. */
  21364. ;
  21365. _proto.pause = function pause() {
  21366. this.techCall_('pause');
  21367. }
  21368. /**
  21369. * Check if the player is paused or has yet to play
  21370. *
  21371. * @return {boolean}
  21372. * - false: if the media is currently playing
  21373. * - true: if media is not currently playing
  21374. */
  21375. ;
  21376. _proto.paused = function paused() {
  21377. // The initial state of paused should be true (in Safari it's actually false)
  21378. return this.techGet_('paused') === false ? false : true;
  21379. }
  21380. /**
  21381. * Get a TimeRange object representing the current ranges of time that the user
  21382. * has played.
  21383. *
  21384. * @return {TimeRange}
  21385. * A time range object that represents all the increments of time that have
  21386. * been played.
  21387. */
  21388. ;
  21389. _proto.played = function played() {
  21390. return this.techGet_('played') || createTimeRanges(0, 0);
  21391. }
  21392. /**
  21393. * Returns whether or not the user is "scrubbing". Scrubbing is
  21394. * when the user has clicked the progress bar handle and is
  21395. * dragging it along the progress bar.
  21396. *
  21397. * @param {boolean} [isScrubbing]
  21398. * whether the user is or is not scrubbing
  21399. *
  21400. * @return {boolean}
  21401. * The value of scrubbing when getting
  21402. */
  21403. ;
  21404. _proto.scrubbing = function scrubbing(isScrubbing) {
  21405. if (typeof isScrubbing === 'undefined') {
  21406. return this.scrubbing_;
  21407. }
  21408. this.scrubbing_ = !!isScrubbing;
  21409. this.techCall_('setScrubbing', this.scrubbing_);
  21410. if (isScrubbing) {
  21411. this.addClass('vjs-scrubbing');
  21412. } else {
  21413. this.removeClass('vjs-scrubbing');
  21414. }
  21415. }
  21416. /**
  21417. * Get or set the current time (in seconds)
  21418. *
  21419. * @param {number|string} [seconds]
  21420. * The time to seek to in seconds
  21421. *
  21422. * @return {number}
  21423. * - the current time in seconds when getting
  21424. */
  21425. ;
  21426. _proto.currentTime = function currentTime(seconds) {
  21427. if (typeof seconds !== 'undefined') {
  21428. if (seconds < 0) {
  21429. seconds = 0;
  21430. }
  21431. if (!this.isReady_ || this.changingSrc_ || !this.tech_ || !this.tech_.isReady_) {
  21432. this.cache_.initTime = seconds;
  21433. this.off('canplay', this.boundApplyInitTime_);
  21434. this.one('canplay', this.boundApplyInitTime_);
  21435. return;
  21436. }
  21437. this.techCall_('setCurrentTime', seconds);
  21438. this.cache_.initTime = 0;
  21439. return;
  21440. } // cache last currentTime and return. default to 0 seconds
  21441. //
  21442. // Caching the currentTime is meant to prevent a massive amount of reads on the tech's
  21443. // currentTime when scrubbing, but may not provide much performance benefit afterall.
  21444. // Should be tested. Also something has to read the actual current time or the cache will
  21445. // never get updated.
  21446. this.cache_.currentTime = this.techGet_('currentTime') || 0;
  21447. return this.cache_.currentTime;
  21448. }
  21449. /**
  21450. * Apply the value of initTime stored in cache as currentTime.
  21451. *
  21452. * @private
  21453. */
  21454. ;
  21455. _proto.applyInitTime_ = function applyInitTime_() {
  21456. this.currentTime(this.cache_.initTime);
  21457. }
  21458. /**
  21459. * Normally gets the length in time of the video in seconds;
  21460. * in all but the rarest use cases an argument will NOT be passed to the method
  21461. *
  21462. * > **NOTE**: The video must have started loading before the duration can be
  21463. * known, and depending on preload behaviour may not be known until the video starts
  21464. * playing.
  21465. *
  21466. * @fires Player#durationchange
  21467. *
  21468. * @param {number} [seconds]
  21469. * The duration of the video to set in seconds
  21470. *
  21471. * @return {number}
  21472. * - The duration of the video in seconds when getting
  21473. */
  21474. ;
  21475. _proto.duration = function duration(seconds) {
  21476. if (seconds === undefined) {
  21477. // return NaN if the duration is not known
  21478. return this.cache_.duration !== undefined ? this.cache_.duration : NaN;
  21479. }
  21480. seconds = parseFloat(seconds); // Standardize on Infinity for signaling video is live
  21481. if (seconds < 0) {
  21482. seconds = Infinity;
  21483. }
  21484. if (seconds !== this.cache_.duration) {
  21485. // Cache the last set value for optimized scrubbing (esp. Flash)
  21486. // TODO: Required for techs other than Flash?
  21487. this.cache_.duration = seconds;
  21488. if (seconds === Infinity) {
  21489. this.addClass('vjs-live');
  21490. } else {
  21491. this.removeClass('vjs-live');
  21492. }
  21493. if (!isNaN(seconds)) {
  21494. // Do not fire durationchange unless the duration value is known.
  21495. // @see [Spec]{@link https://www.w3.org/TR/2011/WD-html5-20110113/video.html#media-element-load-algorithm}
  21496. /**
  21497. * @event Player#durationchange
  21498. * @type {EventTarget~Event}
  21499. */
  21500. this.trigger('durationchange');
  21501. }
  21502. }
  21503. }
  21504. /**
  21505. * Calculates how much time is left in the video. Not part
  21506. * of the native video API.
  21507. *
  21508. * @return {number}
  21509. * The time remaining in seconds
  21510. */
  21511. ;
  21512. _proto.remainingTime = function remainingTime() {
  21513. return this.duration() - this.currentTime();
  21514. }
  21515. /**
  21516. * A remaining time function that is intented to be used when
  21517. * the time is to be displayed directly to the user.
  21518. *
  21519. * @return {number}
  21520. * The rounded time remaining in seconds
  21521. */
  21522. ;
  21523. _proto.remainingTimeDisplay = function remainingTimeDisplay() {
  21524. return Math.floor(this.duration()) - Math.floor(this.currentTime());
  21525. } //
  21526. // Kind of like an array of portions of the video that have been downloaded.
  21527. /**
  21528. * Get a TimeRange object with an array of the times of the video
  21529. * that have been downloaded. If you just want the percent of the
  21530. * video that's been downloaded, use bufferedPercent.
  21531. *
  21532. * @see [Buffered Spec]{@link http://dev.w3.org/html5/spec/video.html#dom-media-buffered}
  21533. *
  21534. * @return {TimeRange}
  21535. * A mock TimeRange object (following HTML spec)
  21536. */
  21537. ;
  21538. _proto.buffered = function buffered() {
  21539. var buffered = this.techGet_('buffered');
  21540. if (!buffered || !buffered.length) {
  21541. buffered = createTimeRanges(0, 0);
  21542. }
  21543. return buffered;
  21544. }
  21545. /**
  21546. * Get the percent (as a decimal) of the video that's been downloaded.
  21547. * This method is not a part of the native HTML video API.
  21548. *
  21549. * @return {number}
  21550. * A decimal between 0 and 1 representing the percent
  21551. * that is buffered 0 being 0% and 1 being 100%
  21552. */
  21553. ;
  21554. _proto.bufferedPercent = function bufferedPercent$1() {
  21555. return bufferedPercent(this.buffered(), this.duration());
  21556. }
  21557. /**
  21558. * Get the ending time of the last buffered time range
  21559. * This is used in the progress bar to encapsulate all time ranges.
  21560. *
  21561. * @return {number}
  21562. * The end of the last buffered time range
  21563. */
  21564. ;
  21565. _proto.bufferedEnd = function bufferedEnd() {
  21566. var buffered = this.buffered();
  21567. var duration = this.duration();
  21568. var end = buffered.end(buffered.length - 1);
  21569. if (end > duration) {
  21570. end = duration;
  21571. }
  21572. return end;
  21573. }
  21574. /**
  21575. * Get or set the current volume of the media
  21576. *
  21577. * @param {number} [percentAsDecimal]
  21578. * The new volume as a decimal percent:
  21579. * - 0 is muted/0%/off
  21580. * - 1.0 is 100%/full
  21581. * - 0.5 is half volume or 50%
  21582. *
  21583. * @return {number}
  21584. * The current volume as a percent when getting
  21585. */
  21586. ;
  21587. _proto.volume = function volume(percentAsDecimal) {
  21588. var vol;
  21589. if (percentAsDecimal !== undefined) {
  21590. // Force value to between 0 and 1
  21591. vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal)));
  21592. this.cache_.volume = vol;
  21593. this.techCall_('setVolume', vol);
  21594. if (vol > 0) {
  21595. this.lastVolume_(vol);
  21596. }
  21597. return;
  21598. } // Default to 1 when returning current volume.
  21599. vol = parseFloat(this.techGet_('volume'));
  21600. return isNaN(vol) ? 1 : vol;
  21601. }
  21602. /**
  21603. * Get the current muted state, or turn mute on or off
  21604. *
  21605. * @param {boolean} [muted]
  21606. * - true to mute
  21607. * - false to unmute
  21608. *
  21609. * @return {boolean}
  21610. * - true if mute is on and getting
  21611. * - false if mute is off and getting
  21612. */
  21613. ;
  21614. _proto.muted = function muted(_muted) {
  21615. if (_muted !== undefined) {
  21616. this.techCall_('setMuted', _muted);
  21617. return;
  21618. }
  21619. return this.techGet_('muted') || false;
  21620. }
  21621. /**
  21622. * Get the current defaultMuted state, or turn defaultMuted on or off. defaultMuted
  21623. * indicates the state of muted on initial playback.
  21624. *
  21625. * ```js
  21626. * var myPlayer = videojs('some-player-id');
  21627. *
  21628. * myPlayer.src("http://www.example.com/path/to/video.mp4");
  21629. *
  21630. * // get, should be false
  21631. * console.log(myPlayer.defaultMuted());
  21632. * // set to true
  21633. * myPlayer.defaultMuted(true);
  21634. * // get should be true
  21635. * console.log(myPlayer.defaultMuted());
  21636. * ```
  21637. *
  21638. * @param {boolean} [defaultMuted]
  21639. * - true to mute
  21640. * - false to unmute
  21641. *
  21642. * @return {boolean|Player}
  21643. * - true if defaultMuted is on and getting
  21644. * - false if defaultMuted is off and getting
  21645. * - A reference to the current player when setting
  21646. */
  21647. ;
  21648. _proto.defaultMuted = function defaultMuted(_defaultMuted) {
  21649. if (_defaultMuted !== undefined) {
  21650. return this.techCall_('setDefaultMuted', _defaultMuted);
  21651. }
  21652. return this.techGet_('defaultMuted') || false;
  21653. }
  21654. /**
  21655. * Get the last volume, or set it
  21656. *
  21657. * @param {number} [percentAsDecimal]
  21658. * The new last volume as a decimal percent:
  21659. * - 0 is muted/0%/off
  21660. * - 1.0 is 100%/full
  21661. * - 0.5 is half volume or 50%
  21662. *
  21663. * @return {number}
  21664. * the current value of lastVolume as a percent when getting
  21665. *
  21666. * @private
  21667. */
  21668. ;
  21669. _proto.lastVolume_ = function lastVolume_(percentAsDecimal) {
  21670. if (percentAsDecimal !== undefined && percentAsDecimal !== 0) {
  21671. this.cache_.lastVolume = percentAsDecimal;
  21672. return;
  21673. }
  21674. return this.cache_.lastVolume;
  21675. }
  21676. /**
  21677. * Check if current tech can support native fullscreen
  21678. * (e.g. with built in controls like iOS)
  21679. *
  21680. * @return {boolean}
  21681. * if native fullscreen is supported
  21682. */
  21683. ;
  21684. _proto.supportsFullScreen = function supportsFullScreen() {
  21685. return this.techGet_('supportsFullScreen') || false;
  21686. }
  21687. /**
  21688. * Check if the player is in fullscreen mode or tell the player that it
  21689. * is or is not in fullscreen mode.
  21690. *
  21691. * > NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official
  21692. * property and instead document.fullscreenElement is used. But isFullscreen is
  21693. * still a valuable property for internal player workings.
  21694. *
  21695. * @param {boolean} [isFS]
  21696. * Set the players current fullscreen state
  21697. *
  21698. * @return {boolean}
  21699. * - true if fullscreen is on and getting
  21700. * - false if fullscreen is off and getting
  21701. */
  21702. ;
  21703. _proto.isFullscreen = function isFullscreen(isFS) {
  21704. if (isFS !== undefined) {
  21705. var oldValue = this.isFullscreen_;
  21706. this.isFullscreen_ = Boolean(isFS); // if we changed fullscreen state and we're in prefixed mode, trigger fullscreenchange
  21707. // this is the only place where we trigger fullscreenchange events for older browsers
  21708. // fullWindow mode is treated as a prefixed event and will get a fullscreenchange event as well
  21709. if (this.isFullscreen_ !== oldValue && this.fsApi_.prefixed) {
  21710. /**
  21711. * @event Player#fullscreenchange
  21712. * @type {EventTarget~Event}
  21713. */
  21714. this.trigger('fullscreenchange');
  21715. }
  21716. this.toggleFullscreenClass_();
  21717. return;
  21718. }
  21719. return this.isFullscreen_;
  21720. }
  21721. /**
  21722. * Increase the size of the video to full screen
  21723. * In some browsers, full screen is not supported natively, so it enters
  21724. * "full window mode", where the video fills the browser window.
  21725. * In browsers and devices that support native full screen, sometimes the
  21726. * browser's default controls will be shown, and not the Video.js custom skin.
  21727. * This includes most mobile devices (iOS, Android) and older versions of
  21728. * Safari.
  21729. *
  21730. * @param {Object} [fullscreenOptions]
  21731. * Override the player fullscreen options
  21732. *
  21733. * @fires Player#fullscreenchange
  21734. */
  21735. ;
  21736. _proto.requestFullscreen = function requestFullscreen(fullscreenOptions) {
  21737. var PromiseClass = this.options_.Promise || window.Promise;
  21738. if (PromiseClass) {
  21739. var self = this;
  21740. return new PromiseClass(function (resolve, reject) {
  21741. function offHandler() {
  21742. self.off('fullscreenerror', errorHandler);
  21743. self.off('fullscreenchange', changeHandler);
  21744. }
  21745. function changeHandler() {
  21746. offHandler();
  21747. resolve();
  21748. }
  21749. function errorHandler(e, err) {
  21750. offHandler();
  21751. reject(err);
  21752. }
  21753. self.one('fullscreenchange', changeHandler);
  21754. self.one('fullscreenerror', errorHandler);
  21755. var promise = self.requestFullscreenHelper_(fullscreenOptions);
  21756. if (promise) {
  21757. promise.then(offHandler, offHandler);
  21758. promise.then(resolve, reject);
  21759. }
  21760. });
  21761. }
  21762. return this.requestFullscreenHelper_();
  21763. };
  21764. _proto.requestFullscreenHelper_ = function requestFullscreenHelper_(fullscreenOptions) {
  21765. var _this12 = this;
  21766. var fsOptions; // Only pass fullscreen options to requestFullscreen in spec-compliant browsers.
  21767. // Use defaults or player configured option unless passed directly to this method.
  21768. if (!this.fsApi_.prefixed) {
  21769. fsOptions = this.options_.fullscreen && this.options_.fullscreen.options || {};
  21770. if (fullscreenOptions !== undefined) {
  21771. fsOptions = fullscreenOptions;
  21772. }
  21773. } // This method works as follows:
  21774. // 1. if a fullscreen api is available, use it
  21775. // 1. call requestFullscreen with potential options
  21776. // 2. if we got a promise from above, use it to update isFullscreen()
  21777. // 2. otherwise, if the tech supports fullscreen, call `enterFullScreen` on it.
  21778. // This is particularly used for iPhone, older iPads, and non-safari browser on iOS.
  21779. // 3. otherwise, use "fullWindow" mode
  21780. if (this.fsApi_.requestFullscreen) {
  21781. var promise = this.el_[this.fsApi_.requestFullscreen](fsOptions);
  21782. if (promise) {
  21783. promise.then(function () {
  21784. return _this12.isFullscreen(true);
  21785. }, function () {
  21786. return _this12.isFullscreen(false);
  21787. });
  21788. }
  21789. return promise;
  21790. } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
  21791. // we can't take the video.js controls fullscreen but we can go fullscreen
  21792. // with native controls
  21793. this.techCall_('enterFullScreen');
  21794. } else {
  21795. // fullscreen isn't supported so we'll just stretch the video element to
  21796. // fill the viewport
  21797. this.enterFullWindow();
  21798. }
  21799. }
  21800. /**
  21801. * Return the video to its normal size after having been in full screen mode
  21802. *
  21803. * @fires Player#fullscreenchange
  21804. */
  21805. ;
  21806. _proto.exitFullscreen = function exitFullscreen() {
  21807. var PromiseClass = this.options_.Promise || window.Promise;
  21808. if (PromiseClass) {
  21809. var self = this;
  21810. return new PromiseClass(function (resolve, reject) {
  21811. function offHandler() {
  21812. self.off('fullscreenerror', errorHandler);
  21813. self.off('fullscreenchange', changeHandler);
  21814. }
  21815. function changeHandler() {
  21816. offHandler();
  21817. resolve();
  21818. }
  21819. function errorHandler(e, err) {
  21820. offHandler();
  21821. reject(err);
  21822. }
  21823. self.one('fullscreenchange', changeHandler);
  21824. self.one('fullscreenerror', errorHandler);
  21825. var promise = self.exitFullscreenHelper_();
  21826. if (promise) {
  21827. promise.then(offHandler, offHandler); // map the promise to our resolve/reject methods
  21828. promise.then(resolve, reject);
  21829. }
  21830. });
  21831. }
  21832. return this.exitFullscreenHelper_();
  21833. };
  21834. _proto.exitFullscreenHelper_ = function exitFullscreenHelper_() {
  21835. var _this13 = this;
  21836. if (this.fsApi_.requestFullscreen) {
  21837. var promise = document[this.fsApi_.exitFullscreen]();
  21838. if (promise) {
  21839. // we're splitting the promise here, so, we want to catch the
  21840. // potential error so that this chain doesn't have unhandled errors
  21841. silencePromise(promise.then(function () {
  21842. return _this13.isFullscreen(false);
  21843. }));
  21844. }
  21845. return promise;
  21846. } else if (this.tech_.supportsFullScreen() && !this.options_.preferFullWindow === true) {
  21847. this.techCall_('exitFullScreen');
  21848. } else {
  21849. this.exitFullWindow();
  21850. }
  21851. }
  21852. /**
  21853. * When fullscreen isn't supported we can stretch the
  21854. * video container to as wide as the browser will let us.
  21855. *
  21856. * @fires Player#enterFullWindow
  21857. */
  21858. ;
  21859. _proto.enterFullWindow = function enterFullWindow() {
  21860. this.isFullscreen(true);
  21861. this.isFullWindow = true; // Storing original doc overflow value to return to when fullscreen is off
  21862. this.docOrigOverflow = document.documentElement.style.overflow; // Add listener for esc key to exit fullscreen
  21863. on(document, 'keydown', this.boundFullWindowOnEscKey_); // Hide any scroll bars
  21864. document.documentElement.style.overflow = 'hidden'; // Apply fullscreen styles
  21865. addClass(document.body, 'vjs-full-window');
  21866. /**
  21867. * @event Player#enterFullWindow
  21868. * @type {EventTarget~Event}
  21869. */
  21870. this.trigger('enterFullWindow');
  21871. }
  21872. /**
  21873. * Check for call to either exit full window or
  21874. * full screen on ESC key
  21875. *
  21876. * @param {string} event
  21877. * Event to check for key press
  21878. */
  21879. ;
  21880. _proto.fullWindowOnEscKey = function fullWindowOnEscKey(event) {
  21881. if (keycode.isEventKey(event, 'Esc')) {
  21882. if (this.isFullscreen() === true) {
  21883. if (!this.isFullWindow) {
  21884. this.exitFullscreen();
  21885. } else {
  21886. this.exitFullWindow();
  21887. }
  21888. }
  21889. }
  21890. }
  21891. /**
  21892. * Exit full window
  21893. *
  21894. * @fires Player#exitFullWindow
  21895. */
  21896. ;
  21897. _proto.exitFullWindow = function exitFullWindow() {
  21898. this.isFullscreen(false);
  21899. this.isFullWindow = false;
  21900. off(document, 'keydown', this.boundFullWindowOnEscKey_); // Unhide scroll bars.
  21901. document.documentElement.style.overflow = this.docOrigOverflow; // Remove fullscreen styles
  21902. removeClass(document.body, 'vjs-full-window'); // Resize the box, controller, and poster to original sizes
  21903. // this.positionAll();
  21904. /**
  21905. * @event Player#exitFullWindow
  21906. * @type {EventTarget~Event}
  21907. */
  21908. this.trigger('exitFullWindow');
  21909. }
  21910. /**
  21911. * Disable Picture-in-Picture mode.
  21912. *
  21913. * @param {boolean} value
  21914. * - true will disable Picture-in-Picture mode
  21915. * - false will enable Picture-in-Picture mode
  21916. */
  21917. ;
  21918. _proto.disablePictureInPicture = function disablePictureInPicture(value) {
  21919. if (value === undefined) {
  21920. return this.techGet_('disablePictureInPicture');
  21921. }
  21922. this.techCall_('setDisablePictureInPicture', value);
  21923. this.options_.disablePictureInPicture = value;
  21924. this.trigger('disablepictureinpicturechanged');
  21925. }
  21926. /**
  21927. * Check if the player is in Picture-in-Picture mode or tell the player that it
  21928. * is or is not in Picture-in-Picture mode.
  21929. *
  21930. * @param {boolean} [isPiP]
  21931. * Set the players current Picture-in-Picture state
  21932. *
  21933. * @return {boolean}
  21934. * - true if Picture-in-Picture is on and getting
  21935. * - false if Picture-in-Picture is off and getting
  21936. */
  21937. ;
  21938. _proto.isInPictureInPicture = function isInPictureInPicture(isPiP) {
  21939. if (isPiP !== undefined) {
  21940. this.isInPictureInPicture_ = !!isPiP;
  21941. this.togglePictureInPictureClass_();
  21942. return;
  21943. }
  21944. return !!this.isInPictureInPicture_;
  21945. }
  21946. /**
  21947. * Create a floating video window always on top of other windows so that users may
  21948. * continue consuming media while they interact with other content sites, or
  21949. * applications on their device.
  21950. *
  21951. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  21952. *
  21953. * @fires Player#enterpictureinpicture
  21954. *
  21955. * @return {Promise}
  21956. * A promise with a Picture-in-Picture window.
  21957. */
  21958. ;
  21959. _proto.requestPictureInPicture = function requestPictureInPicture() {
  21960. if ('pictureInPictureEnabled' in document && this.disablePictureInPicture() === false) {
  21961. /**
  21962. * This event fires when the player enters picture in picture mode
  21963. *
  21964. * @event Player#enterpictureinpicture
  21965. * @type {EventTarget~Event}
  21966. */
  21967. return this.techGet_('requestPictureInPicture');
  21968. }
  21969. }
  21970. /**
  21971. * Exit Picture-in-Picture mode.
  21972. *
  21973. * @see [Spec]{@link https://wicg.github.io/picture-in-picture}
  21974. *
  21975. * @fires Player#leavepictureinpicture
  21976. *
  21977. * @return {Promise}
  21978. * A promise.
  21979. */
  21980. ;
  21981. _proto.exitPictureInPicture = function exitPictureInPicture() {
  21982. if ('pictureInPictureEnabled' in document) {
  21983. /**
  21984. * This event fires when the player leaves picture in picture mode
  21985. *
  21986. * @event Player#leavepictureinpicture
  21987. * @type {EventTarget~Event}
  21988. */
  21989. return document.exitPictureInPicture();
  21990. }
  21991. }
  21992. /**
  21993. * Called when this Player has focus and a key gets pressed down, or when
  21994. * any Component of this player receives a key press that it doesn't handle.
  21995. * This allows player-wide hotkeys (either as defined below, or optionally
  21996. * by an external function).
  21997. *
  21998. * @param {EventTarget~Event} event
  21999. * The `keydown` event that caused this function to be called.
  22000. *
  22001. * @listens keydown
  22002. */
  22003. ;
  22004. _proto.handleKeyDown = function handleKeyDown(event) {
  22005. var userActions = this.options_.userActions; // Bail out if hotkeys are not configured.
  22006. if (!userActions || !userActions.hotkeys) {
  22007. return;
  22008. } // Function that determines whether or not to exclude an element from
  22009. // hotkeys handling.
  22010. var excludeElement = function excludeElement(el) {
  22011. var tagName = el.tagName.toLowerCase(); // The first and easiest test is for `contenteditable` elements.
  22012. if (el.isContentEditable) {
  22013. return true;
  22014. } // Inputs matching these types will still trigger hotkey handling as
  22015. // they are not text inputs.
  22016. var allowedInputTypes = ['button', 'checkbox', 'hidden', 'radio', 'reset', 'submit'];
  22017. if (tagName === 'input') {
  22018. return allowedInputTypes.indexOf(el.type) === -1;
  22019. } // The final test is by tag name. These tags will be excluded entirely.
  22020. var excludedTags = ['textarea'];
  22021. return excludedTags.indexOf(tagName) !== -1;
  22022. }; // Bail out if the user is focused on an interactive form element.
  22023. if (excludeElement(this.el_.ownerDocument.activeElement)) {
  22024. return;
  22025. }
  22026. if (typeof userActions.hotkeys === 'function') {
  22027. userActions.hotkeys.call(this, event);
  22028. } else {
  22029. this.handleHotkeys(event);
  22030. }
  22031. }
  22032. /**
  22033. * Called when this Player receives a hotkey keydown event.
  22034. * Supported player-wide hotkeys are:
  22035. *
  22036. * f - toggle fullscreen
  22037. * m - toggle mute
  22038. * k or Space - toggle play/pause
  22039. *
  22040. * @param {EventTarget~Event} event
  22041. * The `keydown` event that caused this function to be called.
  22042. */
  22043. ;
  22044. _proto.handleHotkeys = function handleHotkeys(event) {
  22045. var hotkeys = this.options_.userActions ? this.options_.userActions.hotkeys : {}; // set fullscreenKey, muteKey, playPauseKey from `hotkeys`, use defaults if not set
  22046. var _hotkeys$fullscreenKe = hotkeys.fullscreenKey,
  22047. fullscreenKey = _hotkeys$fullscreenKe === void 0 ? function (keydownEvent) {
  22048. return keycode.isEventKey(keydownEvent, 'f');
  22049. } : _hotkeys$fullscreenKe,
  22050. _hotkeys$muteKey = hotkeys.muteKey,
  22051. muteKey = _hotkeys$muteKey === void 0 ? function (keydownEvent) {
  22052. return keycode.isEventKey(keydownEvent, 'm');
  22053. } : _hotkeys$muteKey,
  22054. _hotkeys$playPauseKey = hotkeys.playPauseKey,
  22055. playPauseKey = _hotkeys$playPauseKey === void 0 ? function (keydownEvent) {
  22056. return keycode.isEventKey(keydownEvent, 'k') || keycode.isEventKey(keydownEvent, 'Space');
  22057. } : _hotkeys$playPauseKey;
  22058. if (fullscreenKey.call(this, event)) {
  22059. event.preventDefault();
  22060. event.stopPropagation();
  22061. var FSToggle = Component$1.getComponent('FullscreenToggle');
  22062. if (document[this.fsApi_.fullscreenEnabled] !== false) {
  22063. FSToggle.prototype.handleClick.call(this, event);
  22064. }
  22065. } else if (muteKey.call(this, event)) {
  22066. event.preventDefault();
  22067. event.stopPropagation();
  22068. var MuteToggle = Component$1.getComponent('MuteToggle');
  22069. MuteToggle.prototype.handleClick.call(this, event);
  22070. } else if (playPauseKey.call(this, event)) {
  22071. event.preventDefault();
  22072. event.stopPropagation();
  22073. var PlayToggle = Component$1.getComponent('PlayToggle');
  22074. PlayToggle.prototype.handleClick.call(this, event);
  22075. }
  22076. }
  22077. /**
  22078. * Check whether the player can play a given mimetype
  22079. *
  22080. * @see https://www.w3.org/TR/2011/WD-html5-20110113/video.html#dom-navigator-canplaytype
  22081. *
  22082. * @param {string} type
  22083. * The mimetype to check
  22084. *
  22085. * @return {string}
  22086. * 'probably', 'maybe', or '' (empty string)
  22087. */
  22088. ;
  22089. _proto.canPlayType = function canPlayType(type) {
  22090. var can; // Loop through each playback technology in the options order
  22091. for (var i = 0, j = this.options_.techOrder; i < j.length; i++) {
  22092. var techName = j[i];
  22093. var tech = Tech.getTech(techName); // Support old behavior of techs being registered as components.
  22094. // Remove once that deprecated behavior is removed.
  22095. if (!tech) {
  22096. tech = Component$1.getComponent(techName);
  22097. } // Check if the current tech is defined before continuing
  22098. if (!tech) {
  22099. log$1.error("The \"" + techName + "\" tech is undefined. Skipped browser support check for that tech.");
  22100. continue;
  22101. } // Check if the browser supports this technology
  22102. if (tech.isSupported()) {
  22103. can = tech.canPlayType(type);
  22104. if (can) {
  22105. return can;
  22106. }
  22107. }
  22108. }
  22109. return '';
  22110. }
  22111. /**
  22112. * Select source based on tech-order or source-order
  22113. * Uses source-order selection if `options.sourceOrder` is truthy. Otherwise,
  22114. * defaults to tech-order selection
  22115. *
  22116. * @param {Array} sources
  22117. * The sources for a media asset
  22118. *
  22119. * @return {Object|boolean}
  22120. * Object of source and tech order or false
  22121. */
  22122. ;
  22123. _proto.selectSource = function selectSource(sources) {
  22124. var _this14 = this;
  22125. // Get only the techs specified in `techOrder` that exist and are supported by the
  22126. // current platform
  22127. var techs = this.options_.techOrder.map(function (techName) {
  22128. return [techName, Tech.getTech(techName)];
  22129. }).filter(function (_ref) {
  22130. var techName = _ref[0],
  22131. tech = _ref[1];
  22132. // Check if the current tech is defined before continuing
  22133. if (tech) {
  22134. // Check if the browser supports this technology
  22135. return tech.isSupported();
  22136. }
  22137. log$1.error("The \"" + techName + "\" tech is undefined. Skipped browser support check for that tech.");
  22138. return false;
  22139. }); // Iterate over each `innerArray` element once per `outerArray` element and execute
  22140. // `tester` with both. If `tester` returns a non-falsy value, exit early and return
  22141. // that value.
  22142. var findFirstPassingTechSourcePair = function findFirstPassingTechSourcePair(outerArray, innerArray, tester) {
  22143. var found;
  22144. outerArray.some(function (outerChoice) {
  22145. return innerArray.some(function (innerChoice) {
  22146. found = tester(outerChoice, innerChoice);
  22147. if (found) {
  22148. return true;
  22149. }
  22150. });
  22151. });
  22152. return found;
  22153. };
  22154. var foundSourceAndTech;
  22155. var flip = function flip(fn) {
  22156. return function (a, b) {
  22157. return fn(b, a);
  22158. };
  22159. };
  22160. var finder = function finder(_ref2, source) {
  22161. var techName = _ref2[0],
  22162. tech = _ref2[1];
  22163. if (tech.canPlaySource(source, _this14.options_[techName.toLowerCase()])) {
  22164. return {
  22165. source: source,
  22166. tech: techName
  22167. };
  22168. }
  22169. }; // Depending on the truthiness of `options.sourceOrder`, we swap the order of techs and sources
  22170. // to select from them based on their priority.
  22171. if (this.options_.sourceOrder) {
  22172. // Source-first ordering
  22173. foundSourceAndTech = findFirstPassingTechSourcePair(sources, techs, flip(finder));
  22174. } else {
  22175. // Tech-first ordering
  22176. foundSourceAndTech = findFirstPassingTechSourcePair(techs, sources, finder);
  22177. }
  22178. return foundSourceAndTech || false;
  22179. }
  22180. /**
  22181. * Executes source setting and getting logic
  22182. *
  22183. * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
  22184. * A SourceObject, an array of SourceObjects, or a string referencing
  22185. * a URL to a media source. It is _highly recommended_ that an object
  22186. * or array of objects is used here, so that source selection
  22187. * algorithms can take the `type` into account.
  22188. *
  22189. * If not provided, this method acts as a getter.
  22190. * @param {boolean} isRetry
  22191. * Indicates whether this is being called internally as a result of a retry
  22192. *
  22193. * @return {string|undefined}
  22194. * If the `source` argument is missing, returns the current source
  22195. * URL. Otherwise, returns nothing/undefined.
  22196. */
  22197. ;
  22198. _proto.handleSrc_ = function handleSrc_(source, isRetry) {
  22199. var _this15 = this;
  22200. // getter usage
  22201. if (typeof source === 'undefined') {
  22202. return this.cache_.src || '';
  22203. } // Reset retry behavior for new source
  22204. if (this.resetRetryOnError_) {
  22205. this.resetRetryOnError_();
  22206. } // filter out invalid sources and turn our source into
  22207. // an array of source objects
  22208. var sources = filterSource(source); // if a source was passed in then it is invalid because
  22209. // it was filtered to a zero length Array. So we have to
  22210. // show an error
  22211. if (!sources.length) {
  22212. this.setTimeout(function () {
  22213. this.error({
  22214. code: 4,
  22215. message: this.options_.notSupportedMessage
  22216. });
  22217. }, 0);
  22218. return;
  22219. } // initial sources
  22220. this.changingSrc_ = true; // Only update the cached source list if we are not retrying a new source after error,
  22221. // since in that case we want to include the failed source(s) in the cache
  22222. if (!isRetry) {
  22223. this.cache_.sources = sources;
  22224. }
  22225. this.updateSourceCaches_(sources[0]); // middlewareSource is the source after it has been changed by middleware
  22226. setSource(this, sources[0], function (middlewareSource, mws) {
  22227. _this15.middleware_ = mws; // since sourceSet is async we have to update the cache again after we select a source since
  22228. // the source that is selected could be out of order from the cache update above this callback.
  22229. if (!isRetry) {
  22230. _this15.cache_.sources = sources;
  22231. }
  22232. _this15.updateSourceCaches_(middlewareSource);
  22233. var err = _this15.src_(middlewareSource);
  22234. if (err) {
  22235. if (sources.length > 1) {
  22236. return _this15.handleSrc_(sources.slice(1));
  22237. }
  22238. _this15.changingSrc_ = false; // We need to wrap this in a timeout to give folks a chance to add error event handlers
  22239. _this15.setTimeout(function () {
  22240. this.error({
  22241. code: 4,
  22242. message: this.options_.notSupportedMessage
  22243. });
  22244. }, 0); // we could not find an appropriate tech, but let's still notify the delegate that this is it
  22245. // this needs a better comment about why this is needed
  22246. _this15.triggerReady();
  22247. return;
  22248. }
  22249. setTech(mws, _this15.tech_);
  22250. }); // Try another available source if this one fails before playback.
  22251. if (this.options_.retryOnError && sources.length > 1) {
  22252. var retry = function retry() {
  22253. // Remove the error modal
  22254. _this15.error(null);
  22255. _this15.handleSrc_(sources.slice(1), true);
  22256. };
  22257. var stopListeningForErrors = function stopListeningForErrors() {
  22258. _this15.off('error', retry);
  22259. };
  22260. this.one('error', retry);
  22261. this.one('playing', stopListeningForErrors);
  22262. this.resetRetryOnError_ = function () {
  22263. _this15.off('error', retry);
  22264. _this15.off('playing', stopListeningForErrors);
  22265. };
  22266. }
  22267. }
  22268. /**
  22269. * Get or set the video source.
  22270. *
  22271. * @param {Tech~SourceObject|Tech~SourceObject[]|string} [source]
  22272. * A SourceObject, an array of SourceObjects, or a string referencing
  22273. * a URL to a media source. It is _highly recommended_ that an object
  22274. * or array of objects is used here, so that source selection
  22275. * algorithms can take the `type` into account.
  22276. *
  22277. * If not provided, this method acts as a getter.
  22278. *
  22279. * @return {string|undefined}
  22280. * If the `source` argument is missing, returns the current source
  22281. * URL. Otherwise, returns nothing/undefined.
  22282. */
  22283. ;
  22284. _proto.src = function src(source) {
  22285. return this.handleSrc_(source, false);
  22286. }
  22287. /**
  22288. * Set the source object on the tech, returns a boolean that indicates whether
  22289. * there is a tech that can play the source or not
  22290. *
  22291. * @param {Tech~SourceObject} source
  22292. * The source object to set on the Tech
  22293. *
  22294. * @return {boolean}
  22295. * - True if there is no Tech to playback this source
  22296. * - False otherwise
  22297. *
  22298. * @private
  22299. */
  22300. ;
  22301. _proto.src_ = function src_(source) {
  22302. var _this16 = this;
  22303. var sourceTech = this.selectSource([source]);
  22304. if (!sourceTech) {
  22305. return true;
  22306. }
  22307. if (!titleCaseEquals(sourceTech.tech, this.techName_)) {
  22308. this.changingSrc_ = true; // load this technology with the chosen source
  22309. this.loadTech_(sourceTech.tech, sourceTech.source);
  22310. this.tech_.ready(function () {
  22311. _this16.changingSrc_ = false;
  22312. });
  22313. return false;
  22314. } // wait until the tech is ready to set the source
  22315. // and set it synchronously if possible (#2326)
  22316. this.ready(function () {
  22317. // The setSource tech method was added with source handlers
  22318. // so older techs won't support it
  22319. // We need to check the direct prototype for the case where subclasses
  22320. // of the tech do not support source handlers
  22321. if (this.tech_.constructor.prototype.hasOwnProperty('setSource')) {
  22322. this.techCall_('setSource', source);
  22323. } else {
  22324. this.techCall_('src', source.src);
  22325. }
  22326. this.changingSrc_ = false;
  22327. }, true);
  22328. return false;
  22329. }
  22330. /**
  22331. * Begin loading the src data.
  22332. */
  22333. ;
  22334. _proto.load = function load() {
  22335. this.techCall_('load');
  22336. }
  22337. /**
  22338. * Reset the player. Loads the first tech in the techOrder,
  22339. * removes all the text tracks in the existing `tech`,
  22340. * and calls `reset` on the `tech`.
  22341. */
  22342. ;
  22343. _proto.reset = function reset() {
  22344. var _this17 = this;
  22345. var PromiseClass = this.options_.Promise || window.Promise;
  22346. if (this.paused() || !PromiseClass) {
  22347. this.doReset_();
  22348. } else {
  22349. var playPromise = this.play();
  22350. silencePromise(playPromise.then(function () {
  22351. return _this17.doReset_();
  22352. }));
  22353. }
  22354. };
  22355. _proto.doReset_ = function doReset_() {
  22356. if (this.tech_) {
  22357. this.tech_.clearTracks('text');
  22358. }
  22359. this.resetCache_();
  22360. this.poster('');
  22361. this.loadTech_(this.options_.techOrder[0], null);
  22362. this.techCall_('reset');
  22363. this.resetControlBarUI_();
  22364. if (isEvented(this)) {
  22365. this.trigger('playerreset');
  22366. }
  22367. }
  22368. /**
  22369. * Reset Control Bar's UI by calling sub-methods that reset
  22370. * all of Control Bar's components
  22371. */
  22372. ;
  22373. _proto.resetControlBarUI_ = function resetControlBarUI_() {
  22374. this.resetProgressBar_();
  22375. this.resetPlaybackRate_();
  22376. this.resetVolumeBar_();
  22377. }
  22378. /**
  22379. * Reset tech's progress so progress bar is reset in the UI
  22380. */
  22381. ;
  22382. _proto.resetProgressBar_ = function resetProgressBar_() {
  22383. this.currentTime(0);
  22384. var _ref3 = this.controlBar || {},
  22385. durationDisplay = _ref3.durationDisplay,
  22386. remainingTimeDisplay = _ref3.remainingTimeDisplay;
  22387. if (durationDisplay) {
  22388. durationDisplay.updateContent();
  22389. }
  22390. if (remainingTimeDisplay) {
  22391. remainingTimeDisplay.updateContent();
  22392. }
  22393. }
  22394. /**
  22395. * Reset Playback ratio
  22396. */
  22397. ;
  22398. _proto.resetPlaybackRate_ = function resetPlaybackRate_() {
  22399. this.playbackRate(this.defaultPlaybackRate());
  22400. this.handleTechRateChange_();
  22401. }
  22402. /**
  22403. * Reset Volume bar
  22404. */
  22405. ;
  22406. _proto.resetVolumeBar_ = function resetVolumeBar_() {
  22407. this.volume(1.0);
  22408. this.trigger('volumechange');
  22409. }
  22410. /**
  22411. * Returns all of the current source objects.
  22412. *
  22413. * @return {Tech~SourceObject[]}
  22414. * The current source objects
  22415. */
  22416. ;
  22417. _proto.currentSources = function currentSources() {
  22418. var source = this.currentSource();
  22419. var sources = []; // assume `{}` or `{ src }`
  22420. if (Object.keys(source).length !== 0) {
  22421. sources.push(source);
  22422. }
  22423. return this.cache_.sources || sources;
  22424. }
  22425. /**
  22426. * Returns the current source object.
  22427. *
  22428. * @return {Tech~SourceObject}
  22429. * The current source object
  22430. */
  22431. ;
  22432. _proto.currentSource = function currentSource() {
  22433. return this.cache_.source || {};
  22434. }
  22435. /**
  22436. * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4
  22437. * Can be used in conjunction with `currentType` to assist in rebuilding the current source object.
  22438. *
  22439. * @return {string}
  22440. * The current source
  22441. */
  22442. ;
  22443. _proto.currentSrc = function currentSrc() {
  22444. return this.currentSource() && this.currentSource().src || '';
  22445. }
  22446. /**
  22447. * Get the current source type e.g. video/mp4
  22448. * This can allow you rebuild the current source object so that you could load the same
  22449. * source and tech later
  22450. *
  22451. * @return {string}
  22452. * The source MIME type
  22453. */
  22454. ;
  22455. _proto.currentType = function currentType() {
  22456. return this.currentSource() && this.currentSource().type || '';
  22457. }
  22458. /**
  22459. * Get or set the preload attribute
  22460. *
  22461. * @param {boolean} [value]
  22462. * - true means that we should preload
  22463. * - false means that we should not preload
  22464. *
  22465. * @return {string}
  22466. * The preload attribute value when getting
  22467. */
  22468. ;
  22469. _proto.preload = function preload(value) {
  22470. if (value !== undefined) {
  22471. this.techCall_('setPreload', value);
  22472. this.options_.preload = value;
  22473. return;
  22474. }
  22475. return this.techGet_('preload');
  22476. }
  22477. /**
  22478. * Get or set the autoplay option. When this is a boolean it will
  22479. * modify the attribute on the tech. When this is a string the attribute on
  22480. * the tech will be removed and `Player` will handle autoplay on loadstarts.
  22481. *
  22482. * @param {boolean|string} [value]
  22483. * - true: autoplay using the browser behavior
  22484. * - false: do not autoplay
  22485. * - 'play': call play() on every loadstart
  22486. * - 'muted': call muted() then play() on every loadstart
  22487. * - 'any': call play() on every loadstart. if that fails call muted() then play().
  22488. * - *: values other than those listed here will be set `autoplay` to true
  22489. *
  22490. * @return {boolean|string}
  22491. * The current value of autoplay when getting
  22492. */
  22493. ;
  22494. _proto.autoplay = function autoplay(value) {
  22495. // getter usage
  22496. if (value === undefined) {
  22497. return this.options_.autoplay || false;
  22498. }
  22499. var techAutoplay; // if the value is a valid string set it to that, or normalize `true` to 'play', if need be
  22500. if (typeof value === 'string' && /(any|play|muted)/.test(value) || value === true && this.options_.normalizeAutoplay) {
  22501. this.options_.autoplay = value;
  22502. this.manualAutoplay_(typeof value === 'string' ? value : 'play');
  22503. techAutoplay = false; // any falsy value sets autoplay to false in the browser,
  22504. // lets do the same
  22505. } else if (!value) {
  22506. this.options_.autoplay = false; // any other value (ie truthy) sets autoplay to true
  22507. } else {
  22508. this.options_.autoplay = true;
  22509. }
  22510. techAutoplay = typeof techAutoplay === 'undefined' ? this.options_.autoplay : techAutoplay; // if we don't have a tech then we do not queue up
  22511. // a setAutoplay call on tech ready. We do this because the
  22512. // autoplay option will be passed in the constructor and we
  22513. // do not need to set it twice
  22514. if (this.tech_) {
  22515. this.techCall_('setAutoplay', techAutoplay);
  22516. }
  22517. }
  22518. /**
  22519. * Set or unset the playsinline attribute.
  22520. * Playsinline tells the browser that non-fullscreen playback is preferred.
  22521. *
  22522. * @param {boolean} [value]
  22523. * - true means that we should try to play inline by default
  22524. * - false means that we should use the browser's default playback mode,
  22525. * which in most cases is inline. iOS Safari is a notable exception
  22526. * and plays fullscreen by default.
  22527. *
  22528. * @return {string|Player}
  22529. * - the current value of playsinline
  22530. * - the player when setting
  22531. *
  22532. * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline}
  22533. */
  22534. ;
  22535. _proto.playsinline = function playsinline(value) {
  22536. if (value !== undefined) {
  22537. this.techCall_('setPlaysinline', value);
  22538. this.options_.playsinline = value;
  22539. return this;
  22540. }
  22541. return this.techGet_('playsinline');
  22542. }
  22543. /**
  22544. * Get or set the loop attribute on the video element.
  22545. *
  22546. * @param {boolean} [value]
  22547. * - true means that we should loop the video
  22548. * - false means that we should not loop the video
  22549. *
  22550. * @return {boolean}
  22551. * The current value of loop when getting
  22552. */
  22553. ;
  22554. _proto.loop = function loop(value) {
  22555. if (value !== undefined) {
  22556. this.techCall_('setLoop', value);
  22557. this.options_.loop = value;
  22558. return;
  22559. }
  22560. return this.techGet_('loop');
  22561. }
  22562. /**
  22563. * Get or set the poster image source url
  22564. *
  22565. * @fires Player#posterchange
  22566. *
  22567. * @param {string} [src]
  22568. * Poster image source URL
  22569. *
  22570. * @return {string}
  22571. * The current value of poster when getting
  22572. */
  22573. ;
  22574. _proto.poster = function poster(src) {
  22575. if (src === undefined) {
  22576. return this.poster_;
  22577. } // The correct way to remove a poster is to set as an empty string
  22578. // other falsey values will throw errors
  22579. if (!src) {
  22580. src = '';
  22581. }
  22582. if (src === this.poster_) {
  22583. return;
  22584. } // update the internal poster variable
  22585. this.poster_ = src; // update the tech's poster
  22586. this.techCall_('setPoster', src);
  22587. this.isPosterFromTech_ = false; // alert components that the poster has been set
  22588. /**
  22589. * This event fires when the poster image is changed on the player.
  22590. *
  22591. * @event Player#posterchange
  22592. * @type {EventTarget~Event}
  22593. */
  22594. this.trigger('posterchange');
  22595. }
  22596. /**
  22597. * Some techs (e.g. YouTube) can provide a poster source in an
  22598. * asynchronous way. We want the poster component to use this
  22599. * poster source so that it covers up the tech's controls.
  22600. * (YouTube's play button). However we only want to use this
  22601. * source if the player user hasn't set a poster through
  22602. * the normal APIs.
  22603. *
  22604. * @fires Player#posterchange
  22605. * @listens Tech#posterchange
  22606. * @private
  22607. */
  22608. ;
  22609. _proto.handleTechPosterChange_ = function handleTechPosterChange_() {
  22610. if ((!this.poster_ || this.options_.techCanOverridePoster) && this.tech_ && this.tech_.poster) {
  22611. var newPoster = this.tech_.poster() || '';
  22612. if (newPoster !== this.poster_) {
  22613. this.poster_ = newPoster;
  22614. this.isPosterFromTech_ = true; // Let components know the poster has changed
  22615. this.trigger('posterchange');
  22616. }
  22617. }
  22618. }
  22619. /**
  22620. * Get or set whether or not the controls are showing.
  22621. *
  22622. * @fires Player#controlsenabled
  22623. *
  22624. * @param {boolean} [bool]
  22625. * - true to turn controls on
  22626. * - false to turn controls off
  22627. *
  22628. * @return {boolean}
  22629. * The current value of controls when getting
  22630. */
  22631. ;
  22632. _proto.controls = function controls(bool) {
  22633. if (bool === undefined) {
  22634. return !!this.controls_;
  22635. }
  22636. bool = !!bool; // Don't trigger a change event unless it actually changed
  22637. if (this.controls_ === bool) {
  22638. return;
  22639. }
  22640. this.controls_ = bool;
  22641. if (this.usingNativeControls()) {
  22642. this.techCall_('setControls', bool);
  22643. }
  22644. if (this.controls_) {
  22645. this.removeClass('vjs-controls-disabled');
  22646. this.addClass('vjs-controls-enabled');
  22647. /**
  22648. * @event Player#controlsenabled
  22649. * @type {EventTarget~Event}
  22650. */
  22651. this.trigger('controlsenabled');
  22652. if (!this.usingNativeControls()) {
  22653. this.addTechControlsListeners_();
  22654. }
  22655. } else {
  22656. this.removeClass('vjs-controls-enabled');
  22657. this.addClass('vjs-controls-disabled');
  22658. /**
  22659. * @event Player#controlsdisabled
  22660. * @type {EventTarget~Event}
  22661. */
  22662. this.trigger('controlsdisabled');
  22663. if (!this.usingNativeControls()) {
  22664. this.removeTechControlsListeners_();
  22665. }
  22666. }
  22667. }
  22668. /**
  22669. * Toggle native controls on/off. Native controls are the controls built into
  22670. * devices (e.g. default iPhone controls) or other techs
  22671. * (e.g. Vimeo Controls)
  22672. * **This should only be set by the current tech, because only the tech knows
  22673. * if it can support native controls**
  22674. *
  22675. * @fires Player#usingnativecontrols
  22676. * @fires Player#usingcustomcontrols
  22677. *
  22678. * @param {boolean} [bool]
  22679. * - true to turn native controls on
  22680. * - false to turn native controls off
  22681. *
  22682. * @return {boolean}
  22683. * The current value of native controls when getting
  22684. */
  22685. ;
  22686. _proto.usingNativeControls = function usingNativeControls(bool) {
  22687. if (bool === undefined) {
  22688. return !!this.usingNativeControls_;
  22689. }
  22690. bool = !!bool; // Don't trigger a change event unless it actually changed
  22691. if (this.usingNativeControls_ === bool) {
  22692. return;
  22693. }
  22694. this.usingNativeControls_ = bool;
  22695. if (this.usingNativeControls_) {
  22696. this.addClass('vjs-using-native-controls');
  22697. /**
  22698. * player is using the native device controls
  22699. *
  22700. * @event Player#usingnativecontrols
  22701. * @type {EventTarget~Event}
  22702. */
  22703. this.trigger('usingnativecontrols');
  22704. } else {
  22705. this.removeClass('vjs-using-native-controls');
  22706. /**
  22707. * player is using the custom HTML controls
  22708. *
  22709. * @event Player#usingcustomcontrols
  22710. * @type {EventTarget~Event}
  22711. */
  22712. this.trigger('usingcustomcontrols');
  22713. }
  22714. }
  22715. /**
  22716. * Set or get the current MediaError
  22717. *
  22718. * @fires Player#error
  22719. *
  22720. * @param {MediaError|string|number} [err]
  22721. * A MediaError or a string/number to be turned
  22722. * into a MediaError
  22723. *
  22724. * @return {MediaError|null}
  22725. * The current MediaError when getting (or null)
  22726. */
  22727. ;
  22728. _proto.error = function error(err) {
  22729. var _this18 = this;
  22730. if (err === undefined) {
  22731. return this.error_ || null;
  22732. } // allow hooks to modify error object
  22733. hooks('beforeerror').forEach(function (hookFunction) {
  22734. var newErr = hookFunction(_this18, err);
  22735. if (!(isObject$1(newErr) && !Array.isArray(newErr) || typeof newErr === 'string' || typeof newErr === 'number' || newErr === null)) {
  22736. _this18.log.error('please return a value that MediaError expects in beforeerror hooks');
  22737. return;
  22738. }
  22739. err = newErr;
  22740. }); // Suppress the first error message for no compatible source until
  22741. // user interaction
  22742. if (this.options_.suppressNotSupportedError && err && err.code === 4) {
  22743. var triggerSuppressedError = function triggerSuppressedError() {
  22744. this.error(err);
  22745. };
  22746. this.options_.suppressNotSupportedError = false;
  22747. this.any(['click', 'touchstart'], triggerSuppressedError);
  22748. this.one('loadstart', function () {
  22749. this.off(['click', 'touchstart'], triggerSuppressedError);
  22750. });
  22751. return;
  22752. } // restoring to default
  22753. if (err === null) {
  22754. this.error_ = err;
  22755. this.removeClass('vjs-error');
  22756. if (this.errorDisplay) {
  22757. this.errorDisplay.close();
  22758. }
  22759. return;
  22760. }
  22761. this.error_ = new MediaError(err); // add the vjs-error classname to the player
  22762. this.addClass('vjs-error'); // log the name of the error type and any message
  22763. // IE11 logs "[object object]" and required you to expand message to see error object
  22764. log$1.error("(CODE:" + this.error_.code + " " + MediaError.errorTypes[this.error_.code] + ")", this.error_.message, this.error_);
  22765. /**
  22766. * @event Player#error
  22767. * @type {EventTarget~Event}
  22768. */
  22769. this.trigger('error'); // notify hooks of the per player error
  22770. hooks('error').forEach(function (hookFunction) {
  22771. return hookFunction(_this18, _this18.error_);
  22772. });
  22773. return;
  22774. }
  22775. /**
  22776. * Report user activity
  22777. *
  22778. * @param {Object} event
  22779. * Event object
  22780. */
  22781. ;
  22782. _proto.reportUserActivity = function reportUserActivity(event) {
  22783. this.userActivity_ = true;
  22784. }
  22785. /**
  22786. * Get/set if user is active
  22787. *
  22788. * @fires Player#useractive
  22789. * @fires Player#userinactive
  22790. *
  22791. * @param {boolean} [bool]
  22792. * - true if the user is active
  22793. * - false if the user is inactive
  22794. *
  22795. * @return {boolean}
  22796. * The current value of userActive when getting
  22797. */
  22798. ;
  22799. _proto.userActive = function userActive(bool) {
  22800. if (bool === undefined) {
  22801. return this.userActive_;
  22802. }
  22803. bool = !!bool;
  22804. if (bool === this.userActive_) {
  22805. return;
  22806. }
  22807. this.userActive_ = bool;
  22808. if (this.userActive_) {
  22809. this.userActivity_ = true;
  22810. this.removeClass('vjs-user-inactive');
  22811. this.addClass('vjs-user-active');
  22812. /**
  22813. * @event Player#useractive
  22814. * @type {EventTarget~Event}
  22815. */
  22816. this.trigger('useractive');
  22817. return;
  22818. } // Chrome/Safari/IE have bugs where when you change the cursor it can
  22819. // trigger a mousemove event. This causes an issue when you're hiding
  22820. // the cursor when the user is inactive, and a mousemove signals user
  22821. // activity. Making it impossible to go into inactive mode. Specifically
  22822. // this happens in fullscreen when we really need to hide the cursor.
  22823. //
  22824. // When this gets resolved in ALL browsers it can be removed
  22825. // https://code.google.com/p/chromium/issues/detail?id=103041
  22826. if (this.tech_) {
  22827. this.tech_.one('mousemove', function (e) {
  22828. e.stopPropagation();
  22829. e.preventDefault();
  22830. });
  22831. }
  22832. this.userActivity_ = false;
  22833. this.removeClass('vjs-user-active');
  22834. this.addClass('vjs-user-inactive');
  22835. /**
  22836. * @event Player#userinactive
  22837. * @type {EventTarget~Event}
  22838. */
  22839. this.trigger('userinactive');
  22840. }
  22841. /**
  22842. * Listen for user activity based on timeout value
  22843. *
  22844. * @private
  22845. */
  22846. ;
  22847. _proto.listenForUserActivity_ = function listenForUserActivity_() {
  22848. var mouseInProgress;
  22849. var lastMoveX;
  22850. var lastMoveY;
  22851. var handleActivity = bind(this, this.reportUserActivity);
  22852. var handleMouseMove = function handleMouseMove(e) {
  22853. // #1068 - Prevent mousemove spamming
  22854. // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970
  22855. if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) {
  22856. lastMoveX = e.screenX;
  22857. lastMoveY = e.screenY;
  22858. handleActivity();
  22859. }
  22860. };
  22861. var handleMouseDown = function handleMouseDown() {
  22862. handleActivity(); // For as long as the they are touching the device or have their mouse down,
  22863. // we consider them active even if they're not moving their finger or mouse.
  22864. // So we want to continue to update that they are active
  22865. this.clearInterval(mouseInProgress); // Setting userActivity=true now and setting the interval to the same time
  22866. // as the activityCheck interval (250) should ensure we never miss the
  22867. // next activityCheck
  22868. mouseInProgress = this.setInterval(handleActivity, 250);
  22869. };
  22870. var handleMouseUpAndMouseLeave = function handleMouseUpAndMouseLeave(event) {
  22871. handleActivity(); // Stop the interval that maintains activity if the mouse/touch is down
  22872. this.clearInterval(mouseInProgress);
  22873. }; // Any mouse movement will be considered user activity
  22874. this.on('mousedown', handleMouseDown);
  22875. this.on('mousemove', handleMouseMove);
  22876. this.on('mouseup', handleMouseUpAndMouseLeave);
  22877. this.on('mouseleave', handleMouseUpAndMouseLeave);
  22878. var controlBar = this.getChild('controlBar'); // Fixes bug on Android & iOS where when tapping progressBar (when control bar is displayed)
  22879. // controlBar would no longer be hidden by default timeout.
  22880. if (controlBar && !IS_IOS && !IS_ANDROID) {
  22881. controlBar.on('mouseenter', function (event) {
  22882. if (this.player().options_.inactivityTimeout !== 0) {
  22883. this.player().cache_.inactivityTimeout = this.player().options_.inactivityTimeout;
  22884. }
  22885. this.player().options_.inactivityTimeout = 0;
  22886. });
  22887. controlBar.on('mouseleave', function (event) {
  22888. this.player().options_.inactivityTimeout = this.player().cache_.inactivityTimeout;
  22889. });
  22890. } // Listen for keyboard navigation
  22891. // Shouldn't need to use inProgress interval because of key repeat
  22892. this.on('keydown', handleActivity);
  22893. this.on('keyup', handleActivity); // Run an interval every 250 milliseconds instead of stuffing everything into
  22894. // the mousemove/touchmove function itself, to prevent performance degradation.
  22895. // `this.reportUserActivity` simply sets this.userActivity_ to true, which
  22896. // then gets picked up by this loop
  22897. // http://ejohn.org/blog/learning-from-twitter/
  22898. var inactivityTimeout;
  22899. this.setInterval(function () {
  22900. // Check to see if mouse/touch activity has happened
  22901. if (!this.userActivity_) {
  22902. return;
  22903. } // Reset the activity tracker
  22904. this.userActivity_ = false; // If the user state was inactive, set the state to active
  22905. this.userActive(true); // Clear any existing inactivity timeout to start the timer over
  22906. this.clearTimeout(inactivityTimeout);
  22907. var timeout = this.options_.inactivityTimeout;
  22908. if (timeout <= 0) {
  22909. return;
  22910. } // In <timeout> milliseconds, if no more activity has occurred the
  22911. // user will be considered inactive
  22912. inactivityTimeout = this.setTimeout(function () {
  22913. // Protect against the case where the inactivityTimeout can trigger just
  22914. // before the next user activity is picked up by the activity check loop
  22915. // causing a flicker
  22916. if (!this.userActivity_) {
  22917. this.userActive(false);
  22918. }
  22919. }, timeout);
  22920. }, 250);
  22921. }
  22922. /**
  22923. * Gets or sets the current playback rate. A playback rate of
  22924. * 1.0 represents normal speed and 0.5 would indicate half-speed
  22925. * playback, for instance.
  22926. *
  22927. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate
  22928. *
  22929. * @param {number} [rate]
  22930. * New playback rate to set.
  22931. *
  22932. * @return {number}
  22933. * The current playback rate when getting or 1.0
  22934. */
  22935. ;
  22936. _proto.playbackRate = function playbackRate(rate) {
  22937. if (rate !== undefined) {
  22938. // NOTE: this.cache_.lastPlaybackRate is set from the tech handler
  22939. // that is registered above
  22940. this.techCall_('setPlaybackRate', rate);
  22941. return;
  22942. }
  22943. if (this.tech_ && this.tech_.featuresPlaybackRate) {
  22944. return this.cache_.lastPlaybackRate || this.techGet_('playbackRate');
  22945. }
  22946. return 1.0;
  22947. }
  22948. /**
  22949. * Gets or sets the current default playback rate. A default playback rate of
  22950. * 1.0 represents normal speed and 0.5 would indicate half-speed playback, for instance.
  22951. * defaultPlaybackRate will only represent what the initial playbackRate of a video was, not
  22952. * not the current playbackRate.
  22953. *
  22954. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-defaultplaybackrate
  22955. *
  22956. * @param {number} [rate]
  22957. * New default playback rate to set.
  22958. *
  22959. * @return {number|Player}
  22960. * - The default playback rate when getting or 1.0
  22961. * - the player when setting
  22962. */
  22963. ;
  22964. _proto.defaultPlaybackRate = function defaultPlaybackRate(rate) {
  22965. if (rate !== undefined) {
  22966. return this.techCall_('setDefaultPlaybackRate', rate);
  22967. }
  22968. if (this.tech_ && this.tech_.featuresPlaybackRate) {
  22969. return this.techGet_('defaultPlaybackRate');
  22970. }
  22971. return 1.0;
  22972. }
  22973. /**
  22974. * Gets or sets the audio flag
  22975. *
  22976. * @param {boolean} bool
  22977. * - true signals that this is an audio player
  22978. * - false signals that this is not an audio player
  22979. *
  22980. * @return {boolean}
  22981. * The current value of isAudio when getting
  22982. */
  22983. ;
  22984. _proto.isAudio = function isAudio(bool) {
  22985. if (bool !== undefined) {
  22986. this.isAudio_ = !!bool;
  22987. return;
  22988. }
  22989. return !!this.isAudio_;
  22990. };
  22991. _proto.enableAudioOnlyUI_ = function enableAudioOnlyUI_() {
  22992. var _this19 = this;
  22993. // Update styling immediately to show the control bar so we can get its height
  22994. this.addClass('vjs-audio-only-mode');
  22995. var playerChildren = this.children();
  22996. var controlBar = this.getChild('ControlBar');
  22997. var controlBarHeight = controlBar && controlBar.currentHeight(); // Hide all player components except the control bar. Control bar components
  22998. // needed only for video are hidden with CSS
  22999. playerChildren.forEach(function (child) {
  23000. if (child === controlBar) {
  23001. return;
  23002. }
  23003. if (child.el_ && !child.hasClass('vjs-hidden')) {
  23004. child.hide();
  23005. _this19.audioOnlyCache_.hiddenChildren.push(child);
  23006. }
  23007. });
  23008. this.audioOnlyCache_.playerHeight = this.currentHeight(); // Set the player height the same as the control bar
  23009. this.height(controlBarHeight);
  23010. this.trigger('audioonlymodechange');
  23011. };
  23012. _proto.disableAudioOnlyUI_ = function disableAudioOnlyUI_() {
  23013. this.removeClass('vjs-audio-only-mode'); // Show player components that were previously hidden
  23014. this.audioOnlyCache_.hiddenChildren.forEach(function (child) {
  23015. return child.show();
  23016. }); // Reset player height
  23017. this.height(this.audioOnlyCache_.playerHeight);
  23018. this.trigger('audioonlymodechange');
  23019. }
  23020. /**
  23021. * Get the current audioOnlyMode state or set audioOnlyMode to true or false.
  23022. *
  23023. * Setting this to `true` will hide all player components except the control bar,
  23024. * as well as control bar components needed only for video.
  23025. *
  23026. * @param {boolean} [value]
  23027. * The value to set audioOnlyMode to.
  23028. *
  23029. * @return {Promise|boolean}
  23030. * A Promise is returned when setting the state, and a boolean when getting
  23031. * the present state
  23032. */
  23033. ;
  23034. _proto.audioOnlyMode = function audioOnlyMode(value) {
  23035. var _this20 = this;
  23036. if (typeof value !== 'boolean' || value === this.audioOnlyMode_) {
  23037. return this.audioOnlyMode_;
  23038. }
  23039. this.audioOnlyMode_ = value;
  23040. var PromiseClass = this.options_.Promise || window.Promise;
  23041. if (PromiseClass) {
  23042. // Enable Audio Only Mode
  23043. if (value) {
  23044. var exitPromises = []; // Fullscreen and PiP are not supported in audioOnlyMode, so exit if we need to.
  23045. if (this.isInPictureInPicture()) {
  23046. exitPromises.push(this.exitPictureInPicture());
  23047. }
  23048. if (this.isFullscreen()) {
  23049. exitPromises.push(this.exitFullscreen());
  23050. }
  23051. if (this.audioPosterMode()) {
  23052. exitPromises.push(this.audioPosterMode(false));
  23053. }
  23054. return PromiseClass.all(exitPromises).then(function () {
  23055. return _this20.enableAudioOnlyUI_();
  23056. });
  23057. } // Disable Audio Only Mode
  23058. return PromiseClass.resolve().then(function () {
  23059. return _this20.disableAudioOnlyUI_();
  23060. });
  23061. }
  23062. if (value) {
  23063. if (this.isInPictureInPicture()) {
  23064. this.exitPictureInPicture();
  23065. }
  23066. if (this.isFullscreen()) {
  23067. this.exitFullscreen();
  23068. }
  23069. this.enableAudioOnlyUI_();
  23070. } else {
  23071. this.disableAudioOnlyUI_();
  23072. }
  23073. };
  23074. _proto.enablePosterModeUI_ = function enablePosterModeUI_() {
  23075. // Hide the video element and show the poster image to enable posterModeUI
  23076. var tech = this.tech_ && this.tech_;
  23077. tech.hide();
  23078. this.addClass('vjs-audio-poster-mode');
  23079. this.trigger('audiopostermodechange');
  23080. };
  23081. _proto.disablePosterModeUI_ = function disablePosterModeUI_() {
  23082. // Show the video element and hide the poster image to disable posterModeUI
  23083. var tech = this.tech_ && this.tech_;
  23084. tech.show();
  23085. this.removeClass('vjs-audio-poster-mode');
  23086. this.trigger('audiopostermodechange');
  23087. }
  23088. /**
  23089. * Get the current audioPosterMode state or set audioPosterMode to true or false
  23090. *
  23091. * @param {boolean} [value]
  23092. * The value to set audioPosterMode to.
  23093. *
  23094. * @return {Promise|boolean}
  23095. * A Promise is returned when setting the state, and a boolean when getting
  23096. * the present state
  23097. */
  23098. ;
  23099. _proto.audioPosterMode = function audioPosterMode(value) {
  23100. var _this21 = this;
  23101. if (typeof value !== 'boolean' || value === this.audioPosterMode_) {
  23102. return this.audioPosterMode_;
  23103. }
  23104. this.audioPosterMode_ = value;
  23105. var PromiseClass = this.options_.Promise || window.Promise;
  23106. if (PromiseClass) {
  23107. if (value) {
  23108. if (this.audioOnlyMode()) {
  23109. var audioOnlyModePromise = this.audioOnlyMode(false);
  23110. return audioOnlyModePromise.then(function () {
  23111. // enable audio poster mode after audio only mode is disabled
  23112. _this21.enablePosterModeUI_();
  23113. });
  23114. }
  23115. return PromiseClass.resolve().then(function () {
  23116. // enable audio poster mode
  23117. _this21.enablePosterModeUI_();
  23118. });
  23119. }
  23120. return PromiseClass.resolve().then(function () {
  23121. // disable audio poster mode
  23122. _this21.disablePosterModeUI_();
  23123. });
  23124. }
  23125. if (value) {
  23126. if (this.audioOnlyMode()) {
  23127. this.audioOnlyMode(false);
  23128. }
  23129. this.enablePosterModeUI_();
  23130. return;
  23131. }
  23132. this.disablePosterModeUI_();
  23133. }
  23134. /**
  23135. * A helper method for adding a {@link TextTrack} to our
  23136. * {@link TextTrackList}.
  23137. *
  23138. * In addition to the W3C settings we allow adding additional info through options.
  23139. *
  23140. * @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack
  23141. *
  23142. * @param {string} [kind]
  23143. * the kind of TextTrack you are adding
  23144. *
  23145. * @param {string} [label]
  23146. * the label to give the TextTrack label
  23147. *
  23148. * @param {string} [language]
  23149. * the language to set on the TextTrack
  23150. *
  23151. * @return {TextTrack|undefined}
  23152. * the TextTrack that was added or undefined
  23153. * if there is no tech
  23154. */
  23155. ;
  23156. _proto.addTextTrack = function addTextTrack(kind, label, language) {
  23157. if (this.tech_) {
  23158. return this.tech_.addTextTrack(kind, label, language);
  23159. }
  23160. }
  23161. /**
  23162. * Create a remote {@link TextTrack} and an {@link HTMLTrackElement}.
  23163. * When manualCleanup is set to false, the track will be automatically removed
  23164. * on source changes.
  23165. *
  23166. * @param {Object} options
  23167. * Options to pass to {@link HTMLTrackElement} during creation. See
  23168. * {@link HTMLTrackElement} for object properties that you should use.
  23169. *
  23170. * @param {boolean} [manualCleanup=true] if set to false, the TextTrack will be
  23171. * removed on a source change
  23172. *
  23173. * @return {HtmlTrackElement}
  23174. * the HTMLTrackElement that was created and added
  23175. * to the HtmlTrackElementList and the remote
  23176. * TextTrackList
  23177. *
  23178. * @deprecated The default value of the "manualCleanup" parameter will default
  23179. * to "false" in upcoming versions of Video.js
  23180. */
  23181. ;
  23182. _proto.addRemoteTextTrack = function addRemoteTextTrack(options, manualCleanup) {
  23183. if (this.tech_) {
  23184. return this.tech_.addRemoteTextTrack(options, manualCleanup);
  23185. }
  23186. }
  23187. /**
  23188. * Remove a remote {@link TextTrack} from the respective
  23189. * {@link TextTrackList} and {@link HtmlTrackElementList}.
  23190. *
  23191. * @param {Object} track
  23192. * Remote {@link TextTrack} to remove
  23193. *
  23194. * @return {undefined}
  23195. * does not return anything
  23196. */
  23197. ;
  23198. _proto.removeRemoteTextTrack = function removeRemoteTextTrack(obj) {
  23199. if (obj === void 0) {
  23200. obj = {};
  23201. }
  23202. var _obj = obj,
  23203. track = _obj.track;
  23204. if (!track) {
  23205. track = obj;
  23206. } // destructure the input into an object with a track argument, defaulting to arguments[0]
  23207. // default the whole argument to an empty object if nothing was passed in
  23208. if (this.tech_) {
  23209. return this.tech_.removeRemoteTextTrack(track);
  23210. }
  23211. }
  23212. /**
  23213. * Gets available media playback quality metrics as specified by the W3C's Media
  23214. * Playback Quality API.
  23215. *
  23216. * @see [Spec]{@link https://wicg.github.io/media-playback-quality}
  23217. *
  23218. * @return {Object|undefined}
  23219. * An object with supported media playback quality metrics or undefined if there
  23220. * is no tech or the tech does not support it.
  23221. */
  23222. ;
  23223. _proto.getVideoPlaybackQuality = function getVideoPlaybackQuality() {
  23224. return this.techGet_('getVideoPlaybackQuality');
  23225. }
  23226. /**
  23227. * Get video width
  23228. *
  23229. * @return {number}
  23230. * current video width
  23231. */
  23232. ;
  23233. _proto.videoWidth = function videoWidth() {
  23234. return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0;
  23235. }
  23236. /**
  23237. * Get video height
  23238. *
  23239. * @return {number}
  23240. * current video height
  23241. */
  23242. ;
  23243. _proto.videoHeight = function videoHeight() {
  23244. return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0;
  23245. }
  23246. /**
  23247. * The player's language code.
  23248. *
  23249. * Changing the language will trigger
  23250. * [languagechange]{@link Player#event:languagechange}
  23251. * which Components can use to update control text.
  23252. * ClickableComponent will update its control text by default on
  23253. * [languagechange]{@link Player#event:languagechange}.
  23254. *
  23255. * @fires Player#languagechange
  23256. *
  23257. * @param {string} [code]
  23258. * the language code to set the player to
  23259. *
  23260. * @return {string}
  23261. * The current language code when getting
  23262. */
  23263. ;
  23264. _proto.language = function language(code) {
  23265. if (code === undefined) {
  23266. return this.language_;
  23267. }
  23268. if (this.language_ !== String(code).toLowerCase()) {
  23269. this.language_ = String(code).toLowerCase(); // during first init, it's possible some things won't be evented
  23270. if (isEvented(this)) {
  23271. /**
  23272. * fires when the player language change
  23273. *
  23274. * @event Player#languagechange
  23275. * @type {EventTarget~Event}
  23276. */
  23277. this.trigger('languagechange');
  23278. }
  23279. }
  23280. }
  23281. /**
  23282. * Get the player's language dictionary
  23283. * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time
  23284. * Languages specified directly in the player options have precedence
  23285. *
  23286. * @return {Array}
  23287. * An array of of supported languages
  23288. */
  23289. ;
  23290. _proto.languages = function languages() {
  23291. return mergeOptions$3(Player.prototype.options_.languages, this.languages_);
  23292. }
  23293. /**
  23294. * returns a JavaScript object reperesenting the current track
  23295. * information. **DOES not return it as JSON**
  23296. *
  23297. * @return {Object}
  23298. * Object representing the current of track info
  23299. */
  23300. ;
  23301. _proto.toJSON = function toJSON() {
  23302. var options = mergeOptions$3(this.options_);
  23303. var tracks = options.tracks;
  23304. options.tracks = [];
  23305. for (var i = 0; i < tracks.length; i++) {
  23306. var track = tracks[i]; // deep merge tracks and null out player so no circular references
  23307. track = mergeOptions$3(track);
  23308. track.player = undefined;
  23309. options.tracks[i] = track;
  23310. }
  23311. return options;
  23312. }
  23313. /**
  23314. * Creates a simple modal dialog (an instance of the {@link ModalDialog}
  23315. * component) that immediately overlays the player with arbitrary
  23316. * content and removes itself when closed.
  23317. *
  23318. * @param {string|Function|Element|Array|null} content
  23319. * Same as {@link ModalDialog#content}'s param of the same name.
  23320. * The most straight-forward usage is to provide a string or DOM
  23321. * element.
  23322. *
  23323. * @param {Object} [options]
  23324. * Extra options which will be passed on to the {@link ModalDialog}.
  23325. *
  23326. * @return {ModalDialog}
  23327. * the {@link ModalDialog} that was created
  23328. */
  23329. ;
  23330. _proto.createModal = function createModal(content, options) {
  23331. var _this22 = this;
  23332. options = options || {};
  23333. options.content = content || '';
  23334. var modal = new ModalDialog(this, options);
  23335. this.addChild(modal);
  23336. modal.on('dispose', function () {
  23337. _this22.removeChild(modal);
  23338. });
  23339. modal.open();
  23340. return modal;
  23341. }
  23342. /**
  23343. * Change breakpoint classes when the player resizes.
  23344. *
  23345. * @private
  23346. */
  23347. ;
  23348. _proto.updateCurrentBreakpoint_ = function updateCurrentBreakpoint_() {
  23349. if (!this.responsive()) {
  23350. return;
  23351. }
  23352. var currentBreakpoint = this.currentBreakpoint();
  23353. var currentWidth = this.currentWidth();
  23354. for (var i = 0; i < BREAKPOINT_ORDER.length; i++) {
  23355. var candidateBreakpoint = BREAKPOINT_ORDER[i];
  23356. var maxWidth = this.breakpoints_[candidateBreakpoint];
  23357. if (currentWidth <= maxWidth) {
  23358. // The current breakpoint did not change, nothing to do.
  23359. if (currentBreakpoint === candidateBreakpoint) {
  23360. return;
  23361. } // Only remove a class if there is a current breakpoint.
  23362. if (currentBreakpoint) {
  23363. this.removeClass(BREAKPOINT_CLASSES[currentBreakpoint]);
  23364. }
  23365. this.addClass(BREAKPOINT_CLASSES[candidateBreakpoint]);
  23366. this.breakpoint_ = candidateBreakpoint;
  23367. break;
  23368. }
  23369. }
  23370. }
  23371. /**
  23372. * Removes the current breakpoint.
  23373. *
  23374. * @private
  23375. */
  23376. ;
  23377. _proto.removeCurrentBreakpoint_ = function removeCurrentBreakpoint_() {
  23378. var className = this.currentBreakpointClass();
  23379. this.breakpoint_ = '';
  23380. if (className) {
  23381. this.removeClass(className);
  23382. }
  23383. }
  23384. /**
  23385. * Get or set breakpoints on the player.
  23386. *
  23387. * Calling this method with an object or `true` will remove any previous
  23388. * custom breakpoints and start from the defaults again.
  23389. *
  23390. * @param {Object|boolean} [breakpoints]
  23391. * If an object is given, it can be used to provide custom
  23392. * breakpoints. If `true` is given, will set default breakpoints.
  23393. * If this argument is not given, will simply return the current
  23394. * breakpoints.
  23395. *
  23396. * @param {number} [breakpoints.tiny]
  23397. * The maximum width for the "vjs-layout-tiny" class.
  23398. *
  23399. * @param {number} [breakpoints.xsmall]
  23400. * The maximum width for the "vjs-layout-x-small" class.
  23401. *
  23402. * @param {number} [breakpoints.small]
  23403. * The maximum width for the "vjs-layout-small" class.
  23404. *
  23405. * @param {number} [breakpoints.medium]
  23406. * The maximum width for the "vjs-layout-medium" class.
  23407. *
  23408. * @param {number} [breakpoints.large]
  23409. * The maximum width for the "vjs-layout-large" class.
  23410. *
  23411. * @param {number} [breakpoints.xlarge]
  23412. * The maximum width for the "vjs-layout-x-large" class.
  23413. *
  23414. * @param {number} [breakpoints.huge]
  23415. * The maximum width for the "vjs-layout-huge" class.
  23416. *
  23417. * @return {Object}
  23418. * An object mapping breakpoint names to maximum width values.
  23419. */
  23420. ;
  23421. _proto.breakpoints = function breakpoints(_breakpoints) {
  23422. // Used as a getter.
  23423. if (_breakpoints === undefined) {
  23424. return assign$1(this.breakpoints_);
  23425. }
  23426. this.breakpoint_ = '';
  23427. this.breakpoints_ = assign$1({}, DEFAULT_BREAKPOINTS, _breakpoints); // When breakpoint definitions change, we need to update the currently
  23428. // selected breakpoint.
  23429. this.updateCurrentBreakpoint_(); // Clone the breakpoints before returning.
  23430. return assign$1(this.breakpoints_);
  23431. }
  23432. /**
  23433. * Get or set a flag indicating whether or not this player should adjust
  23434. * its UI based on its dimensions.
  23435. *
  23436. * @param {boolean} value
  23437. * Should be `true` if the player should adjust its UI based on its
  23438. * dimensions; otherwise, should be `false`.
  23439. *
  23440. * @return {boolean}
  23441. * Will be `true` if this player should adjust its UI based on its
  23442. * dimensions; otherwise, will be `false`.
  23443. */
  23444. ;
  23445. _proto.responsive = function responsive(value) {
  23446. // Used as a getter.
  23447. if (value === undefined) {
  23448. return this.responsive_;
  23449. }
  23450. value = Boolean(value);
  23451. var current = this.responsive_; // Nothing changed.
  23452. if (value === current) {
  23453. return;
  23454. } // The value actually changed, set it.
  23455. this.responsive_ = value; // Start listening for breakpoints and set the initial breakpoint if the
  23456. // player is now responsive.
  23457. if (value) {
  23458. this.on('playerresize', this.boundUpdateCurrentBreakpoint_);
  23459. this.updateCurrentBreakpoint_(); // Stop listening for breakpoints if the player is no longer responsive.
  23460. } else {
  23461. this.off('playerresize', this.boundUpdateCurrentBreakpoint_);
  23462. this.removeCurrentBreakpoint_();
  23463. }
  23464. return value;
  23465. }
  23466. /**
  23467. * Get current breakpoint name, if any.
  23468. *
  23469. * @return {string}
  23470. * If there is currently a breakpoint set, returns a the key from the
  23471. * breakpoints object matching it. Otherwise, returns an empty string.
  23472. */
  23473. ;
  23474. _proto.currentBreakpoint = function currentBreakpoint() {
  23475. return this.breakpoint_;
  23476. }
  23477. /**
  23478. * Get the current breakpoint class name.
  23479. *
  23480. * @return {string}
  23481. * The matching class name (e.g. `"vjs-layout-tiny"` or
  23482. * `"vjs-layout-large"`) for the current breakpoint. Empty string if
  23483. * there is no current breakpoint.
  23484. */
  23485. ;
  23486. _proto.currentBreakpointClass = function currentBreakpointClass() {
  23487. return BREAKPOINT_CLASSES[this.breakpoint_] || '';
  23488. }
  23489. /**
  23490. * An object that describes a single piece of media.
  23491. *
  23492. * Properties that are not part of this type description will be retained; so,
  23493. * this can be viewed as a generic metadata storage mechanism as well.
  23494. *
  23495. * @see {@link https://wicg.github.io/mediasession/#the-mediametadata-interface}
  23496. * @typedef {Object} Player~MediaObject
  23497. *
  23498. * @property {string} [album]
  23499. * Unused, except if this object is passed to the `MediaSession`
  23500. * API.
  23501. *
  23502. * @property {string} [artist]
  23503. * Unused, except if this object is passed to the `MediaSession`
  23504. * API.
  23505. *
  23506. * @property {Object[]} [artwork]
  23507. * Unused, except if this object is passed to the `MediaSession`
  23508. * API. If not specified, will be populated via the `poster`, if
  23509. * available.
  23510. *
  23511. * @property {string} [poster]
  23512. * URL to an image that will display before playback.
  23513. *
  23514. * @property {Tech~SourceObject|Tech~SourceObject[]|string} [src]
  23515. * A single source object, an array of source objects, or a string
  23516. * referencing a URL to a media source. It is _highly recommended_
  23517. * that an object or array of objects is used here, so that source
  23518. * selection algorithms can take the `type` into account.
  23519. *
  23520. * @property {string} [title]
  23521. * Unused, except if this object is passed to the `MediaSession`
  23522. * API.
  23523. *
  23524. * @property {Object[]} [textTracks]
  23525. * An array of objects to be used to create text tracks, following
  23526. * the {@link https://www.w3.org/TR/html50/embedded-content-0.html#the-track-element|native track element format}.
  23527. * For ease of removal, these will be created as "remote" text
  23528. * tracks and set to automatically clean up on source changes.
  23529. *
  23530. * These objects may have properties like `src`, `kind`, `label`,
  23531. * and `language`, see {@link Tech#createRemoteTextTrack}.
  23532. */
  23533. /**
  23534. * Populate the player using a {@link Player~MediaObject|MediaObject}.
  23535. *
  23536. * @param {Player~MediaObject} media
  23537. * A media object.
  23538. *
  23539. * @param {Function} ready
  23540. * A callback to be called when the player is ready.
  23541. */
  23542. ;
  23543. _proto.loadMedia = function loadMedia(media, ready) {
  23544. var _this23 = this;
  23545. if (!media || typeof media !== 'object') {
  23546. return;
  23547. }
  23548. this.reset(); // Clone the media object so it cannot be mutated from outside.
  23549. this.cache_.media = mergeOptions$3(media);
  23550. var _this$cache_$media = this.cache_.media,
  23551. artwork = _this$cache_$media.artwork,
  23552. poster = _this$cache_$media.poster,
  23553. src = _this$cache_$media.src,
  23554. textTracks = _this$cache_$media.textTracks; // If `artwork` is not given, create it using `poster`.
  23555. if (!artwork && poster) {
  23556. this.cache_.media.artwork = [{
  23557. src: poster,
  23558. type: getMimetype(poster)
  23559. }];
  23560. }
  23561. if (src) {
  23562. this.src(src);
  23563. }
  23564. if (poster) {
  23565. this.poster(poster);
  23566. }
  23567. if (Array.isArray(textTracks)) {
  23568. textTracks.forEach(function (tt) {
  23569. return _this23.addRemoteTextTrack(tt, false);
  23570. });
  23571. }
  23572. this.ready(ready);
  23573. }
  23574. /**
  23575. * Get a clone of the current {@link Player~MediaObject} for this player.
  23576. *
  23577. * If the `loadMedia` method has not been used, will attempt to return a
  23578. * {@link Player~MediaObject} based on the current state of the player.
  23579. *
  23580. * @return {Player~MediaObject}
  23581. */
  23582. ;
  23583. _proto.getMedia = function getMedia() {
  23584. if (!this.cache_.media) {
  23585. var poster = this.poster();
  23586. var src = this.currentSources();
  23587. var textTracks = Array.prototype.map.call(this.remoteTextTracks(), function (tt) {
  23588. return {
  23589. kind: tt.kind,
  23590. label: tt.label,
  23591. language: tt.language,
  23592. src: tt.src
  23593. };
  23594. });
  23595. var media = {
  23596. src: src,
  23597. textTracks: textTracks
  23598. };
  23599. if (poster) {
  23600. media.poster = poster;
  23601. media.artwork = [{
  23602. src: media.poster,
  23603. type: getMimetype(media.poster)
  23604. }];
  23605. }
  23606. return media;
  23607. }
  23608. return mergeOptions$3(this.cache_.media);
  23609. }
  23610. /**
  23611. * Gets tag settings
  23612. *
  23613. * @param {Element} tag
  23614. * The player tag
  23615. *
  23616. * @return {Object}
  23617. * An object containing all of the settings
  23618. * for a player tag
  23619. */
  23620. ;
  23621. Player.getTagSettings = function getTagSettings(tag) {
  23622. var baseOptions = {
  23623. sources: [],
  23624. tracks: []
  23625. };
  23626. var tagOptions = getAttributes(tag);
  23627. var dataSetup = tagOptions['data-setup'];
  23628. if (hasClass(tag, 'vjs-fill')) {
  23629. tagOptions.fill = true;
  23630. }
  23631. if (hasClass(tag, 'vjs-fluid')) {
  23632. tagOptions.fluid = true;
  23633. } // Check if data-setup attr exists.
  23634. if (dataSetup !== null) {
  23635. // Parse options JSON
  23636. // If empty string, make it a parsable json object.
  23637. var _safeParseTuple = tuple(dataSetup || '{}'),
  23638. err = _safeParseTuple[0],
  23639. data = _safeParseTuple[1];
  23640. if (err) {
  23641. log$1.error(err);
  23642. }
  23643. assign$1(tagOptions, data);
  23644. }
  23645. assign$1(baseOptions, tagOptions); // Get tag children settings
  23646. if (tag.hasChildNodes()) {
  23647. var children = tag.childNodes;
  23648. for (var i = 0, j = children.length; i < j; i++) {
  23649. var child = children[i]; // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/
  23650. var childName = child.nodeName.toLowerCase();
  23651. if (childName === 'source') {
  23652. baseOptions.sources.push(getAttributes(child));
  23653. } else if (childName === 'track') {
  23654. baseOptions.tracks.push(getAttributes(child));
  23655. }
  23656. }
  23657. }
  23658. return baseOptions;
  23659. }
  23660. /**
  23661. * Determine whether or not flexbox is supported
  23662. *
  23663. * @return {boolean}
  23664. * - true if flexbox is supported
  23665. * - false if flexbox is not supported
  23666. */
  23667. ;
  23668. _proto.flexNotSupported_ = function flexNotSupported_() {
  23669. var elem = document.createElement('i'); // Note: We don't actually use flexBasis (or flexOrder), but it's one of the more
  23670. // common flex features that we can rely on when checking for flex support.
  23671. 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
  23672. 'msFlexOrder' in elem.style);
  23673. }
  23674. /**
  23675. * Set debug mode to enable/disable logs at info level.
  23676. *
  23677. * @param {boolean} enabled
  23678. * @fires Player#debugon
  23679. * @fires Player#debugoff
  23680. */
  23681. ;
  23682. _proto.debug = function debug(enabled) {
  23683. if (enabled === undefined) {
  23684. return this.debugEnabled_;
  23685. }
  23686. if (enabled) {
  23687. this.trigger('debugon');
  23688. this.previousLogLevel_ = this.log.level;
  23689. this.log.level('debug');
  23690. this.debugEnabled_ = true;
  23691. } else {
  23692. this.trigger('debugoff');
  23693. this.log.level(this.previousLogLevel_);
  23694. this.previousLogLevel_ = undefined;
  23695. this.debugEnabled_ = false;
  23696. }
  23697. }
  23698. /**
  23699. * Set or get current playback rates.
  23700. * Takes an array and updates the playback rates menu with the new items.
  23701. * Pass in an empty array to hide the menu.
  23702. * Values other than arrays are ignored.
  23703. *
  23704. * @fires Player#playbackrateschange
  23705. * @param {number[]} newRates
  23706. * The new rates that the playback rates menu should update to.
  23707. * An empty array will hide the menu
  23708. * @return {number[]} When used as a getter will return the current playback rates
  23709. */
  23710. ;
  23711. _proto.playbackRates = function playbackRates(newRates) {
  23712. if (newRates === undefined) {
  23713. return this.cache_.playbackRates;
  23714. } // ignore any value that isn't an array
  23715. if (!Array.isArray(newRates)) {
  23716. return;
  23717. } // ignore any arrays that don't only contain numbers
  23718. if (!newRates.every(function (rate) {
  23719. return typeof rate === 'number';
  23720. })) {
  23721. return;
  23722. }
  23723. this.cache_.playbackRates = newRates;
  23724. /**
  23725. * fires when the playback rates in a player are changed
  23726. *
  23727. * @event Player#playbackrateschange
  23728. * @type {EventTarget~Event}
  23729. */
  23730. this.trigger('playbackrateschange');
  23731. };
  23732. return Player;
  23733. }(Component$1);
  23734. /**
  23735. * Get the {@link VideoTrackList}
  23736. * @link https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist
  23737. *
  23738. * @return {VideoTrackList}
  23739. * the current video track list
  23740. *
  23741. * @method Player.prototype.videoTracks
  23742. */
  23743. /**
  23744. * Get the {@link AudioTrackList}
  23745. * @link https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist
  23746. *
  23747. * @return {AudioTrackList}
  23748. * the current audio track list
  23749. *
  23750. * @method Player.prototype.audioTracks
  23751. */
  23752. /**
  23753. * Get the {@link TextTrackList}
  23754. *
  23755. * @link http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks
  23756. *
  23757. * @return {TextTrackList}
  23758. * the current text track list
  23759. *
  23760. * @method Player.prototype.textTracks
  23761. */
  23762. /**
  23763. * Get the remote {@link TextTrackList}
  23764. *
  23765. * @return {TextTrackList}
  23766. * The current remote text track list
  23767. *
  23768. * @method Player.prototype.remoteTextTracks
  23769. */
  23770. /**
  23771. * Get the remote {@link HtmlTrackElementList} tracks.
  23772. *
  23773. * @return {HtmlTrackElementList}
  23774. * The current remote text track element list
  23775. *
  23776. * @method Player.prototype.remoteTextTrackEls
  23777. */
  23778. ALL.names.forEach(function (name) {
  23779. var props = ALL[name];
  23780. Player.prototype[props.getterName] = function () {
  23781. if (this.tech_) {
  23782. return this.tech_[props.getterName]();
  23783. } // if we have not yet loadTech_, we create {video,audio,text}Tracks_
  23784. // these will be passed to the tech during loading
  23785. this[props.privateName] = this[props.privateName] || new props.ListClass();
  23786. return this[props.privateName];
  23787. };
  23788. });
  23789. /**
  23790. * Get or set the `Player`'s crossorigin option. For the HTML5 player, this
  23791. * sets the `crossOrigin` property on the `<video>` tag to control the CORS
  23792. * behavior.
  23793. *
  23794. * @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
  23795. *
  23796. * @param {string} [value]
  23797. * The value to set the `Player`'s crossorigin to. If an argument is
  23798. * given, must be one of `anonymous` or `use-credentials`.
  23799. *
  23800. * @return {string|undefined}
  23801. * - The current crossorigin value of the `Player` when getting.
  23802. * - undefined when setting
  23803. */
  23804. Player.prototype.crossorigin = Player.prototype.crossOrigin;
  23805. /**
  23806. * Global enumeration of players.
  23807. *
  23808. * The keys are the player IDs and the values are either the {@link Player}
  23809. * instance or `null` for disposed players.
  23810. *
  23811. * @type {Object}
  23812. */
  23813. Player.players = {};
  23814. var navigator = window.navigator;
  23815. /*
  23816. * Player instance options, surfaced using options
  23817. * options = Player.prototype.options_
  23818. * Make changes in options, not here.
  23819. *
  23820. * @type {Object}
  23821. * @private
  23822. */
  23823. Player.prototype.options_ = {
  23824. // Default order of fallback technology
  23825. techOrder: Tech.defaultTechOrder_,
  23826. html5: {},
  23827. // default inactivity timeout
  23828. inactivityTimeout: 2000,
  23829. // default playback rates
  23830. playbackRates: [],
  23831. // Add playback rate selection by adding rates
  23832. // 'playbackRates': [0.5, 1, 1.5, 2],
  23833. liveui: false,
  23834. // Included control sets
  23835. children: ['mediaLoader', 'posterImage', 'textTrackDisplay', 'loadingSpinner', 'bigPlayButton', 'liveTracker', 'controlBar', 'errorDisplay', 'textTrackSettings', 'resizeManager'],
  23836. language: navigator && (navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language) || 'en',
  23837. // locales and their language translations
  23838. languages: {},
  23839. // Default message to show when a video cannot be played.
  23840. notSupportedMessage: 'No compatible source was found for this media.',
  23841. normalizeAutoplay: false,
  23842. fullscreen: {
  23843. options: {
  23844. navigationUI: 'hide'
  23845. }
  23846. },
  23847. breakpoints: {},
  23848. responsive: false,
  23849. audioOnlyMode: false,
  23850. audioPosterMode: false
  23851. };
  23852. [
  23853. /**
  23854. * Returns whether or not the player is in the "ended" state.
  23855. *
  23856. * @return {Boolean} True if the player is in the ended state, false if not.
  23857. * @method Player#ended
  23858. */
  23859. 'ended',
  23860. /**
  23861. * Returns whether or not the player is in the "seeking" state.
  23862. *
  23863. * @return {Boolean} True if the player is in the seeking state, false if not.
  23864. * @method Player#seeking
  23865. */
  23866. 'seeking',
  23867. /**
  23868. * Returns the TimeRanges of the media that are currently available
  23869. * for seeking to.
  23870. *
  23871. * @return {TimeRanges} the seekable intervals of the media timeline
  23872. * @method Player#seekable
  23873. */
  23874. 'seekable',
  23875. /**
  23876. * Returns the current state of network activity for the element, from
  23877. * the codes in the list below.
  23878. * - NETWORK_EMPTY (numeric value 0)
  23879. * The element has not yet been initialised. All attributes are in
  23880. * their initial states.
  23881. * - NETWORK_IDLE (numeric value 1)
  23882. * The element's resource selection algorithm is active and has
  23883. * selected a resource, but it is not actually using the network at
  23884. * this time.
  23885. * - NETWORK_LOADING (numeric value 2)
  23886. * The user agent is actively trying to download data.
  23887. * - NETWORK_NO_SOURCE (numeric value 3)
  23888. * The element's resource selection algorithm is active, but it has
  23889. * not yet found a resource to use.
  23890. *
  23891. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states
  23892. * @return {number} the current network activity state
  23893. * @method Player#networkState
  23894. */
  23895. 'networkState',
  23896. /**
  23897. * Returns a value that expresses the current state of the element
  23898. * with respect to rendering the current playback position, from the
  23899. * codes in the list below.
  23900. * - HAVE_NOTHING (numeric value 0)
  23901. * No information regarding the media resource is available.
  23902. * - HAVE_METADATA (numeric value 1)
  23903. * Enough of the resource has been obtained that the duration of the
  23904. * resource is available.
  23905. * - HAVE_CURRENT_DATA (numeric value 2)
  23906. * Data for the immediate current playback position is available.
  23907. * - HAVE_FUTURE_DATA (numeric value 3)
  23908. * Data for the immediate current playback position is available, as
  23909. * well as enough data for the user agent to advance the current
  23910. * playback position in the direction of playback.
  23911. * - HAVE_ENOUGH_DATA (numeric value 4)
  23912. * The user agent estimates that enough data is available for
  23913. * playback to proceed uninterrupted.
  23914. *
  23915. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate
  23916. * @return {number} the current playback rendering state
  23917. * @method Player#readyState
  23918. */
  23919. 'readyState'].forEach(function (fn) {
  23920. Player.prototype[fn] = function () {
  23921. return this.techGet_(fn);
  23922. };
  23923. });
  23924. TECH_EVENTS_RETRIGGER.forEach(function (event) {
  23925. Player.prototype["handleTech" + toTitleCase$1(event) + "_"] = function () {
  23926. return this.trigger(event);
  23927. };
  23928. });
  23929. /**
  23930. * Fired when the player has initial duration and dimension information
  23931. *
  23932. * @event Player#loadedmetadata
  23933. * @type {EventTarget~Event}
  23934. */
  23935. /**
  23936. * Fired when the player has downloaded data at the current playback position
  23937. *
  23938. * @event Player#loadeddata
  23939. * @type {EventTarget~Event}
  23940. */
  23941. /**
  23942. * Fired when the current playback position has changed *
  23943. * During playback this is fired every 15-250 milliseconds, depending on the
  23944. * playback technology in use.
  23945. *
  23946. * @event Player#timeupdate
  23947. * @type {EventTarget~Event}
  23948. */
  23949. /**
  23950. * Fired when the volume changes
  23951. *
  23952. * @event Player#volumechange
  23953. * @type {EventTarget~Event}
  23954. */
  23955. /**
  23956. * Reports whether or not a player has a plugin available.
  23957. *
  23958. * This does not report whether or not the plugin has ever been initialized
  23959. * on this player. For that, [usingPlugin]{@link Player#usingPlugin}.
  23960. *
  23961. * @method Player#hasPlugin
  23962. * @param {string} name
  23963. * The name of a plugin.
  23964. *
  23965. * @return {boolean}
  23966. * Whether or not this player has the requested plugin available.
  23967. */
  23968. /**
  23969. * Reports whether or not a player is using a plugin by name.
  23970. *
  23971. * For basic plugins, this only reports whether the plugin has _ever_ been
  23972. * initialized on this player.
  23973. *
  23974. * @method Player#usingPlugin
  23975. * @param {string} name
  23976. * The name of a plugin.
  23977. *
  23978. * @return {boolean}
  23979. * Whether or not this player is using the requested plugin.
  23980. */
  23981. Component$1.registerComponent('Player', Player);
  23982. var setPrototypeOf = createCommonjsModule(function (module) {
  23983. function _setPrototypeOf(o, p) {
  23984. module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  23985. o.__proto__ = p;
  23986. return o;
  23987. };
  23988. return _setPrototypeOf(o, p);
  23989. }
  23990. module.exports = _setPrototypeOf;
  23991. });
  23992. function _isNativeReflectConstruct() {
  23993. if (typeof Reflect === "undefined" || !Reflect.construct) return false;
  23994. if (Reflect.construct.sham) return false;
  23995. if (typeof Proxy === "function") return true;
  23996. try {
  23997. Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
  23998. return true;
  23999. } catch (e) {
  24000. return false;
  24001. }
  24002. }
  24003. var isNativeReflectConstruct = _isNativeReflectConstruct;
  24004. var construct = createCommonjsModule(function (module) {
  24005. function _construct(Parent, args, Class) {
  24006. if (isNativeReflectConstruct()) {
  24007. module.exports = _construct = Reflect.construct;
  24008. } else {
  24009. module.exports = _construct = function _construct(Parent, args, Class) {
  24010. var a = [null];
  24011. a.push.apply(a, args);
  24012. var Constructor = Function.bind.apply(Parent, a);
  24013. var instance = new Constructor();
  24014. if (Class) setPrototypeOf(instance, Class.prototype);
  24015. return instance;
  24016. };
  24017. }
  24018. return _construct.apply(null, arguments);
  24019. }
  24020. module.exports = _construct;
  24021. });
  24022. /**
  24023. * The base plugin name.
  24024. *
  24025. * @private
  24026. * @constant
  24027. * @type {string}
  24028. */
  24029. var BASE_PLUGIN_NAME = 'plugin';
  24030. /**
  24031. * The key on which a player's active plugins cache is stored.
  24032. *
  24033. * @private
  24034. * @constant
  24035. * @type {string}
  24036. */
  24037. var PLUGIN_CACHE_KEY = 'activePlugins_';
  24038. /**
  24039. * Stores registered plugins in a private space.
  24040. *
  24041. * @private
  24042. * @type {Object}
  24043. */
  24044. var pluginStorage = {};
  24045. /**
  24046. * Reports whether or not a plugin has been registered.
  24047. *
  24048. * @private
  24049. * @param {string} name
  24050. * The name of a plugin.
  24051. *
  24052. * @return {boolean}
  24053. * Whether or not the plugin has been registered.
  24054. */
  24055. var pluginExists = function pluginExists(name) {
  24056. return pluginStorage.hasOwnProperty(name);
  24057. };
  24058. /**
  24059. * Get a single registered plugin by name.
  24060. *
  24061. * @private
  24062. * @param {string} name
  24063. * The name of a plugin.
  24064. *
  24065. * @return {Function|undefined}
  24066. * The plugin (or undefined).
  24067. */
  24068. var getPlugin = function getPlugin(name) {
  24069. return pluginExists(name) ? pluginStorage[name] : undefined;
  24070. };
  24071. /**
  24072. * Marks a plugin as "active" on a player.
  24073. *
  24074. * Also, ensures that the player has an object for tracking active plugins.
  24075. *
  24076. * @private
  24077. * @param {Player} player
  24078. * A Video.js player instance.
  24079. *
  24080. * @param {string} name
  24081. * The name of a plugin.
  24082. */
  24083. var markPluginAsActive = function markPluginAsActive(player, name) {
  24084. player[PLUGIN_CACHE_KEY] = player[PLUGIN_CACHE_KEY] || {};
  24085. player[PLUGIN_CACHE_KEY][name] = true;
  24086. };
  24087. /**
  24088. * Triggers a pair of plugin setup events.
  24089. *
  24090. * @private
  24091. * @param {Player} player
  24092. * A Video.js player instance.
  24093. *
  24094. * @param {Plugin~PluginEventHash} hash
  24095. * A plugin event hash.
  24096. *
  24097. * @param {boolean} [before]
  24098. * If true, prefixes the event name with "before". In other words,
  24099. * use this to trigger "beforepluginsetup" instead of "pluginsetup".
  24100. */
  24101. var triggerSetupEvent = function triggerSetupEvent(player, hash, before) {
  24102. var eventName = (before ? 'before' : '') + 'pluginsetup';
  24103. player.trigger(eventName, hash);
  24104. player.trigger(eventName + ':' + hash.name, hash);
  24105. };
  24106. /**
  24107. * Takes a basic plugin function and returns a wrapper function which marks
  24108. * on the player that the plugin has been activated.
  24109. *
  24110. * @private
  24111. * @param {string} name
  24112. * The name of the plugin.
  24113. *
  24114. * @param {Function} plugin
  24115. * The basic plugin.
  24116. *
  24117. * @return {Function}
  24118. * A wrapper function for the given plugin.
  24119. */
  24120. var createBasicPlugin = function createBasicPlugin(name, plugin) {
  24121. var basicPluginWrapper = function basicPluginWrapper() {
  24122. // We trigger the "beforepluginsetup" and "pluginsetup" events on the player
  24123. // regardless, but we want the hash to be consistent with the hash provided
  24124. // for advanced plugins.
  24125. //
  24126. // The only potentially counter-intuitive thing here is the `instance` in
  24127. // the "pluginsetup" event is the value returned by the `plugin` function.
  24128. triggerSetupEvent(this, {
  24129. name: name,
  24130. plugin: plugin,
  24131. instance: null
  24132. }, true);
  24133. var instance = plugin.apply(this, arguments);
  24134. markPluginAsActive(this, name);
  24135. triggerSetupEvent(this, {
  24136. name: name,
  24137. plugin: plugin,
  24138. instance: instance
  24139. });
  24140. return instance;
  24141. };
  24142. Object.keys(plugin).forEach(function (prop) {
  24143. basicPluginWrapper[prop] = plugin[prop];
  24144. });
  24145. return basicPluginWrapper;
  24146. };
  24147. /**
  24148. * Takes a plugin sub-class and returns a factory function for generating
  24149. * instances of it.
  24150. *
  24151. * This factory function will replace itself with an instance of the requested
  24152. * sub-class of Plugin.
  24153. *
  24154. * @private
  24155. * @param {string} name
  24156. * The name of the plugin.
  24157. *
  24158. * @param {Plugin} PluginSubClass
  24159. * The advanced plugin.
  24160. *
  24161. * @return {Function}
  24162. */
  24163. var createPluginFactory = function createPluginFactory(name, PluginSubClass) {
  24164. // Add a `name` property to the plugin prototype so that each plugin can
  24165. // refer to itself by name.
  24166. PluginSubClass.prototype.name = name;
  24167. return function () {
  24168. triggerSetupEvent(this, {
  24169. name: name,
  24170. plugin: PluginSubClass,
  24171. instance: null
  24172. }, true);
  24173. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  24174. args[_key] = arguments[_key];
  24175. }
  24176. var instance = construct(PluginSubClass, [this].concat(args)); // The plugin is replaced by a function that returns the current instance.
  24177. this[name] = function () {
  24178. return instance;
  24179. };
  24180. triggerSetupEvent(this, instance.getEventHash());
  24181. return instance;
  24182. };
  24183. };
  24184. /**
  24185. * Parent class for all advanced plugins.
  24186. *
  24187. * @mixes module:evented~EventedMixin
  24188. * @mixes module:stateful~StatefulMixin
  24189. * @fires Player#beforepluginsetup
  24190. * @fires Player#beforepluginsetup:$name
  24191. * @fires Player#pluginsetup
  24192. * @fires Player#pluginsetup:$name
  24193. * @listens Player#dispose
  24194. * @throws {Error}
  24195. * If attempting to instantiate the base {@link Plugin} class
  24196. * directly instead of via a sub-class.
  24197. */
  24198. var Plugin = /*#__PURE__*/function () {
  24199. /**
  24200. * Creates an instance of this class.
  24201. *
  24202. * Sub-classes should call `super` to ensure plugins are properly initialized.
  24203. *
  24204. * @param {Player} player
  24205. * A Video.js player instance.
  24206. */
  24207. function Plugin(player) {
  24208. if (this.constructor === Plugin) {
  24209. throw new Error('Plugin must be sub-classed; not directly instantiated.');
  24210. }
  24211. this.player = player;
  24212. if (!this.log) {
  24213. this.log = this.player.log.createLogger(this.name);
  24214. } // Make this object evented, but remove the added `trigger` method so we
  24215. // use the prototype version instead.
  24216. evented(this);
  24217. delete this.trigger;
  24218. stateful(this, this.constructor.defaultState);
  24219. markPluginAsActive(player, this.name); // Auto-bind the dispose method so we can use it as a listener and unbind
  24220. // it later easily.
  24221. this.dispose = this.dispose.bind(this); // If the player is disposed, dispose the plugin.
  24222. player.on('dispose', this.dispose);
  24223. }
  24224. /**
  24225. * Get the version of the plugin that was set on <pluginName>.VERSION
  24226. */
  24227. var _proto = Plugin.prototype;
  24228. _proto.version = function version() {
  24229. return this.constructor.VERSION;
  24230. }
  24231. /**
  24232. * Each event triggered by plugins includes a hash of additional data with
  24233. * conventional properties.
  24234. *
  24235. * This returns that object or mutates an existing hash.
  24236. *
  24237. * @param {Object} [hash={}]
  24238. * An object to be used as event an event hash.
  24239. *
  24240. * @return {Plugin~PluginEventHash}
  24241. * An event hash object with provided properties mixed-in.
  24242. */
  24243. ;
  24244. _proto.getEventHash = function getEventHash(hash) {
  24245. if (hash === void 0) {
  24246. hash = {};
  24247. }
  24248. hash.name = this.name;
  24249. hash.plugin = this.constructor;
  24250. hash.instance = this;
  24251. return hash;
  24252. }
  24253. /**
  24254. * Triggers an event on the plugin object and overrides
  24255. * {@link module:evented~EventedMixin.trigger|EventedMixin.trigger}.
  24256. *
  24257. * @param {string|Object} event
  24258. * An event type or an object with a type property.
  24259. *
  24260. * @param {Object} [hash={}]
  24261. * Additional data hash to merge with a
  24262. * {@link Plugin~PluginEventHash|PluginEventHash}.
  24263. *
  24264. * @return {boolean}
  24265. * Whether or not default was prevented.
  24266. */
  24267. ;
  24268. _proto.trigger = function trigger$1(event, hash) {
  24269. if (hash === void 0) {
  24270. hash = {};
  24271. }
  24272. return trigger(this.eventBusEl_, event, this.getEventHash(hash));
  24273. }
  24274. /**
  24275. * Handles "statechanged" events on the plugin. No-op by default, override by
  24276. * subclassing.
  24277. *
  24278. * @abstract
  24279. * @param {Event} e
  24280. * An event object provided by a "statechanged" event.
  24281. *
  24282. * @param {Object} e.changes
  24283. * An object describing changes that occurred with the "statechanged"
  24284. * event.
  24285. */
  24286. ;
  24287. _proto.handleStateChanged = function handleStateChanged(e) {}
  24288. /**
  24289. * Disposes a plugin.
  24290. *
  24291. * Subclasses can override this if they want, but for the sake of safety,
  24292. * it's probably best to subscribe the "dispose" event.
  24293. *
  24294. * @fires Plugin#dispose
  24295. */
  24296. ;
  24297. _proto.dispose = function dispose() {
  24298. var name = this.name,
  24299. player = this.player;
  24300. /**
  24301. * Signals that a advanced plugin is about to be disposed.
  24302. *
  24303. * @event Plugin#dispose
  24304. * @type {EventTarget~Event}
  24305. */
  24306. this.trigger('dispose');
  24307. this.off();
  24308. player.off('dispose', this.dispose); // Eliminate any possible sources of leaking memory by clearing up
  24309. // references between the player and the plugin instance and nulling out
  24310. // the plugin's state and replacing methods with a function that throws.
  24311. player[PLUGIN_CACHE_KEY][name] = false;
  24312. this.player = this.state = null; // Finally, replace the plugin name on the player with a new factory
  24313. // function, so that the plugin is ready to be set up again.
  24314. player[name] = createPluginFactory(name, pluginStorage[name]);
  24315. }
  24316. /**
  24317. * Determines if a plugin is a basic plugin (i.e. not a sub-class of `Plugin`).
  24318. *
  24319. * @param {string|Function} plugin
  24320. * If a string, matches the name of a plugin. If a function, will be
  24321. * tested directly.
  24322. *
  24323. * @return {boolean}
  24324. * Whether or not a plugin is a basic plugin.
  24325. */
  24326. ;
  24327. Plugin.isBasic = function isBasic(plugin) {
  24328. var p = typeof plugin === 'string' ? getPlugin(plugin) : plugin;
  24329. return typeof p === 'function' && !Plugin.prototype.isPrototypeOf(p.prototype);
  24330. }
  24331. /**
  24332. * Register a Video.js plugin.
  24333. *
  24334. * @param {string} name
  24335. * The name of the plugin to be registered. Must be a string and
  24336. * must not match an existing plugin or a method on the `Player`
  24337. * prototype.
  24338. *
  24339. * @param {Function} plugin
  24340. * A sub-class of `Plugin` or a function for basic plugins.
  24341. *
  24342. * @return {Function}
  24343. * For advanced plugins, a factory function for that plugin. For
  24344. * basic plugins, a wrapper function that initializes the plugin.
  24345. */
  24346. ;
  24347. Plugin.registerPlugin = function registerPlugin(name, plugin) {
  24348. if (typeof name !== 'string') {
  24349. throw new Error("Illegal plugin name, \"" + name + "\", must be a string, was " + typeof name + ".");
  24350. }
  24351. if (pluginExists(name)) {
  24352. log$1.warn("A plugin named \"" + name + "\" already exists. You may want to avoid re-registering plugins!");
  24353. } else if (Player.prototype.hasOwnProperty(name)) {
  24354. throw new Error("Illegal plugin name, \"" + name + "\", cannot share a name with an existing player method!");
  24355. }
  24356. if (typeof plugin !== 'function') {
  24357. throw new Error("Illegal plugin for \"" + name + "\", must be a function, was " + typeof plugin + ".");
  24358. }
  24359. pluginStorage[name] = plugin; // Add a player prototype method for all sub-classed plugins (but not for
  24360. // the base Plugin class).
  24361. if (name !== BASE_PLUGIN_NAME) {
  24362. if (Plugin.isBasic(plugin)) {
  24363. Player.prototype[name] = createBasicPlugin(name, plugin);
  24364. } else {
  24365. Player.prototype[name] = createPluginFactory(name, plugin);
  24366. }
  24367. }
  24368. return plugin;
  24369. }
  24370. /**
  24371. * De-register a Video.js plugin.
  24372. *
  24373. * @param {string} name
  24374. * The name of the plugin to be de-registered. Must be a string that
  24375. * matches an existing plugin.
  24376. *
  24377. * @throws {Error}
  24378. * If an attempt is made to de-register the base plugin.
  24379. */
  24380. ;
  24381. Plugin.deregisterPlugin = function deregisterPlugin(name) {
  24382. if (name === BASE_PLUGIN_NAME) {
  24383. throw new Error('Cannot de-register base plugin.');
  24384. }
  24385. if (pluginExists(name)) {
  24386. delete pluginStorage[name];
  24387. delete Player.prototype[name];
  24388. }
  24389. }
  24390. /**
  24391. * Gets an object containing multiple Video.js plugins.
  24392. *
  24393. * @param {Array} [names]
  24394. * If provided, should be an array of plugin names. Defaults to _all_
  24395. * plugin names.
  24396. *
  24397. * @return {Object|undefined}
  24398. * An object containing plugin(s) associated with their name(s) or
  24399. * `undefined` if no matching plugins exist).
  24400. */
  24401. ;
  24402. Plugin.getPlugins = function getPlugins(names) {
  24403. if (names === void 0) {
  24404. names = Object.keys(pluginStorage);
  24405. }
  24406. var result;
  24407. names.forEach(function (name) {
  24408. var plugin = getPlugin(name);
  24409. if (plugin) {
  24410. result = result || {};
  24411. result[name] = plugin;
  24412. }
  24413. });
  24414. return result;
  24415. }
  24416. /**
  24417. * Gets a plugin's version, if available
  24418. *
  24419. * @param {string} name
  24420. * The name of a plugin.
  24421. *
  24422. * @return {string}
  24423. * The plugin's version or an empty string.
  24424. */
  24425. ;
  24426. Plugin.getPluginVersion = function getPluginVersion(name) {
  24427. var plugin = getPlugin(name);
  24428. return plugin && plugin.VERSION || '';
  24429. };
  24430. return Plugin;
  24431. }();
  24432. /**
  24433. * Gets a plugin by name if it exists.
  24434. *
  24435. * @static
  24436. * @method getPlugin
  24437. * @memberOf Plugin
  24438. * @param {string} name
  24439. * The name of a plugin.
  24440. *
  24441. * @returns {Function|undefined}
  24442. * The plugin (or `undefined`).
  24443. */
  24444. Plugin.getPlugin = getPlugin;
  24445. /**
  24446. * The name of the base plugin class as it is registered.
  24447. *
  24448. * @type {string}
  24449. */
  24450. Plugin.BASE_PLUGIN_NAME = BASE_PLUGIN_NAME;
  24451. Plugin.registerPlugin(BASE_PLUGIN_NAME, Plugin);
  24452. /**
  24453. * Documented in player.js
  24454. *
  24455. * @ignore
  24456. */
  24457. Player.prototype.usingPlugin = function (name) {
  24458. return !!this[PLUGIN_CACHE_KEY] && this[PLUGIN_CACHE_KEY][name] === true;
  24459. };
  24460. /**
  24461. * Documented in player.js
  24462. *
  24463. * @ignore
  24464. */
  24465. Player.prototype.hasPlugin = function (name) {
  24466. return !!pluginExists(name);
  24467. };
  24468. /**
  24469. * Signals that a plugin is about to be set up on a player.
  24470. *
  24471. * @event Player#beforepluginsetup
  24472. * @type {Plugin~PluginEventHash}
  24473. */
  24474. /**
  24475. * Signals that a plugin is about to be set up on a player - by name. The name
  24476. * is the name of the plugin.
  24477. *
  24478. * @event Player#beforepluginsetup:$name
  24479. * @type {Plugin~PluginEventHash}
  24480. */
  24481. /**
  24482. * Signals that a plugin has just been set up on a player.
  24483. *
  24484. * @event Player#pluginsetup
  24485. * @type {Plugin~PluginEventHash}
  24486. */
  24487. /**
  24488. * Signals that a plugin has just been set up on a player - by name. The name
  24489. * is the name of the plugin.
  24490. *
  24491. * @event Player#pluginsetup:$name
  24492. * @type {Plugin~PluginEventHash}
  24493. */
  24494. /**
  24495. * @typedef {Object} Plugin~PluginEventHash
  24496. *
  24497. * @property {string} instance
  24498. * For basic plugins, the return value of the plugin function. For
  24499. * advanced plugins, the plugin instance on which the event is fired.
  24500. *
  24501. * @property {string} name
  24502. * The name of the plugin.
  24503. *
  24504. * @property {string} plugin
  24505. * For basic plugins, the plugin function. For advanced plugins, the
  24506. * plugin class/constructor.
  24507. */
  24508. function _inherits(subClass, superClass) {
  24509. if (typeof superClass !== "function" && superClass !== null) {
  24510. throw new TypeError("Super expression must either be null or a function");
  24511. }
  24512. subClass.prototype = Object.create(superClass && superClass.prototype, {
  24513. constructor: {
  24514. value: subClass,
  24515. writable: true,
  24516. configurable: true
  24517. }
  24518. });
  24519. if (superClass) setPrototypeOf(subClass, superClass);
  24520. }
  24521. var inherits = _inherits;
  24522. /**
  24523. * @file extend.js
  24524. * @module extend
  24525. */
  24526. var hasLogged = false;
  24527. /**
  24528. * Used to subclass an existing class by emulating ES subclassing using the
  24529. * `extends` keyword.
  24530. *
  24531. * @function
  24532. * @deprecated
  24533. * @example
  24534. * var MyComponent = videojs.extend(videojs.getComponent('Component'), {
  24535. * myCustomMethod: function() {
  24536. * // Do things in my method.
  24537. * }
  24538. * });
  24539. *
  24540. * @param {Function} superClass
  24541. * The class to inherit from
  24542. *
  24543. * @param {Object} [subClassMethods={}]
  24544. * Methods of the new class
  24545. *
  24546. * @return {Function}
  24547. * The new class with subClassMethods that inherited superClass.
  24548. */
  24549. var extend = function extend(superClass, subClassMethods) {
  24550. if (subClassMethods === void 0) {
  24551. subClassMethods = {};
  24552. }
  24553. // Log a warning the first time extend is called to note that it is deprecated
  24554. // It was previously deprecated in our documentation (guides, specifically),
  24555. // but was never formally deprecated in code.
  24556. if (!hasLogged) {
  24557. log$1.warn('videojs.extend is deprecated as of Video.js 7.22.0 and will be removed in Video.js 8.0.0');
  24558. hasLogged = true;
  24559. }
  24560. var subClass = function subClass() {
  24561. superClass.apply(this, arguments);
  24562. };
  24563. var methods = {};
  24564. if (typeof subClassMethods === 'object') {
  24565. if (subClassMethods.constructor !== Object.prototype.constructor) {
  24566. subClass = subClassMethods.constructor;
  24567. }
  24568. methods = subClassMethods;
  24569. } else if (typeof subClassMethods === 'function') {
  24570. subClass = subClassMethods;
  24571. }
  24572. inherits(subClass, superClass); // this is needed for backward-compatibility and node compatibility.
  24573. if (superClass) {
  24574. subClass.super_ = superClass;
  24575. } // Extend subObj's prototype with functions and other properties from props
  24576. for (var name in methods) {
  24577. if (methods.hasOwnProperty(name)) {
  24578. subClass.prototype[name] = methods[name];
  24579. }
  24580. }
  24581. return subClass;
  24582. };
  24583. /**
  24584. * @file video.js
  24585. * @module videojs
  24586. */
  24587. /**
  24588. * Normalize an `id` value by trimming off a leading `#`
  24589. *
  24590. * @private
  24591. * @param {string} id
  24592. * A string, maybe with a leading `#`.
  24593. *
  24594. * @return {string}
  24595. * The string, without any leading `#`.
  24596. */
  24597. var normalizeId = function normalizeId(id) {
  24598. return id.indexOf('#') === 0 ? id.slice(1) : id;
  24599. };
  24600. /**
  24601. * The `videojs()` function doubles as the main function for users to create a
  24602. * {@link Player} instance as well as the main library namespace.
  24603. *
  24604. * It can also be used as a getter for a pre-existing {@link Player} instance.
  24605. * However, we _strongly_ recommend using `videojs.getPlayer()` for this
  24606. * purpose because it avoids any potential for unintended initialization.
  24607. *
  24608. * Due to [limitations](https://github.com/jsdoc3/jsdoc/issues/955#issuecomment-313829149)
  24609. * of our JSDoc template, we cannot properly document this as both a function
  24610. * and a namespace, so its function signature is documented here.
  24611. *
  24612. * #### Arguments
  24613. * ##### id
  24614. * string|Element, **required**
  24615. *
  24616. * Video element or video element ID.
  24617. *
  24618. * ##### options
  24619. * Object, optional
  24620. *
  24621. * Options object for providing settings.
  24622. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).
  24623. *
  24624. * ##### ready
  24625. * {@link Component~ReadyCallback}, optional
  24626. *
  24627. * A function to be called when the {@link Player} and {@link Tech} are ready.
  24628. *
  24629. * #### Return Value
  24630. *
  24631. * The `videojs()` function returns a {@link Player} instance.
  24632. *
  24633. * @namespace
  24634. *
  24635. * @borrows AudioTrack as AudioTrack
  24636. * @borrows Component.getComponent as getComponent
  24637. * @borrows module:computed-style~computedStyle as computedStyle
  24638. * @borrows module:events.on as on
  24639. * @borrows module:events.one as one
  24640. * @borrows module:events.off as off
  24641. * @borrows module:events.trigger as trigger
  24642. * @borrows EventTarget as EventTarget
  24643. * @borrows module:extend~extend as extend
  24644. * @borrows module:fn.bind as bind
  24645. * @borrows module:format-time.formatTime as formatTime
  24646. * @borrows module:format-time.resetFormatTime as resetFormatTime
  24647. * @borrows module:format-time.setFormatTime as setFormatTime
  24648. * @borrows module:merge-options.mergeOptions as mergeOptions
  24649. * @borrows module:middleware.use as use
  24650. * @borrows Player.players as players
  24651. * @borrows Plugin.registerPlugin as registerPlugin
  24652. * @borrows Plugin.deregisterPlugin as deregisterPlugin
  24653. * @borrows Plugin.getPlugins as getPlugins
  24654. * @borrows Plugin.getPlugin as getPlugin
  24655. * @borrows Plugin.getPluginVersion as getPluginVersion
  24656. * @borrows Tech.getTech as getTech
  24657. * @borrows Tech.registerTech as registerTech
  24658. * @borrows TextTrack as TextTrack
  24659. * @borrows module:time-ranges.createTimeRanges as createTimeRange
  24660. * @borrows module:time-ranges.createTimeRanges as createTimeRanges
  24661. * @borrows module:url.isCrossOrigin as isCrossOrigin
  24662. * @borrows module:url.parseUrl as parseUrl
  24663. * @borrows VideoTrack as VideoTrack
  24664. *
  24665. * @param {string|Element} id
  24666. * Video element or video element ID.
  24667. *
  24668. * @param {Object} [options]
  24669. * Options object for providing settings.
  24670. * See: [Options Guide](https://docs.videojs.com/tutorial-options.html).
  24671. *
  24672. * @param {Component~ReadyCallback} [ready]
  24673. * A function to be called when the {@link Player} and {@link Tech} are
  24674. * ready.
  24675. *
  24676. * @return {Player}
  24677. * The `videojs()` function returns a {@link Player|Player} instance.
  24678. */
  24679. function videojs(id, options, ready) {
  24680. var player = videojs.getPlayer(id);
  24681. if (player) {
  24682. if (options) {
  24683. log$1.warn("Player \"" + id + "\" is already initialised. Options will not be applied.");
  24684. }
  24685. if (ready) {
  24686. player.ready(ready);
  24687. }
  24688. return player;
  24689. }
  24690. var el = typeof id === 'string' ? $('#' + normalizeId(id)) : id;
  24691. if (!isEl(el)) {
  24692. throw new TypeError('The element or ID supplied is not valid. (videojs)');
  24693. } // document.body.contains(el) will only check if el is contained within that one document.
  24694. // This causes problems for elements in iframes.
  24695. // Instead, use the element's ownerDocument instead of the global document.
  24696. // This will make sure that the element is indeed in the dom of that document.
  24697. // Additionally, check that the document in question has a default view.
  24698. // If the document is no longer attached to the dom, the defaultView of the document will be null.
  24699. if (!el.ownerDocument.defaultView || !el.ownerDocument.body.contains(el)) {
  24700. log$1.warn('The element supplied is not included in the DOM');
  24701. }
  24702. options = options || {}; // Store a copy of the el before modification, if it is to be restored in destroy()
  24703. // If div ingest, store the parent div
  24704. if (options.restoreEl === true) {
  24705. options.restoreEl = (el.parentNode && el.parentNode.hasAttribute('data-vjs-player') ? el.parentNode : el).cloneNode(true);
  24706. }
  24707. hooks('beforesetup').forEach(function (hookFunction) {
  24708. var opts = hookFunction(el, mergeOptions$3(options));
  24709. if (!isObject$1(opts) || Array.isArray(opts)) {
  24710. log$1.error('please return an object in beforesetup hooks');
  24711. return;
  24712. }
  24713. options = mergeOptions$3(options, opts);
  24714. }); // We get the current "Player" component here in case an integration has
  24715. // replaced it with a custom player.
  24716. var PlayerComponent = Component$1.getComponent('Player');
  24717. player = new PlayerComponent(el, options, ready);
  24718. hooks('setup').forEach(function (hookFunction) {
  24719. return hookFunction(player);
  24720. });
  24721. return player;
  24722. }
  24723. videojs.hooks_ = hooks_;
  24724. videojs.hooks = hooks;
  24725. videojs.hook = hook;
  24726. videojs.hookOnce = hookOnce;
  24727. videojs.removeHook = removeHook; // Add default styles
  24728. if (window.VIDEOJS_NO_DYNAMIC_STYLE !== true && isReal()) {
  24729. var style = $('.vjs-styles-defaults');
  24730. if (!style) {
  24731. style = createStyleElement('vjs-styles-defaults');
  24732. var head = $('head');
  24733. if (head) {
  24734. head.insertBefore(style, head.firstChild);
  24735. }
  24736. 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 ");
  24737. }
  24738. } // Run Auto-load players
  24739. // You have to wait at least once in case this script is loaded after your
  24740. // video in the DOM (weird behavior only with minified version)
  24741. autoSetupTimeout(1, videojs);
  24742. /**
  24743. * Current Video.js version. Follows [semantic versioning](https://semver.org/).
  24744. *
  24745. * @type {string}
  24746. */
  24747. videojs.VERSION = version$5;
  24748. /**
  24749. * The global options object. These are the settings that take effect
  24750. * if no overrides are specified when the player is created.
  24751. *
  24752. * @type {Object}
  24753. */
  24754. videojs.options = Player.prototype.options_;
  24755. /**
  24756. * Get an object with the currently created players, keyed by player ID
  24757. *
  24758. * @return {Object}
  24759. * The created players
  24760. */
  24761. videojs.getPlayers = function () {
  24762. return Player.players;
  24763. };
  24764. /**
  24765. * Get a single player based on an ID or DOM element.
  24766. *
  24767. * This is useful if you want to check if an element or ID has an associated
  24768. * Video.js player, but not create one if it doesn't.
  24769. *
  24770. * @param {string|Element} id
  24771. * An HTML element - `<video>`, `<audio>`, or `<video-js>` -
  24772. * or a string matching the `id` of such an element.
  24773. *
  24774. * @return {Player|undefined}
  24775. * A player instance or `undefined` if there is no player instance
  24776. * matching the argument.
  24777. */
  24778. videojs.getPlayer = function (id) {
  24779. var players = Player.players;
  24780. var tag;
  24781. if (typeof id === 'string') {
  24782. var nId = normalizeId(id);
  24783. var player = players[nId];
  24784. if (player) {
  24785. return player;
  24786. }
  24787. tag = $('#' + nId);
  24788. } else {
  24789. tag = id;
  24790. }
  24791. if (isEl(tag)) {
  24792. var _tag = tag,
  24793. _player = _tag.player,
  24794. playerId = _tag.playerId; // Element may have a `player` property referring to an already created
  24795. // player instance. If so, return that.
  24796. if (_player || players[playerId]) {
  24797. return _player || players[playerId];
  24798. }
  24799. }
  24800. };
  24801. /**
  24802. * Returns an array of all current players.
  24803. *
  24804. * @return {Array}
  24805. * An array of all players. The array will be in the order that
  24806. * `Object.keys` provides, which could potentially vary between
  24807. * JavaScript engines.
  24808. *
  24809. */
  24810. videojs.getAllPlayers = function () {
  24811. return (// Disposed players leave a key with a `null` value, so we need to make sure
  24812. // we filter those out.
  24813. Object.keys(Player.players).map(function (k) {
  24814. return Player.players[k];
  24815. }).filter(Boolean)
  24816. );
  24817. };
  24818. videojs.players = Player.players;
  24819. videojs.getComponent = Component$1.getComponent;
  24820. /**
  24821. * Register a component so it can referred to by name. Used when adding to other
  24822. * components, either through addChild `component.addChild('myComponent')` or through
  24823. * default children options `{ children: ['myComponent'] }`.
  24824. *
  24825. * > NOTE: You could also just initialize the component before adding.
  24826. * `component.addChild(new MyComponent());`
  24827. *
  24828. * @param {string} name
  24829. * The class name of the component
  24830. *
  24831. * @param {Component} comp
  24832. * The component class
  24833. *
  24834. * @return {Component}
  24835. * The newly registered component
  24836. */
  24837. videojs.registerComponent = function (name, comp) {
  24838. if (Tech.isTech(comp)) {
  24839. log$1.warn("The " + name + " tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)");
  24840. }
  24841. Component$1.registerComponent.call(Component$1, name, comp);
  24842. };
  24843. videojs.getTech = Tech.getTech;
  24844. videojs.registerTech = Tech.registerTech;
  24845. videojs.use = use;
  24846. /**
  24847. * An object that can be returned by a middleware to signify
  24848. * that the middleware is being terminated.
  24849. *
  24850. * @type {object}
  24851. * @property {object} middleware.TERMINATOR
  24852. */
  24853. Object.defineProperty(videojs, 'middleware', {
  24854. value: {},
  24855. writeable: false,
  24856. enumerable: true
  24857. });
  24858. Object.defineProperty(videojs.middleware, 'TERMINATOR', {
  24859. value: TERMINATOR,
  24860. writeable: false,
  24861. enumerable: true
  24862. });
  24863. /**
  24864. * A reference to the {@link module:browser|browser utility module} as an object.
  24865. *
  24866. * @type {Object}
  24867. * @see {@link module:browser|browser}
  24868. */
  24869. videojs.browser = browser;
  24870. /**
  24871. * Use {@link module:browser.TOUCH_ENABLED|browser.TOUCH_ENABLED} instead; only
  24872. * included for backward-compatibility with 4.x.
  24873. *
  24874. * @deprecated Since version 5.0, use {@link module:browser.TOUCH_ENABLED|browser.TOUCH_ENABLED instead.
  24875. * @type {boolean}
  24876. */
  24877. videojs.TOUCH_ENABLED = TOUCH_ENABLED;
  24878. videojs.extend = extend;
  24879. videojs.mergeOptions = mergeOptions$3;
  24880. videojs.bind = bind;
  24881. videojs.registerPlugin = Plugin.registerPlugin;
  24882. videojs.deregisterPlugin = Plugin.deregisterPlugin;
  24883. /**
  24884. * Deprecated method to register a plugin with Video.js
  24885. *
  24886. * @deprecated videojs.plugin() is deprecated; use videojs.registerPlugin() instead
  24887. *
  24888. * @param {string} name
  24889. * The plugin name
  24890. *
  24891. * @param {Plugin|Function} plugin
  24892. * The plugin sub-class or function
  24893. */
  24894. videojs.plugin = function (name, plugin) {
  24895. log$1.warn('videojs.plugin() is deprecated; use videojs.registerPlugin() instead');
  24896. return Plugin.registerPlugin(name, plugin);
  24897. };
  24898. videojs.getPlugins = Plugin.getPlugins;
  24899. videojs.getPlugin = Plugin.getPlugin;
  24900. videojs.getPluginVersion = Plugin.getPluginVersion;
  24901. /**
  24902. * Adding languages so that they're available to all players.
  24903. * Example: `videojs.addLanguage('es', { 'Hello': 'Hola' });`
  24904. *
  24905. * @param {string} code
  24906. * The language code or dictionary property
  24907. *
  24908. * @param {Object} data
  24909. * The data values to be translated
  24910. *
  24911. * @return {Object}
  24912. * The resulting language dictionary object
  24913. */
  24914. videojs.addLanguage = function (code, data) {
  24915. var _mergeOptions;
  24916. code = ('' + code).toLowerCase();
  24917. videojs.options.languages = mergeOptions$3(videojs.options.languages, (_mergeOptions = {}, _mergeOptions[code] = data, _mergeOptions));
  24918. return videojs.options.languages[code];
  24919. };
  24920. /**
  24921. * A reference to the {@link module:log|log utility module} as an object.
  24922. *
  24923. * @type {Function}
  24924. * @see {@link module:log|log}
  24925. */
  24926. videojs.log = log$1;
  24927. videojs.createLogger = createLogger;
  24928. videojs.createTimeRange = videojs.createTimeRanges = createTimeRanges;
  24929. videojs.formatTime = formatTime;
  24930. videojs.setFormatTime = setFormatTime;
  24931. videojs.resetFormatTime = resetFormatTime;
  24932. videojs.parseUrl = parseUrl;
  24933. videojs.isCrossOrigin = isCrossOrigin;
  24934. videojs.EventTarget = EventTarget$2;
  24935. videojs.on = on;
  24936. videojs.one = one;
  24937. videojs.off = off;
  24938. videojs.trigger = trigger;
  24939. /**
  24940. * A cross-browser XMLHttpRequest wrapper.
  24941. *
  24942. * @function
  24943. * @param {Object} options
  24944. * Settings for the request.
  24945. *
  24946. * @return {XMLHttpRequest|XDomainRequest}
  24947. * The request object.
  24948. *
  24949. * @see https://github.com/Raynos/xhr
  24950. */
  24951. videojs.xhr = lib;
  24952. videojs.TextTrack = TextTrack;
  24953. videojs.AudioTrack = AudioTrack;
  24954. videojs.VideoTrack = VideoTrack;
  24955. ['isEl', 'isTextNode', 'createEl', 'hasClass', 'addClass', 'removeClass', 'toggleClass', 'setAttributes', 'getAttributes', 'emptyEl', 'appendContent', 'insertContent'].forEach(function (k) {
  24956. videojs[k] = function () {
  24957. log$1.warn("videojs." + k + "() is deprecated; use videojs.dom." + k + "() instead");
  24958. return Dom[k].apply(null, arguments);
  24959. };
  24960. });
  24961. videojs.computedStyle = computedStyle;
  24962. /**
  24963. * A reference to the {@link module:dom|DOM utility module} as an object.
  24964. *
  24965. * @type {Object}
  24966. * @see {@link module:dom|dom}
  24967. */
  24968. videojs.dom = Dom;
  24969. /**
  24970. * A reference to the {@link module:url|URL utility module} as an object.
  24971. *
  24972. * @type {Object}
  24973. * @see {@link module:url|url}
  24974. */
  24975. videojs.url = Url;
  24976. videojs.defineLazyProperty = defineLazyProperty; // Adding less ambiguous text for fullscreen button.
  24977. // In a major update this could become the default text and key.
  24978. videojs.addLanguage('en', {
  24979. 'Non-Fullscreen': 'Exit Fullscreen'
  24980. });
  24981. var urlToolkit = createCommonjsModule(function (module, exports) {
  24982. // see https://tools.ietf.org/html/rfc1808
  24983. (function (root) {
  24984. var URL_REGEX = /^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#[^]*)?$/;
  24985. var FIRST_SEGMENT_REGEX = /^([^\/?#]*)([^]*)$/;
  24986. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  24987. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g;
  24988. var URLToolkit = {
  24989. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  24990. // E.g
  24991. // With opts.alwaysNormalize = false (default, spec compliant)
  24992. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  24993. // With opts.alwaysNormalize = true (not spec compliant)
  24994. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  24995. buildAbsoluteURL: function buildAbsoluteURL(baseURL, relativeURL, opts) {
  24996. opts = opts || {}; // remove any remaining space and CRLF
  24997. baseURL = baseURL.trim();
  24998. relativeURL = relativeURL.trim();
  24999. if (!relativeURL) {
  25000. // 2a) If the embedded URL is entirely empty, it inherits the
  25001. // entire base URL (i.e., is set equal to the base URL)
  25002. // and we are done.
  25003. if (!opts.alwaysNormalize) {
  25004. return baseURL;
  25005. }
  25006. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  25007. if (!basePartsForNormalise) {
  25008. throw new Error('Error trying to parse base URL.');
  25009. }
  25010. basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);
  25011. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  25012. }
  25013. var relativeParts = URLToolkit.parseURL(relativeURL);
  25014. if (!relativeParts) {
  25015. throw new Error('Error trying to parse relative URL.');
  25016. }
  25017. if (relativeParts.scheme) {
  25018. // 2b) If the embedded URL starts with a scheme name, it is
  25019. // interpreted as an absolute URL and we are done.
  25020. if (!opts.alwaysNormalize) {
  25021. return relativeURL;
  25022. }
  25023. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  25024. return URLToolkit.buildURLFromParts(relativeParts);
  25025. }
  25026. var baseParts = URLToolkit.parseURL(baseURL);
  25027. if (!baseParts) {
  25028. throw new Error('Error trying to parse base URL.');
  25029. }
  25030. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
  25031. // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
  25032. // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
  25033. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  25034. baseParts.netLoc = pathParts[1];
  25035. baseParts.path = pathParts[2];
  25036. }
  25037. if (baseParts.netLoc && !baseParts.path) {
  25038. baseParts.path = '/';
  25039. }
  25040. var builtParts = {
  25041. // 2c) Otherwise, the embedded URL inherits the scheme of
  25042. // the base URL.
  25043. scheme: baseParts.scheme,
  25044. netLoc: relativeParts.netLoc,
  25045. path: null,
  25046. params: relativeParts.params,
  25047. query: relativeParts.query,
  25048. fragment: relativeParts.fragment
  25049. };
  25050. if (!relativeParts.netLoc) {
  25051. // 3) If the embedded URL's <net_loc> is non-empty, we skip to
  25052. // Step 7. Otherwise, the embedded URL inherits the <net_loc>
  25053. // (if any) of the base URL.
  25054. builtParts.netLoc = baseParts.netLoc; // 4) If the embedded URL path is preceded by a slash "/", the
  25055. // path is not relative and we skip to Step 7.
  25056. if (relativeParts.path[0] !== '/') {
  25057. if (!relativeParts.path) {
  25058. // 5) If the embedded URL path is empty (and not preceded by a
  25059. // slash), then the embedded URL inherits the base URL path
  25060. builtParts.path = baseParts.path; // 5a) if the embedded URL's <params> is non-empty, we skip to
  25061. // step 7; otherwise, it inherits the <params> of the base
  25062. // URL (if any) and
  25063. if (!relativeParts.params) {
  25064. builtParts.params = baseParts.params; // 5b) if the embedded URL's <query> is non-empty, we skip to
  25065. // step 7; otherwise, it inherits the <query> of the base
  25066. // URL (if any) and we skip to step 7.
  25067. if (!relativeParts.query) {
  25068. builtParts.query = baseParts.query;
  25069. }
  25070. }
  25071. } else {
  25072. // 6) The last segment of the base URL's path (anything
  25073. // following the rightmost slash "/", or the entire path if no
  25074. // slash is present) is removed and the embedded URL's path is
  25075. // appended in its place.
  25076. var baseURLPath = baseParts.path;
  25077. var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path;
  25078. builtParts.path = URLToolkit.normalizePath(newPath);
  25079. }
  25080. }
  25081. }
  25082. if (builtParts.path === null) {
  25083. builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;
  25084. }
  25085. return URLToolkit.buildURLFromParts(builtParts);
  25086. },
  25087. parseURL: function parseURL(url) {
  25088. var parts = URL_REGEX.exec(url);
  25089. if (!parts) {
  25090. return null;
  25091. }
  25092. return {
  25093. scheme: parts[1] || '',
  25094. netLoc: parts[2] || '',
  25095. path: parts[3] || '',
  25096. params: parts[4] || '',
  25097. query: parts[5] || '',
  25098. fragment: parts[6] || ''
  25099. };
  25100. },
  25101. normalizePath: function normalizePath(path) {
  25102. // The following operations are
  25103. // then applied, in order, to the new path:
  25104. // 6a) All occurrences of "./", where "." is a complete path
  25105. // segment, are removed.
  25106. // 6b) If the path ends with "." as a complete path segment,
  25107. // that "." is removed.
  25108. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, ''); // 6c) All occurrences of "<segment>/../", where <segment> is a
  25109. // complete path segment not equal to "..", are removed.
  25110. // Removal of these path segments is performed iteratively,
  25111. // removing the leftmost matching pattern on each iteration,
  25112. // until no matching pattern remains.
  25113. // 6d) If the path ends with "<segment>/..", where <segment> is a
  25114. // complete path segment not equal to "..", that
  25115. // "<segment>/.." is removed.
  25116. while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {}
  25117. return path.split('').reverse().join('');
  25118. },
  25119. buildURLFromParts: function buildURLFromParts(parts) {
  25120. return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
  25121. }
  25122. };
  25123. module.exports = URLToolkit;
  25124. })();
  25125. });
  25126. var DEFAULT_LOCATION$1 = 'http://example.com';
  25127. var resolveUrl$2 = function resolveUrl(baseUrl, relativeUrl) {
  25128. // return early if we don't need to resolve
  25129. if (/^[a-z]+:/i.test(relativeUrl)) {
  25130. return relativeUrl;
  25131. } // if baseUrl is a data URI, ignore it and resolve everything relative to window.location
  25132. if (/^data:/.test(baseUrl)) {
  25133. baseUrl = window.location && window.location.href || '';
  25134. } // IE11 supports URL but not the URL constructor
  25135. // feature detect the behavior we want
  25136. var nativeURL = typeof window.URL === 'function';
  25137. var protocolLess = /^\/\//.test(baseUrl); // remove location if window.location isn't available (i.e. we're in node)
  25138. // and if baseUrl isn't an absolute url
  25139. var removeLocation = !window.location && !/\/\//i.test(baseUrl); // if the base URL is relative then combine with the current location
  25140. if (nativeURL) {
  25141. baseUrl = new window.URL(baseUrl, window.location || DEFAULT_LOCATION$1);
  25142. } else if (!/\/\//i.test(baseUrl)) {
  25143. baseUrl = urlToolkit.buildAbsoluteURL(window.location && window.location.href || '', baseUrl);
  25144. }
  25145. if (nativeURL) {
  25146. var newUrl = new URL(relativeUrl, baseUrl); // if we're a protocol-less url, remove the protocol
  25147. // and if we're location-less, remove the location
  25148. // otherwise, return the url unmodified
  25149. if (removeLocation) {
  25150. return newUrl.href.slice(DEFAULT_LOCATION$1.length);
  25151. } else if (protocolLess) {
  25152. return newUrl.href.slice(newUrl.protocol.length);
  25153. }
  25154. return newUrl.href;
  25155. }
  25156. return urlToolkit.buildAbsoluteURL(baseUrl, relativeUrl);
  25157. };
  25158. /**
  25159. * @file stream.js
  25160. */
  25161. /**
  25162. * A lightweight readable stream implemention that handles event dispatching.
  25163. *
  25164. * @class Stream
  25165. */
  25166. var Stream = /*#__PURE__*/function () {
  25167. function Stream() {
  25168. this.listeners = {};
  25169. }
  25170. /**
  25171. * Add a listener for a specified event type.
  25172. *
  25173. * @param {string} type the event name
  25174. * @param {Function} listener the callback to be invoked when an event of
  25175. * the specified type occurs
  25176. */
  25177. var _proto = Stream.prototype;
  25178. _proto.on = function on(type, listener) {
  25179. if (!this.listeners[type]) {
  25180. this.listeners[type] = [];
  25181. }
  25182. this.listeners[type].push(listener);
  25183. }
  25184. /**
  25185. * Remove a listener for a specified event type.
  25186. *
  25187. * @param {string} type the event name
  25188. * @param {Function} listener a function previously registered for this
  25189. * type of event through `on`
  25190. * @return {boolean} if we could turn it off or not
  25191. */
  25192. ;
  25193. _proto.off = function off(type, listener) {
  25194. if (!this.listeners[type]) {
  25195. return false;
  25196. }
  25197. var index = this.listeners[type].indexOf(listener); // TODO: which is better?
  25198. // In Video.js we slice listener functions
  25199. // on trigger so that it does not mess up the order
  25200. // while we loop through.
  25201. //
  25202. // Here we slice on off so that the loop in trigger
  25203. // can continue using it's old reference to loop without
  25204. // messing up the order.
  25205. this.listeners[type] = this.listeners[type].slice(0);
  25206. this.listeners[type].splice(index, 1);
  25207. return index > -1;
  25208. }
  25209. /**
  25210. * Trigger an event of the specified type on this stream. Any additional
  25211. * arguments to this function are passed as parameters to event listeners.
  25212. *
  25213. * @param {string} type the event name
  25214. */
  25215. ;
  25216. _proto.trigger = function trigger(type) {
  25217. var callbacks = this.listeners[type];
  25218. if (!callbacks) {
  25219. return;
  25220. } // Slicing the arguments on every invocation of this method
  25221. // can add a significant amount of overhead. Avoid the
  25222. // intermediate object creation for the common case of a
  25223. // single callback argument
  25224. if (arguments.length === 2) {
  25225. var length = callbacks.length;
  25226. for (var i = 0; i < length; ++i) {
  25227. callbacks[i].call(this, arguments[1]);
  25228. }
  25229. } else {
  25230. var args = Array.prototype.slice.call(arguments, 1);
  25231. var _length = callbacks.length;
  25232. for (var _i = 0; _i < _length; ++_i) {
  25233. callbacks[_i].apply(this, args);
  25234. }
  25235. }
  25236. }
  25237. /**
  25238. * Destroys the stream and cleans up.
  25239. */
  25240. ;
  25241. _proto.dispose = function dispose() {
  25242. this.listeners = {};
  25243. }
  25244. /**
  25245. * Forwards all `data` events on this stream to the destination stream. The
  25246. * destination stream should provide a method `push` to receive the data
  25247. * events as they arrive.
  25248. *
  25249. * @param {Stream} destination the stream that will receive all `data` events
  25250. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  25251. */
  25252. ;
  25253. _proto.pipe = function pipe(destination) {
  25254. this.on('data', function (data) {
  25255. destination.push(data);
  25256. });
  25257. };
  25258. return Stream;
  25259. }();
  25260. var atob$1 = function atob(s) {
  25261. return window.atob ? window.atob(s) : Buffer.from(s, 'base64').toString('binary');
  25262. };
  25263. function decodeB64ToUint8Array$1(b64Text) {
  25264. var decodedString = atob$1(b64Text);
  25265. var array = new Uint8Array(decodedString.length);
  25266. for (var i = 0; i < decodedString.length; i++) {
  25267. array[i] = decodedString.charCodeAt(i);
  25268. }
  25269. return array;
  25270. }
  25271. /*! @name m3u8-parser @version 4.8.0 @license Apache-2.0 */
  25272. /**
  25273. * A stream that buffers string input and generates a `data` event for each
  25274. * line.
  25275. *
  25276. * @class LineStream
  25277. * @extends Stream
  25278. */
  25279. var LineStream = /*#__PURE__*/function (_Stream) {
  25280. inheritsLoose(LineStream, _Stream);
  25281. function LineStream() {
  25282. var _this;
  25283. _this = _Stream.call(this) || this;
  25284. _this.buffer = '';
  25285. return _this;
  25286. }
  25287. /**
  25288. * Add new data to be parsed.
  25289. *
  25290. * @param {string} data the text to process
  25291. */
  25292. var _proto = LineStream.prototype;
  25293. _proto.push = function push(data) {
  25294. var nextNewline;
  25295. this.buffer += data;
  25296. nextNewline = this.buffer.indexOf('\n');
  25297. for (; nextNewline > -1; nextNewline = this.buffer.indexOf('\n')) {
  25298. this.trigger('data', this.buffer.substring(0, nextNewline));
  25299. this.buffer = this.buffer.substring(nextNewline + 1);
  25300. }
  25301. };
  25302. return LineStream;
  25303. }(Stream);
  25304. var TAB = String.fromCharCode(0x09);
  25305. var parseByterange = function parseByterange(byterangeString) {
  25306. // optionally match and capture 0+ digits before `@`
  25307. // optionally match and capture 0+ digits after `@`
  25308. var match = /([0-9.]*)?@?([0-9.]*)?/.exec(byterangeString || '');
  25309. var result = {};
  25310. if (match[1]) {
  25311. result.length = parseInt(match[1], 10);
  25312. }
  25313. if (match[2]) {
  25314. result.offset = parseInt(match[2], 10);
  25315. }
  25316. return result;
  25317. };
  25318. /**
  25319. * "forgiving" attribute list psuedo-grammar:
  25320. * attributes -> keyvalue (',' keyvalue)*
  25321. * keyvalue -> key '=' value
  25322. * key -> [^=]*
  25323. * value -> '"' [^"]* '"' | [^,]*
  25324. */
  25325. var attributeSeparator = function attributeSeparator() {
  25326. var key = '[^=]*';
  25327. var value = '"[^"]*"|[^,]*';
  25328. var keyvalue = '(?:' + key + ')=(?:' + value + ')';
  25329. return new RegExp('(?:^|,)(' + keyvalue + ')');
  25330. };
  25331. /**
  25332. * Parse attributes from a line given the separator
  25333. *
  25334. * @param {string} attributes the attribute line to parse
  25335. */
  25336. var parseAttributes$1 = function parseAttributes(attributes) {
  25337. // split the string using attributes as the separator
  25338. var attrs = attributes.split(attributeSeparator());
  25339. var result = {};
  25340. var i = attrs.length;
  25341. var attr;
  25342. while (i--) {
  25343. // filter out unmatched portions of the string
  25344. if (attrs[i] === '') {
  25345. continue;
  25346. } // split the key and value
  25347. attr = /([^=]*)=(.*)/.exec(attrs[i]).slice(1); // trim whitespace and remove optional quotes around the value
  25348. attr[0] = attr[0].replace(/^\s+|\s+$/g, '');
  25349. attr[1] = attr[1].replace(/^\s+|\s+$/g, '');
  25350. attr[1] = attr[1].replace(/^['"](.*)['"]$/g, '$1');
  25351. result[attr[0]] = attr[1];
  25352. }
  25353. return result;
  25354. };
  25355. /**
  25356. * A line-level M3U8 parser event stream. It expects to receive input one
  25357. * line at a time and performs a context-free parse of its contents. A stream
  25358. * interpretation of a manifest can be useful if the manifest is expected to
  25359. * be too large to fit comfortably into memory or the entirety of the input
  25360. * is not immediately available. Otherwise, it's probably much easier to work
  25361. * with a regular `Parser` object.
  25362. *
  25363. * Produces `data` events with an object that captures the parser's
  25364. * interpretation of the input. That object has a property `tag` that is one
  25365. * of `uri`, `comment`, or `tag`. URIs only have a single additional
  25366. * property, `line`, which captures the entirety of the input without
  25367. * interpretation. Comments similarly have a single additional property
  25368. * `text` which is the input without the leading `#`.
  25369. *
  25370. * Tags always have a property `tagType` which is the lower-cased version of
  25371. * the M3U8 directive without the `#EXT` or `#EXT-X-` prefix. For instance,
  25372. * `#EXT-X-MEDIA-SEQUENCE` becomes `media-sequence` when parsed. Unrecognized
  25373. * tags are given the tag type `unknown` and a single additional property
  25374. * `data` with the remainder of the input.
  25375. *
  25376. * @class ParseStream
  25377. * @extends Stream
  25378. */
  25379. var ParseStream = /*#__PURE__*/function (_Stream) {
  25380. inheritsLoose(ParseStream, _Stream);
  25381. function ParseStream() {
  25382. var _this;
  25383. _this = _Stream.call(this) || this;
  25384. _this.customParsers = [];
  25385. _this.tagMappers = [];
  25386. return _this;
  25387. }
  25388. /**
  25389. * Parses an additional line of input.
  25390. *
  25391. * @param {string} line a single line of an M3U8 file to parse
  25392. */
  25393. var _proto = ParseStream.prototype;
  25394. _proto.push = function push(line) {
  25395. var _this2 = this;
  25396. var match;
  25397. var event; // strip whitespace
  25398. line = line.trim();
  25399. if (line.length === 0) {
  25400. // ignore empty lines
  25401. return;
  25402. } // URIs
  25403. if (line[0] !== '#') {
  25404. this.trigger('data', {
  25405. type: 'uri',
  25406. uri: line
  25407. });
  25408. return;
  25409. } // map tags
  25410. var newLines = this.tagMappers.reduce(function (acc, mapper) {
  25411. var mappedLine = mapper(line); // skip if unchanged
  25412. if (mappedLine === line) {
  25413. return acc;
  25414. }
  25415. return acc.concat([mappedLine]);
  25416. }, [line]);
  25417. newLines.forEach(function (newLine) {
  25418. for (var i = 0; i < _this2.customParsers.length; i++) {
  25419. if (_this2.customParsers[i].call(_this2, newLine)) {
  25420. return;
  25421. }
  25422. } // Comments
  25423. if (newLine.indexOf('#EXT') !== 0) {
  25424. _this2.trigger('data', {
  25425. type: 'comment',
  25426. text: newLine.slice(1)
  25427. });
  25428. return;
  25429. } // strip off any carriage returns here so the regex matching
  25430. // doesn't have to account for them.
  25431. newLine = newLine.replace('\r', ''); // Tags
  25432. match = /^#EXTM3U/.exec(newLine);
  25433. if (match) {
  25434. _this2.trigger('data', {
  25435. type: 'tag',
  25436. tagType: 'm3u'
  25437. });
  25438. return;
  25439. }
  25440. match = /^#EXTINF:?([0-9\.]*)?,?(.*)?$/.exec(newLine);
  25441. if (match) {
  25442. event = {
  25443. type: 'tag',
  25444. tagType: 'inf'
  25445. };
  25446. if (match[1]) {
  25447. event.duration = parseFloat(match[1]);
  25448. }
  25449. if (match[2]) {
  25450. event.title = match[2];
  25451. }
  25452. _this2.trigger('data', event);
  25453. return;
  25454. }
  25455. match = /^#EXT-X-TARGETDURATION:?([0-9.]*)?/.exec(newLine);
  25456. if (match) {
  25457. event = {
  25458. type: 'tag',
  25459. tagType: 'targetduration'
  25460. };
  25461. if (match[1]) {
  25462. event.duration = parseInt(match[1], 10);
  25463. }
  25464. _this2.trigger('data', event);
  25465. return;
  25466. }
  25467. match = /^#EXT-X-VERSION:?([0-9.]*)?/.exec(newLine);
  25468. if (match) {
  25469. event = {
  25470. type: 'tag',
  25471. tagType: 'version'
  25472. };
  25473. if (match[1]) {
  25474. event.version = parseInt(match[1], 10);
  25475. }
  25476. _this2.trigger('data', event);
  25477. return;
  25478. }
  25479. match = /^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(newLine);
  25480. if (match) {
  25481. event = {
  25482. type: 'tag',
  25483. tagType: 'media-sequence'
  25484. };
  25485. if (match[1]) {
  25486. event.number = parseInt(match[1], 10);
  25487. }
  25488. _this2.trigger('data', event);
  25489. return;
  25490. }
  25491. match = /^#EXT-X-DISCONTINUITY-SEQUENCE:?(\-?[0-9.]*)?/.exec(newLine);
  25492. if (match) {
  25493. event = {
  25494. type: 'tag',
  25495. tagType: 'discontinuity-sequence'
  25496. };
  25497. if (match[1]) {
  25498. event.number = parseInt(match[1], 10);
  25499. }
  25500. _this2.trigger('data', event);
  25501. return;
  25502. }
  25503. match = /^#EXT-X-PLAYLIST-TYPE:?(.*)?$/.exec(newLine);
  25504. if (match) {
  25505. event = {
  25506. type: 'tag',
  25507. tagType: 'playlist-type'
  25508. };
  25509. if (match[1]) {
  25510. event.playlistType = match[1];
  25511. }
  25512. _this2.trigger('data', event);
  25513. return;
  25514. }
  25515. match = /^#EXT-X-BYTERANGE:?(.*)?$/.exec(newLine);
  25516. if (match) {
  25517. event = _extends_1(parseByterange(match[1]), {
  25518. type: 'tag',
  25519. tagType: 'byterange'
  25520. });
  25521. _this2.trigger('data', event);
  25522. return;
  25523. }
  25524. match = /^#EXT-X-ALLOW-CACHE:?(YES|NO)?/.exec(newLine);
  25525. if (match) {
  25526. event = {
  25527. type: 'tag',
  25528. tagType: 'allow-cache'
  25529. };
  25530. if (match[1]) {
  25531. event.allowed = !/NO/.test(match[1]);
  25532. }
  25533. _this2.trigger('data', event);
  25534. return;
  25535. }
  25536. match = /^#EXT-X-MAP:?(.*)$/.exec(newLine);
  25537. if (match) {
  25538. event = {
  25539. type: 'tag',
  25540. tagType: 'map'
  25541. };
  25542. if (match[1]) {
  25543. var attributes = parseAttributes$1(match[1]);
  25544. if (attributes.URI) {
  25545. event.uri = attributes.URI;
  25546. }
  25547. if (attributes.BYTERANGE) {
  25548. event.byterange = parseByterange(attributes.BYTERANGE);
  25549. }
  25550. }
  25551. _this2.trigger('data', event);
  25552. return;
  25553. }
  25554. match = /^#EXT-X-STREAM-INF:?(.*)$/.exec(newLine);
  25555. if (match) {
  25556. event = {
  25557. type: 'tag',
  25558. tagType: 'stream-inf'
  25559. };
  25560. if (match[1]) {
  25561. event.attributes = parseAttributes$1(match[1]);
  25562. if (event.attributes.RESOLUTION) {
  25563. var split = event.attributes.RESOLUTION.split('x');
  25564. var resolution = {};
  25565. if (split[0]) {
  25566. resolution.width = parseInt(split[0], 10);
  25567. }
  25568. if (split[1]) {
  25569. resolution.height = parseInt(split[1], 10);
  25570. }
  25571. event.attributes.RESOLUTION = resolution;
  25572. }
  25573. if (event.attributes.BANDWIDTH) {
  25574. event.attributes.BANDWIDTH = parseInt(event.attributes.BANDWIDTH, 10);
  25575. }
  25576. if (event.attributes['FRAME-RATE']) {
  25577. event.attributes['FRAME-RATE'] = parseFloat(event.attributes['FRAME-RATE']);
  25578. }
  25579. if (event.attributes['PROGRAM-ID']) {
  25580. event.attributes['PROGRAM-ID'] = parseInt(event.attributes['PROGRAM-ID'], 10);
  25581. }
  25582. }
  25583. _this2.trigger('data', event);
  25584. return;
  25585. }
  25586. match = /^#EXT-X-MEDIA:?(.*)$/.exec(newLine);
  25587. if (match) {
  25588. event = {
  25589. type: 'tag',
  25590. tagType: 'media'
  25591. };
  25592. if (match[1]) {
  25593. event.attributes = parseAttributes$1(match[1]);
  25594. }
  25595. _this2.trigger('data', event);
  25596. return;
  25597. }
  25598. match = /^#EXT-X-ENDLIST/.exec(newLine);
  25599. if (match) {
  25600. _this2.trigger('data', {
  25601. type: 'tag',
  25602. tagType: 'endlist'
  25603. });
  25604. return;
  25605. }
  25606. match = /^#EXT-X-DISCONTINUITY/.exec(newLine);
  25607. if (match) {
  25608. _this2.trigger('data', {
  25609. type: 'tag',
  25610. tagType: 'discontinuity'
  25611. });
  25612. return;
  25613. }
  25614. match = /^#EXT-X-PROGRAM-DATE-TIME:?(.*)$/.exec(newLine);
  25615. if (match) {
  25616. event = {
  25617. type: 'tag',
  25618. tagType: 'program-date-time'
  25619. };
  25620. if (match[1]) {
  25621. event.dateTimeString = match[1];
  25622. event.dateTimeObject = new Date(match[1]);
  25623. }
  25624. _this2.trigger('data', event);
  25625. return;
  25626. }
  25627. match = /^#EXT-X-KEY:?(.*)$/.exec(newLine);
  25628. if (match) {
  25629. event = {
  25630. type: 'tag',
  25631. tagType: 'key'
  25632. };
  25633. if (match[1]) {
  25634. event.attributes = parseAttributes$1(match[1]); // parse the IV string into a Uint32Array
  25635. if (event.attributes.IV) {
  25636. if (event.attributes.IV.substring(0, 2).toLowerCase() === '0x') {
  25637. event.attributes.IV = event.attributes.IV.substring(2);
  25638. }
  25639. event.attributes.IV = event.attributes.IV.match(/.{8}/g);
  25640. event.attributes.IV[0] = parseInt(event.attributes.IV[0], 16);
  25641. event.attributes.IV[1] = parseInt(event.attributes.IV[1], 16);
  25642. event.attributes.IV[2] = parseInt(event.attributes.IV[2], 16);
  25643. event.attributes.IV[3] = parseInt(event.attributes.IV[3], 16);
  25644. event.attributes.IV = new Uint32Array(event.attributes.IV);
  25645. }
  25646. }
  25647. _this2.trigger('data', event);
  25648. return;
  25649. }
  25650. match = /^#EXT-X-START:?(.*)$/.exec(newLine);
  25651. if (match) {
  25652. event = {
  25653. type: 'tag',
  25654. tagType: 'start'
  25655. };
  25656. if (match[1]) {
  25657. event.attributes = parseAttributes$1(match[1]);
  25658. event.attributes['TIME-OFFSET'] = parseFloat(event.attributes['TIME-OFFSET']);
  25659. event.attributes.PRECISE = /YES/.test(event.attributes.PRECISE);
  25660. }
  25661. _this2.trigger('data', event);
  25662. return;
  25663. }
  25664. match = /^#EXT-X-CUE-OUT-CONT:?(.*)?$/.exec(newLine);
  25665. if (match) {
  25666. event = {
  25667. type: 'tag',
  25668. tagType: 'cue-out-cont'
  25669. };
  25670. if (match[1]) {
  25671. event.data = match[1];
  25672. } else {
  25673. event.data = '';
  25674. }
  25675. _this2.trigger('data', event);
  25676. return;
  25677. }
  25678. match = /^#EXT-X-CUE-OUT:?(.*)?$/.exec(newLine);
  25679. if (match) {
  25680. event = {
  25681. type: 'tag',
  25682. tagType: 'cue-out'
  25683. };
  25684. if (match[1]) {
  25685. event.data = match[1];
  25686. } else {
  25687. event.data = '';
  25688. }
  25689. _this2.trigger('data', event);
  25690. return;
  25691. }
  25692. match = /^#EXT-X-CUE-IN:?(.*)?$/.exec(newLine);
  25693. if (match) {
  25694. event = {
  25695. type: 'tag',
  25696. tagType: 'cue-in'
  25697. };
  25698. if (match[1]) {
  25699. event.data = match[1];
  25700. } else {
  25701. event.data = '';
  25702. }
  25703. _this2.trigger('data', event);
  25704. return;
  25705. }
  25706. match = /^#EXT-X-SKIP:(.*)$/.exec(newLine);
  25707. if (match && match[1]) {
  25708. event = {
  25709. type: 'tag',
  25710. tagType: 'skip'
  25711. };
  25712. event.attributes = parseAttributes$1(match[1]);
  25713. if (event.attributes.hasOwnProperty('SKIPPED-SEGMENTS')) {
  25714. event.attributes['SKIPPED-SEGMENTS'] = parseInt(event.attributes['SKIPPED-SEGMENTS'], 10);
  25715. }
  25716. if (event.attributes.hasOwnProperty('RECENTLY-REMOVED-DATERANGES')) {
  25717. event.attributes['RECENTLY-REMOVED-DATERANGES'] = event.attributes['RECENTLY-REMOVED-DATERANGES'].split(TAB);
  25718. }
  25719. _this2.trigger('data', event);
  25720. return;
  25721. }
  25722. match = /^#EXT-X-PART:(.*)$/.exec(newLine);
  25723. if (match && match[1]) {
  25724. event = {
  25725. type: 'tag',
  25726. tagType: 'part'
  25727. };
  25728. event.attributes = parseAttributes$1(match[1]);
  25729. ['DURATION'].forEach(function (key) {
  25730. if (event.attributes.hasOwnProperty(key)) {
  25731. event.attributes[key] = parseFloat(event.attributes[key]);
  25732. }
  25733. });
  25734. ['INDEPENDENT', 'GAP'].forEach(function (key) {
  25735. if (event.attributes.hasOwnProperty(key)) {
  25736. event.attributes[key] = /YES/.test(event.attributes[key]);
  25737. }
  25738. });
  25739. if (event.attributes.hasOwnProperty('BYTERANGE')) {
  25740. event.attributes.byterange = parseByterange(event.attributes.BYTERANGE);
  25741. }
  25742. _this2.trigger('data', event);
  25743. return;
  25744. }
  25745. match = /^#EXT-X-SERVER-CONTROL:(.*)$/.exec(newLine);
  25746. if (match && match[1]) {
  25747. event = {
  25748. type: 'tag',
  25749. tagType: 'server-control'
  25750. };
  25751. event.attributes = parseAttributes$1(match[1]);
  25752. ['CAN-SKIP-UNTIL', 'PART-HOLD-BACK', 'HOLD-BACK'].forEach(function (key) {
  25753. if (event.attributes.hasOwnProperty(key)) {
  25754. event.attributes[key] = parseFloat(event.attributes[key]);
  25755. }
  25756. });
  25757. ['CAN-SKIP-DATERANGES', 'CAN-BLOCK-RELOAD'].forEach(function (key) {
  25758. if (event.attributes.hasOwnProperty(key)) {
  25759. event.attributes[key] = /YES/.test(event.attributes[key]);
  25760. }
  25761. });
  25762. _this2.trigger('data', event);
  25763. return;
  25764. }
  25765. match = /^#EXT-X-PART-INF:(.*)$/.exec(newLine);
  25766. if (match && match[1]) {
  25767. event = {
  25768. type: 'tag',
  25769. tagType: 'part-inf'
  25770. };
  25771. event.attributes = parseAttributes$1(match[1]);
  25772. ['PART-TARGET'].forEach(function (key) {
  25773. if (event.attributes.hasOwnProperty(key)) {
  25774. event.attributes[key] = parseFloat(event.attributes[key]);
  25775. }
  25776. });
  25777. _this2.trigger('data', event);
  25778. return;
  25779. }
  25780. match = /^#EXT-X-PRELOAD-HINT:(.*)$/.exec(newLine);
  25781. if (match && match[1]) {
  25782. event = {
  25783. type: 'tag',
  25784. tagType: 'preload-hint'
  25785. };
  25786. event.attributes = parseAttributes$1(match[1]);
  25787. ['BYTERANGE-START', 'BYTERANGE-LENGTH'].forEach(function (key) {
  25788. if (event.attributes.hasOwnProperty(key)) {
  25789. event.attributes[key] = parseInt(event.attributes[key], 10);
  25790. var subkey = key === 'BYTERANGE-LENGTH' ? 'length' : 'offset';
  25791. event.attributes.byterange = event.attributes.byterange || {};
  25792. event.attributes.byterange[subkey] = event.attributes[key]; // only keep the parsed byterange object.
  25793. delete event.attributes[key];
  25794. }
  25795. });
  25796. _this2.trigger('data', event);
  25797. return;
  25798. }
  25799. match = /^#EXT-X-RENDITION-REPORT:(.*)$/.exec(newLine);
  25800. if (match && match[1]) {
  25801. event = {
  25802. type: 'tag',
  25803. tagType: 'rendition-report'
  25804. };
  25805. event.attributes = parseAttributes$1(match[1]);
  25806. ['LAST-MSN', 'LAST-PART'].forEach(function (key) {
  25807. if (event.attributes.hasOwnProperty(key)) {
  25808. event.attributes[key] = parseInt(event.attributes[key], 10);
  25809. }
  25810. });
  25811. _this2.trigger('data', event);
  25812. return;
  25813. } // unknown tag type
  25814. _this2.trigger('data', {
  25815. type: 'tag',
  25816. data: newLine.slice(4)
  25817. });
  25818. });
  25819. }
  25820. /**
  25821. * Add a parser for custom headers
  25822. *
  25823. * @param {Object} options a map of options for the added parser
  25824. * @param {RegExp} options.expression a regular expression to match the custom header
  25825. * @param {string} options.customType the custom type to register to the output
  25826. * @param {Function} [options.dataParser] function to parse the line into an object
  25827. * @param {boolean} [options.segment] should tag data be attached to the segment object
  25828. */
  25829. ;
  25830. _proto.addParser = function addParser(_ref) {
  25831. var _this3 = this;
  25832. var expression = _ref.expression,
  25833. customType = _ref.customType,
  25834. dataParser = _ref.dataParser,
  25835. segment = _ref.segment;
  25836. if (typeof dataParser !== 'function') {
  25837. dataParser = function dataParser(line) {
  25838. return line;
  25839. };
  25840. }
  25841. this.customParsers.push(function (line) {
  25842. var match = expression.exec(line);
  25843. if (match) {
  25844. _this3.trigger('data', {
  25845. type: 'custom',
  25846. data: dataParser(line),
  25847. customType: customType,
  25848. segment: segment
  25849. });
  25850. return true;
  25851. }
  25852. });
  25853. }
  25854. /**
  25855. * Add a custom header mapper
  25856. *
  25857. * @param {Object} options
  25858. * @param {RegExp} options.expression a regular expression to match the custom header
  25859. * @param {Function} options.map function to translate tag into a different tag
  25860. */
  25861. ;
  25862. _proto.addTagMapper = function addTagMapper(_ref2) {
  25863. var expression = _ref2.expression,
  25864. map = _ref2.map;
  25865. var mapFn = function mapFn(line) {
  25866. if (expression.test(line)) {
  25867. return map(line);
  25868. }
  25869. return line;
  25870. };
  25871. this.tagMappers.push(mapFn);
  25872. };
  25873. return ParseStream;
  25874. }(Stream);
  25875. var camelCase = function camelCase(str) {
  25876. return str.toLowerCase().replace(/-(\w)/g, function (a) {
  25877. return a[1].toUpperCase();
  25878. });
  25879. };
  25880. var camelCaseKeys = function camelCaseKeys(attributes) {
  25881. var result = {};
  25882. Object.keys(attributes).forEach(function (key) {
  25883. result[camelCase(key)] = attributes[key];
  25884. });
  25885. return result;
  25886. }; // set SERVER-CONTROL hold back based upon targetDuration and partTargetDuration
  25887. // we need this helper because defaults are based upon targetDuration and
  25888. // partTargetDuration being set, but they may not be if SERVER-CONTROL appears before
  25889. // target durations are set.
  25890. var setHoldBack = function setHoldBack(manifest) {
  25891. var serverControl = manifest.serverControl,
  25892. targetDuration = manifest.targetDuration,
  25893. partTargetDuration = manifest.partTargetDuration;
  25894. if (!serverControl) {
  25895. return;
  25896. }
  25897. var tag = '#EXT-X-SERVER-CONTROL';
  25898. var hb = 'holdBack';
  25899. var phb = 'partHoldBack';
  25900. var minTargetDuration = targetDuration && targetDuration * 3;
  25901. var minPartDuration = partTargetDuration && partTargetDuration * 2;
  25902. if (targetDuration && !serverControl.hasOwnProperty(hb)) {
  25903. serverControl[hb] = minTargetDuration;
  25904. this.trigger('info', {
  25905. message: tag + " defaulting HOLD-BACK to targetDuration * 3 (" + minTargetDuration + ")."
  25906. });
  25907. }
  25908. if (minTargetDuration && serverControl[hb] < minTargetDuration) {
  25909. this.trigger('warn', {
  25910. message: tag + " clamping HOLD-BACK (" + serverControl[hb] + ") to targetDuration * 3 (" + minTargetDuration + ")"
  25911. });
  25912. serverControl[hb] = minTargetDuration;
  25913. } // default no part hold back to part target duration * 3
  25914. if (partTargetDuration && !serverControl.hasOwnProperty(phb)) {
  25915. serverControl[phb] = partTargetDuration * 3;
  25916. this.trigger('info', {
  25917. message: tag + " defaulting PART-HOLD-BACK to partTargetDuration * 3 (" + serverControl[phb] + ")."
  25918. });
  25919. } // if part hold back is too small default it to part target duration * 2
  25920. if (partTargetDuration && serverControl[phb] < minPartDuration) {
  25921. this.trigger('warn', {
  25922. message: tag + " clamping PART-HOLD-BACK (" + serverControl[phb] + ") to partTargetDuration * 2 (" + minPartDuration + ")."
  25923. });
  25924. serverControl[phb] = minPartDuration;
  25925. }
  25926. };
  25927. /**
  25928. * A parser for M3U8 files. The current interpretation of the input is
  25929. * exposed as a property `manifest` on parser objects. It's just two lines to
  25930. * create and parse a manifest once you have the contents available as a string:
  25931. *
  25932. * ```js
  25933. * var parser = new m3u8.Parser();
  25934. * parser.push(xhr.responseText);
  25935. * ```
  25936. *
  25937. * New input can later be applied to update the manifest object by calling
  25938. * `push` again.
  25939. *
  25940. * The parser attempts to create a usable manifest object even if the
  25941. * underlying input is somewhat nonsensical. It emits `info` and `warning`
  25942. * events during the parse if it encounters input that seems invalid or
  25943. * requires some property of the manifest object to be defaulted.
  25944. *
  25945. * @class Parser
  25946. * @extends Stream
  25947. */
  25948. var Parser = /*#__PURE__*/function (_Stream) {
  25949. inheritsLoose(Parser, _Stream);
  25950. function Parser() {
  25951. var _this;
  25952. _this = _Stream.call(this) || this;
  25953. _this.lineStream = new LineStream();
  25954. _this.parseStream = new ParseStream();
  25955. _this.lineStream.pipe(_this.parseStream);
  25956. /* eslint-disable consistent-this */
  25957. var self = assertThisInitialized(_this);
  25958. /* eslint-enable consistent-this */
  25959. var uris = [];
  25960. var currentUri = {}; // if specified, the active EXT-X-MAP definition
  25961. var currentMap; // if specified, the active decryption key
  25962. var _key;
  25963. var hasParts = false;
  25964. var noop = function noop() {};
  25965. var defaultMediaGroups = {
  25966. 'AUDIO': {},
  25967. 'VIDEO': {},
  25968. 'CLOSED-CAPTIONS': {},
  25969. 'SUBTITLES': {}
  25970. }; // This is the Widevine UUID from DASH IF IOP. The same exact string is
  25971. // used in MPDs with Widevine encrypted streams.
  25972. var widevineUuid = 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed'; // group segments into numbered timelines delineated by discontinuities
  25973. var currentTimeline = 0; // the manifest is empty until the parse stream begins delivering data
  25974. _this.manifest = {
  25975. allowCache: true,
  25976. discontinuityStarts: [],
  25977. segments: []
  25978. }; // keep track of the last seen segment's byte range end, as segments are not required
  25979. // to provide the offset, in which case it defaults to the next byte after the
  25980. // previous segment
  25981. var lastByterangeEnd = 0; // keep track of the last seen part's byte range end.
  25982. var lastPartByterangeEnd = 0;
  25983. _this.on('end', function () {
  25984. // only add preloadSegment if we don't yet have a uri for it.
  25985. // and we actually have parts/preloadHints
  25986. if (currentUri.uri || !currentUri.parts && !currentUri.preloadHints) {
  25987. return;
  25988. }
  25989. if (!currentUri.map && currentMap) {
  25990. currentUri.map = currentMap;
  25991. }
  25992. if (!currentUri.key && _key) {
  25993. currentUri.key = _key;
  25994. }
  25995. if (!currentUri.timeline && typeof currentTimeline === 'number') {
  25996. currentUri.timeline = currentTimeline;
  25997. }
  25998. _this.manifest.preloadSegment = currentUri;
  25999. }); // update the manifest with the m3u8 entry from the parse stream
  26000. _this.parseStream.on('data', function (entry) {
  26001. var mediaGroup;
  26002. var rendition;
  26003. ({
  26004. tag: function tag() {
  26005. // switch based on the tag type
  26006. (({
  26007. version: function version() {
  26008. if (entry.version) {
  26009. this.manifest.version = entry.version;
  26010. }
  26011. },
  26012. 'allow-cache': function allowCache() {
  26013. this.manifest.allowCache = entry.allowed;
  26014. if (!('allowed' in entry)) {
  26015. this.trigger('info', {
  26016. message: 'defaulting allowCache to YES'
  26017. });
  26018. this.manifest.allowCache = true;
  26019. }
  26020. },
  26021. byterange: function byterange() {
  26022. var byterange = {};
  26023. if ('length' in entry) {
  26024. currentUri.byterange = byterange;
  26025. byterange.length = entry.length;
  26026. if (!('offset' in entry)) {
  26027. /*
  26028. * From the latest spec (as of this writing):
  26029. * https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.2
  26030. *
  26031. * Same text since EXT-X-BYTERANGE's introduction in draft 7:
  26032. * https://tools.ietf.org/html/draft-pantos-http-live-streaming-07#section-3.3.1)
  26033. *
  26034. * "If o [offset] is not present, the sub-range begins at the next byte
  26035. * following the sub-range of the previous media segment."
  26036. */
  26037. entry.offset = lastByterangeEnd;
  26038. }
  26039. }
  26040. if ('offset' in entry) {
  26041. currentUri.byterange = byterange;
  26042. byterange.offset = entry.offset;
  26043. }
  26044. lastByterangeEnd = byterange.offset + byterange.length;
  26045. },
  26046. endlist: function endlist() {
  26047. this.manifest.endList = true;
  26048. },
  26049. inf: function inf() {
  26050. if (!('mediaSequence' in this.manifest)) {
  26051. this.manifest.mediaSequence = 0;
  26052. this.trigger('info', {
  26053. message: 'defaulting media sequence to zero'
  26054. });
  26055. }
  26056. if (!('discontinuitySequence' in this.manifest)) {
  26057. this.manifest.discontinuitySequence = 0;
  26058. this.trigger('info', {
  26059. message: 'defaulting discontinuity sequence to zero'
  26060. });
  26061. }
  26062. if (entry.duration > 0) {
  26063. currentUri.duration = entry.duration;
  26064. }
  26065. if (entry.duration === 0) {
  26066. currentUri.duration = 0.01;
  26067. this.trigger('info', {
  26068. message: 'updating zero segment duration to a small value'
  26069. });
  26070. }
  26071. this.manifest.segments = uris;
  26072. },
  26073. key: function key() {
  26074. if (!entry.attributes) {
  26075. this.trigger('warn', {
  26076. message: 'ignoring key declaration without attribute list'
  26077. });
  26078. return;
  26079. } // clear the active encryption key
  26080. if (entry.attributes.METHOD === 'NONE') {
  26081. _key = null;
  26082. return;
  26083. }
  26084. if (!entry.attributes.URI) {
  26085. this.trigger('warn', {
  26086. message: 'ignoring key declaration without URI'
  26087. });
  26088. return;
  26089. }
  26090. if (entry.attributes.KEYFORMAT === 'com.apple.streamingkeydelivery') {
  26091. this.manifest.contentProtection = this.manifest.contentProtection || {}; // TODO: add full support for this.
  26092. this.manifest.contentProtection['com.apple.fps.1_0'] = {
  26093. attributes: entry.attributes
  26094. };
  26095. return;
  26096. }
  26097. if (entry.attributes.KEYFORMAT === 'com.microsoft.playready') {
  26098. this.manifest.contentProtection = this.manifest.contentProtection || {}; // TODO: add full support for this.
  26099. this.manifest.contentProtection['com.microsoft.playready'] = {
  26100. uri: entry.attributes.URI
  26101. };
  26102. return;
  26103. } // check if the content is encrypted for Widevine
  26104. // Widevine/HLS spec: https://storage.googleapis.com/wvdocs/Widevine_DRM_HLS.pdf
  26105. if (entry.attributes.KEYFORMAT === widevineUuid) {
  26106. var VALID_METHODS = ['SAMPLE-AES', 'SAMPLE-AES-CTR', 'SAMPLE-AES-CENC'];
  26107. if (VALID_METHODS.indexOf(entry.attributes.METHOD) === -1) {
  26108. this.trigger('warn', {
  26109. message: 'invalid key method provided for Widevine'
  26110. });
  26111. return;
  26112. }
  26113. if (entry.attributes.METHOD === 'SAMPLE-AES-CENC') {
  26114. this.trigger('warn', {
  26115. message: 'SAMPLE-AES-CENC is deprecated, please use SAMPLE-AES-CTR instead'
  26116. });
  26117. }
  26118. if (entry.attributes.URI.substring(0, 23) !== 'data:text/plain;base64,') {
  26119. this.trigger('warn', {
  26120. message: 'invalid key URI provided for Widevine'
  26121. });
  26122. return;
  26123. }
  26124. if (!(entry.attributes.KEYID && entry.attributes.KEYID.substring(0, 2) === '0x')) {
  26125. this.trigger('warn', {
  26126. message: 'invalid key ID provided for Widevine'
  26127. });
  26128. return;
  26129. } // if Widevine key attributes are valid, store them as `contentProtection`
  26130. // on the manifest to emulate Widevine tag structure in a DASH mpd
  26131. this.manifest.contentProtection = this.manifest.contentProtection || {};
  26132. this.manifest.contentProtection['com.widevine.alpha'] = {
  26133. attributes: {
  26134. schemeIdUri: entry.attributes.KEYFORMAT,
  26135. // remove '0x' from the key id string
  26136. keyId: entry.attributes.KEYID.substring(2)
  26137. },
  26138. // decode the base64-encoded PSSH box
  26139. pssh: decodeB64ToUint8Array$1(entry.attributes.URI.split(',')[1])
  26140. };
  26141. return;
  26142. }
  26143. if (!entry.attributes.METHOD) {
  26144. this.trigger('warn', {
  26145. message: 'defaulting key method to AES-128'
  26146. });
  26147. } // setup an encryption key for upcoming segments
  26148. _key = {
  26149. method: entry.attributes.METHOD || 'AES-128',
  26150. uri: entry.attributes.URI
  26151. };
  26152. if (typeof entry.attributes.IV !== 'undefined') {
  26153. _key.iv = entry.attributes.IV;
  26154. }
  26155. },
  26156. 'media-sequence': function mediaSequence() {
  26157. if (!isFinite(entry.number)) {
  26158. this.trigger('warn', {
  26159. message: 'ignoring invalid media sequence: ' + entry.number
  26160. });
  26161. return;
  26162. }
  26163. this.manifest.mediaSequence = entry.number;
  26164. },
  26165. 'discontinuity-sequence': function discontinuitySequence() {
  26166. if (!isFinite(entry.number)) {
  26167. this.trigger('warn', {
  26168. message: 'ignoring invalid discontinuity sequence: ' + entry.number
  26169. });
  26170. return;
  26171. }
  26172. this.manifest.discontinuitySequence = entry.number;
  26173. currentTimeline = entry.number;
  26174. },
  26175. 'playlist-type': function playlistType() {
  26176. if (!/VOD|EVENT/.test(entry.playlistType)) {
  26177. this.trigger('warn', {
  26178. message: 'ignoring unknown playlist type: ' + entry.playlist
  26179. });
  26180. return;
  26181. }
  26182. this.manifest.playlistType = entry.playlistType;
  26183. },
  26184. map: function map() {
  26185. currentMap = {};
  26186. if (entry.uri) {
  26187. currentMap.uri = entry.uri;
  26188. }
  26189. if (entry.byterange) {
  26190. currentMap.byterange = entry.byterange;
  26191. }
  26192. if (_key) {
  26193. currentMap.key = _key;
  26194. }
  26195. },
  26196. 'stream-inf': function streamInf() {
  26197. this.manifest.playlists = uris;
  26198. this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
  26199. if (!entry.attributes) {
  26200. this.trigger('warn', {
  26201. message: 'ignoring empty stream-inf attributes'
  26202. });
  26203. return;
  26204. }
  26205. if (!currentUri.attributes) {
  26206. currentUri.attributes = {};
  26207. }
  26208. _extends_1(currentUri.attributes, entry.attributes);
  26209. },
  26210. media: function media() {
  26211. this.manifest.mediaGroups = this.manifest.mediaGroups || defaultMediaGroups;
  26212. if (!(entry.attributes && entry.attributes.TYPE && entry.attributes['GROUP-ID'] && entry.attributes.NAME)) {
  26213. this.trigger('warn', {
  26214. message: 'ignoring incomplete or missing media group'
  26215. });
  26216. return;
  26217. } // find the media group, creating defaults as necessary
  26218. var mediaGroupType = this.manifest.mediaGroups[entry.attributes.TYPE];
  26219. mediaGroupType[entry.attributes['GROUP-ID']] = mediaGroupType[entry.attributes['GROUP-ID']] || {};
  26220. mediaGroup = mediaGroupType[entry.attributes['GROUP-ID']]; // collect the rendition metadata
  26221. rendition = {
  26222. "default": /yes/i.test(entry.attributes.DEFAULT)
  26223. };
  26224. if (rendition["default"]) {
  26225. rendition.autoselect = true;
  26226. } else {
  26227. rendition.autoselect = /yes/i.test(entry.attributes.AUTOSELECT);
  26228. }
  26229. if (entry.attributes.LANGUAGE) {
  26230. rendition.language = entry.attributes.LANGUAGE;
  26231. }
  26232. if (entry.attributes.URI) {
  26233. rendition.uri = entry.attributes.URI;
  26234. }
  26235. if (entry.attributes['INSTREAM-ID']) {
  26236. rendition.instreamId = entry.attributes['INSTREAM-ID'];
  26237. }
  26238. if (entry.attributes.CHARACTERISTICS) {
  26239. rendition.characteristics = entry.attributes.CHARACTERISTICS;
  26240. }
  26241. if (entry.attributes.FORCED) {
  26242. rendition.forced = /yes/i.test(entry.attributes.FORCED);
  26243. } // insert the new rendition
  26244. mediaGroup[entry.attributes.NAME] = rendition;
  26245. },
  26246. discontinuity: function discontinuity() {
  26247. currentTimeline += 1;
  26248. currentUri.discontinuity = true;
  26249. this.manifest.discontinuityStarts.push(uris.length);
  26250. },
  26251. 'program-date-time': function programDateTime() {
  26252. if (typeof this.manifest.dateTimeString === 'undefined') {
  26253. // PROGRAM-DATE-TIME is a media-segment tag, but for backwards
  26254. // compatibility, we add the first occurence of the PROGRAM-DATE-TIME tag
  26255. // to the manifest object
  26256. // TODO: Consider removing this in future major version
  26257. this.manifest.dateTimeString = entry.dateTimeString;
  26258. this.manifest.dateTimeObject = entry.dateTimeObject;
  26259. }
  26260. currentUri.dateTimeString = entry.dateTimeString;
  26261. currentUri.dateTimeObject = entry.dateTimeObject;
  26262. },
  26263. targetduration: function targetduration() {
  26264. if (!isFinite(entry.duration) || entry.duration < 0) {
  26265. this.trigger('warn', {
  26266. message: 'ignoring invalid target duration: ' + entry.duration
  26267. });
  26268. return;
  26269. }
  26270. this.manifest.targetDuration = entry.duration;
  26271. setHoldBack.call(this, this.manifest);
  26272. },
  26273. start: function start() {
  26274. if (!entry.attributes || isNaN(entry.attributes['TIME-OFFSET'])) {
  26275. this.trigger('warn', {
  26276. message: 'ignoring start declaration without appropriate attribute list'
  26277. });
  26278. return;
  26279. }
  26280. this.manifest.start = {
  26281. timeOffset: entry.attributes['TIME-OFFSET'],
  26282. precise: entry.attributes.PRECISE
  26283. };
  26284. },
  26285. 'cue-out': function cueOut() {
  26286. currentUri.cueOut = entry.data;
  26287. },
  26288. 'cue-out-cont': function cueOutCont() {
  26289. currentUri.cueOutCont = entry.data;
  26290. },
  26291. 'cue-in': function cueIn() {
  26292. currentUri.cueIn = entry.data;
  26293. },
  26294. 'skip': function skip() {
  26295. this.manifest.skip = camelCaseKeys(entry.attributes);
  26296. this.warnOnMissingAttributes_('#EXT-X-SKIP', entry.attributes, ['SKIPPED-SEGMENTS']);
  26297. },
  26298. 'part': function part() {
  26299. var _this2 = this;
  26300. hasParts = true; // parts are always specifed before a segment
  26301. var segmentIndex = this.manifest.segments.length;
  26302. var part = camelCaseKeys(entry.attributes);
  26303. currentUri.parts = currentUri.parts || [];
  26304. currentUri.parts.push(part);
  26305. if (part.byterange) {
  26306. if (!part.byterange.hasOwnProperty('offset')) {
  26307. part.byterange.offset = lastPartByterangeEnd;
  26308. }
  26309. lastPartByterangeEnd = part.byterange.offset + part.byterange.length;
  26310. }
  26311. var partIndex = currentUri.parts.length - 1;
  26312. this.warnOnMissingAttributes_("#EXT-X-PART #" + partIndex + " for segment #" + segmentIndex, entry.attributes, ['URI', 'DURATION']);
  26313. if (this.manifest.renditionReports) {
  26314. this.manifest.renditionReports.forEach(function (r, i) {
  26315. if (!r.hasOwnProperty('lastPart')) {
  26316. _this2.trigger('warn', {
  26317. message: "#EXT-X-RENDITION-REPORT #" + i + " lacks required attribute(s): LAST-PART"
  26318. });
  26319. }
  26320. });
  26321. }
  26322. },
  26323. 'server-control': function serverControl() {
  26324. var attrs = this.manifest.serverControl = camelCaseKeys(entry.attributes);
  26325. if (!attrs.hasOwnProperty('canBlockReload')) {
  26326. attrs.canBlockReload = false;
  26327. this.trigger('info', {
  26328. message: '#EXT-X-SERVER-CONTROL defaulting CAN-BLOCK-RELOAD to false'
  26329. });
  26330. }
  26331. setHoldBack.call(this, this.manifest);
  26332. if (attrs.canSkipDateranges && !attrs.hasOwnProperty('canSkipUntil')) {
  26333. this.trigger('warn', {
  26334. message: '#EXT-X-SERVER-CONTROL lacks required attribute CAN-SKIP-UNTIL which is required when CAN-SKIP-DATERANGES is set'
  26335. });
  26336. }
  26337. },
  26338. 'preload-hint': function preloadHint() {
  26339. // parts are always specifed before a segment
  26340. var segmentIndex = this.manifest.segments.length;
  26341. var hint = camelCaseKeys(entry.attributes);
  26342. var isPart = hint.type && hint.type === 'PART';
  26343. currentUri.preloadHints = currentUri.preloadHints || [];
  26344. currentUri.preloadHints.push(hint);
  26345. if (hint.byterange) {
  26346. if (!hint.byterange.hasOwnProperty('offset')) {
  26347. // use last part byterange end or zero if not a part.
  26348. hint.byterange.offset = isPart ? lastPartByterangeEnd : 0;
  26349. if (isPart) {
  26350. lastPartByterangeEnd = hint.byterange.offset + hint.byterange.length;
  26351. }
  26352. }
  26353. }
  26354. var index = currentUri.preloadHints.length - 1;
  26355. this.warnOnMissingAttributes_("#EXT-X-PRELOAD-HINT #" + index + " for segment #" + segmentIndex, entry.attributes, ['TYPE', 'URI']);
  26356. if (!hint.type) {
  26357. return;
  26358. } // search through all preload hints except for the current one for
  26359. // a duplicate type.
  26360. for (var i = 0; i < currentUri.preloadHints.length - 1; i++) {
  26361. var otherHint = currentUri.preloadHints[i];
  26362. if (!otherHint.type) {
  26363. continue;
  26364. }
  26365. if (otherHint.type === hint.type) {
  26366. this.trigger('warn', {
  26367. message: "#EXT-X-PRELOAD-HINT #" + index + " for segment #" + segmentIndex + " has the same TYPE " + hint.type + " as preload hint #" + i
  26368. });
  26369. }
  26370. }
  26371. },
  26372. 'rendition-report': function renditionReport() {
  26373. var report = camelCaseKeys(entry.attributes);
  26374. this.manifest.renditionReports = this.manifest.renditionReports || [];
  26375. this.manifest.renditionReports.push(report);
  26376. var index = this.manifest.renditionReports.length - 1;
  26377. var required = ['LAST-MSN', 'URI'];
  26378. if (hasParts) {
  26379. required.push('LAST-PART');
  26380. }
  26381. this.warnOnMissingAttributes_("#EXT-X-RENDITION-REPORT #" + index, entry.attributes, required);
  26382. },
  26383. 'part-inf': function partInf() {
  26384. this.manifest.partInf = camelCaseKeys(entry.attributes);
  26385. this.warnOnMissingAttributes_('#EXT-X-PART-INF', entry.attributes, ['PART-TARGET']);
  26386. if (this.manifest.partInf.partTarget) {
  26387. this.manifest.partTargetDuration = this.manifest.partInf.partTarget;
  26388. }
  26389. setHoldBack.call(this, this.manifest);
  26390. }
  26391. })[entry.tagType] || noop).call(self);
  26392. },
  26393. uri: function uri() {
  26394. currentUri.uri = entry.uri;
  26395. uris.push(currentUri); // if no explicit duration was declared, use the target duration
  26396. if (this.manifest.targetDuration && !('duration' in currentUri)) {
  26397. this.trigger('warn', {
  26398. message: 'defaulting segment duration to the target duration'
  26399. });
  26400. currentUri.duration = this.manifest.targetDuration;
  26401. } // annotate with encryption information, if necessary
  26402. if (_key) {
  26403. currentUri.key = _key;
  26404. }
  26405. currentUri.timeline = currentTimeline; // annotate with initialization segment information, if necessary
  26406. if (currentMap) {
  26407. currentUri.map = currentMap;
  26408. } // reset the last byterange end as it needs to be 0 between parts
  26409. lastPartByterangeEnd = 0; // prepare for the next URI
  26410. currentUri = {};
  26411. },
  26412. comment: function comment() {// comments are not important for playback
  26413. },
  26414. custom: function custom() {
  26415. // if this is segment-level data attach the output to the segment
  26416. if (entry.segment) {
  26417. currentUri.custom = currentUri.custom || {};
  26418. currentUri.custom[entry.customType] = entry.data; // if this is manifest-level data attach to the top level manifest object
  26419. } else {
  26420. this.manifest.custom = this.manifest.custom || {};
  26421. this.manifest.custom[entry.customType] = entry.data;
  26422. }
  26423. }
  26424. })[entry.type].call(self);
  26425. });
  26426. return _this;
  26427. }
  26428. var _proto = Parser.prototype;
  26429. _proto.warnOnMissingAttributes_ = function warnOnMissingAttributes_(identifier, attributes, required) {
  26430. var missing = [];
  26431. required.forEach(function (key) {
  26432. if (!attributes.hasOwnProperty(key)) {
  26433. missing.push(key);
  26434. }
  26435. });
  26436. if (missing.length) {
  26437. this.trigger('warn', {
  26438. message: identifier + " lacks required attribute(s): " + missing.join(', ')
  26439. });
  26440. }
  26441. }
  26442. /**
  26443. * Parse the input string and update the manifest object.
  26444. *
  26445. * @param {string} chunk a potentially incomplete portion of the manifest
  26446. */
  26447. ;
  26448. _proto.push = function push(chunk) {
  26449. this.lineStream.push(chunk);
  26450. }
  26451. /**
  26452. * Flush any remaining input. This can be handy if the last line of an M3U8
  26453. * manifest did not contain a trailing newline but the file has been
  26454. * completely received.
  26455. */
  26456. ;
  26457. _proto.end = function end() {
  26458. // flush any buffered input
  26459. this.lineStream.push('\n');
  26460. this.trigger('end');
  26461. }
  26462. /**
  26463. * Add an additional parser for non-standard tags
  26464. *
  26465. * @param {Object} options a map of options for the added parser
  26466. * @param {RegExp} options.expression a regular expression to match the custom header
  26467. * @param {string} options.type the type to register to the output
  26468. * @param {Function} [options.dataParser] function to parse the line into an object
  26469. * @param {boolean} [options.segment] should tag data be attached to the segment object
  26470. */
  26471. ;
  26472. _proto.addParser = function addParser(options) {
  26473. this.parseStream.addParser(options);
  26474. }
  26475. /**
  26476. * Add a custom header mapper
  26477. *
  26478. * @param {Object} options
  26479. * @param {RegExp} options.expression a regular expression to match the custom header
  26480. * @param {Function} options.map function to translate tag into a different tag
  26481. */
  26482. ;
  26483. _proto.addTagMapper = function addTagMapper(options) {
  26484. this.parseStream.addTagMapper(options);
  26485. };
  26486. return Parser;
  26487. }(Stream);
  26488. var regexs = {
  26489. // to determine mime types
  26490. mp4: /^(av0?1|avc0?[1234]|vp0?9|flac|opus|mp3|mp4a|mp4v|stpp.ttml.im1t)/,
  26491. webm: /^(vp0?[89]|av0?1|opus|vorbis)/,
  26492. ogg: /^(vp0?[89]|theora|flac|opus|vorbis)/,
  26493. // to determine if a codec is audio or video
  26494. video: /^(av0?1|avc0?[1234]|vp0?[89]|hvc1|hev1|theora|mp4v)/,
  26495. audio: /^(mp4a|flac|vorbis|opus|ac-[34]|ec-3|alac|mp3|speex|aac)/,
  26496. text: /^(stpp.ttml.im1t)/,
  26497. // mux.js support regex
  26498. muxerVideo: /^(avc0?1)/,
  26499. muxerAudio: /^(mp4a)/,
  26500. // match nothing as muxer does not support text right now.
  26501. // there cannot never be a character before the start of a string
  26502. // so this matches nothing.
  26503. muxerText: /a^/
  26504. };
  26505. var mediaTypes = ['video', 'audio', 'text'];
  26506. var upperMediaTypes = ['Video', 'Audio', 'Text'];
  26507. /**
  26508. * Replace the old apple-style `avc1.<dd>.<dd>` codec string with the standard
  26509. * `avc1.<hhhhhh>`
  26510. *
  26511. * @param {string} codec
  26512. * Codec string to translate
  26513. * @return {string}
  26514. * The translated codec string
  26515. */
  26516. var translateLegacyCodec = function translateLegacyCodec(codec) {
  26517. if (!codec) {
  26518. return codec;
  26519. }
  26520. return codec.replace(/avc1\.(\d+)\.(\d+)/i, function (orig, profile, avcLevel) {
  26521. var profileHex = ('00' + Number(profile).toString(16)).slice(-2);
  26522. var avcLevelHex = ('00' + Number(avcLevel).toString(16)).slice(-2);
  26523. return 'avc1.' + profileHex + '00' + avcLevelHex;
  26524. });
  26525. };
  26526. /**
  26527. * @typedef {Object} ParsedCodecInfo
  26528. * @property {number} codecCount
  26529. * Number of codecs parsed
  26530. * @property {string} [videoCodec]
  26531. * Parsed video codec (if found)
  26532. * @property {string} [videoObjectTypeIndicator]
  26533. * Video object type indicator (if found)
  26534. * @property {string|null} audioProfile
  26535. * Audio profile
  26536. */
  26537. /**
  26538. * Parses a codec string to retrieve the number of codecs specified, the video codec and
  26539. * object type indicator, and the audio profile.
  26540. *
  26541. * @param {string} [codecString]
  26542. * The codec string to parse
  26543. * @return {ParsedCodecInfo}
  26544. * Parsed codec info
  26545. */
  26546. var parseCodecs = function parseCodecs(codecString) {
  26547. if (codecString === void 0) {
  26548. codecString = '';
  26549. }
  26550. var codecs = codecString.split(',');
  26551. var result = [];
  26552. codecs.forEach(function (codec) {
  26553. codec = codec.trim();
  26554. var codecType;
  26555. mediaTypes.forEach(function (name) {
  26556. var match = regexs[name].exec(codec.toLowerCase());
  26557. if (!match || match.length <= 1) {
  26558. return;
  26559. }
  26560. codecType = name; // maintain codec case
  26561. var type = codec.substring(0, match[1].length);
  26562. var details = codec.replace(type, '');
  26563. result.push({
  26564. type: type,
  26565. details: details,
  26566. mediaType: name
  26567. });
  26568. });
  26569. if (!codecType) {
  26570. result.push({
  26571. type: codec,
  26572. details: '',
  26573. mediaType: 'unknown'
  26574. });
  26575. }
  26576. });
  26577. return result;
  26578. };
  26579. /**
  26580. * Returns a ParsedCodecInfo object for the default alternate audio playlist if there is
  26581. * a default alternate audio playlist for the provided audio group.
  26582. *
  26583. * @param {Object} master
  26584. * The master playlist
  26585. * @param {string} audioGroupId
  26586. * ID of the audio group for which to find the default codec info
  26587. * @return {ParsedCodecInfo}
  26588. * Parsed codec info
  26589. */
  26590. var codecsFromDefault = function codecsFromDefault(master, audioGroupId) {
  26591. if (!master.mediaGroups.AUDIO || !audioGroupId) {
  26592. return null;
  26593. }
  26594. var audioGroup = master.mediaGroups.AUDIO[audioGroupId];
  26595. if (!audioGroup) {
  26596. return null;
  26597. }
  26598. for (var name in audioGroup) {
  26599. var audioType = audioGroup[name];
  26600. if (audioType["default"] && audioType.playlists) {
  26601. // codec should be the same for all playlists within the audio type
  26602. return parseCodecs(audioType.playlists[0].attributes.CODECS);
  26603. }
  26604. }
  26605. return null;
  26606. };
  26607. var isAudioCodec = function isAudioCodec(codec) {
  26608. if (codec === void 0) {
  26609. codec = '';
  26610. }
  26611. return regexs.audio.test(codec.trim().toLowerCase());
  26612. };
  26613. var isTextCodec = function isTextCodec(codec) {
  26614. if (codec === void 0) {
  26615. codec = '';
  26616. }
  26617. return regexs.text.test(codec.trim().toLowerCase());
  26618. };
  26619. var getMimeForCodec = function getMimeForCodec(codecString) {
  26620. if (!codecString || typeof codecString !== 'string') {
  26621. return;
  26622. }
  26623. var codecs = codecString.toLowerCase().split(',').map(function (c) {
  26624. return translateLegacyCodec(c.trim());
  26625. }); // default to video type
  26626. var type = 'video'; // only change to audio type if the only codec we have is
  26627. // audio
  26628. if (codecs.length === 1 && isAudioCodec(codecs[0])) {
  26629. type = 'audio';
  26630. } else if (codecs.length === 1 && isTextCodec(codecs[0])) {
  26631. // text uses application/<container> for now
  26632. type = 'application';
  26633. } // default the container to mp4
  26634. var container = 'mp4'; // every codec must be able to go into the container
  26635. // for that container to be the correct one
  26636. if (codecs.every(function (c) {
  26637. return regexs.mp4.test(c);
  26638. })) {
  26639. container = 'mp4';
  26640. } else if (codecs.every(function (c) {
  26641. return regexs.webm.test(c);
  26642. })) {
  26643. container = 'webm';
  26644. } else if (codecs.every(function (c) {
  26645. return regexs.ogg.test(c);
  26646. })) {
  26647. container = 'ogg';
  26648. }
  26649. return type + "/" + container + ";codecs=\"" + codecString + "\"";
  26650. };
  26651. var browserSupportsCodec = function browserSupportsCodec(codecString) {
  26652. if (codecString === void 0) {
  26653. codecString = '';
  26654. }
  26655. return window.MediaSource && window.MediaSource.isTypeSupported && window.MediaSource.isTypeSupported(getMimeForCodec(codecString)) || false;
  26656. };
  26657. var muxerSupportsCodec = function muxerSupportsCodec(codecString) {
  26658. if (codecString === void 0) {
  26659. codecString = '';
  26660. }
  26661. return codecString.toLowerCase().split(',').every(function (codec) {
  26662. codec = codec.trim(); // any match is supported.
  26663. for (var i = 0; i < upperMediaTypes.length; i++) {
  26664. var type = upperMediaTypes[i];
  26665. if (regexs["muxer" + type].test(codec)) {
  26666. return true;
  26667. }
  26668. }
  26669. return false;
  26670. });
  26671. };
  26672. var DEFAULT_AUDIO_CODEC = 'mp4a.40.2';
  26673. var DEFAULT_VIDEO_CODEC = 'avc1.4d400d';
  26674. var MPEGURL_REGEX = /^(audio|video|application)\/(x-|vnd\.apple\.)?mpegurl/i;
  26675. var DASH_REGEX = /^application\/dash\+xml/i;
  26676. /**
  26677. * Returns a string that describes the type of source based on a video source object's
  26678. * media type.
  26679. *
  26680. * @see {@link https://dev.w3.org/html5/pf-summary/video.html#dom-source-type|Source Type}
  26681. *
  26682. * @param {string} type
  26683. * Video source object media type
  26684. * @return {('hls'|'dash'|'vhs-json'|null)}
  26685. * VHS source type string
  26686. */
  26687. var simpleTypeFromSourceType = function simpleTypeFromSourceType(type) {
  26688. if (MPEGURL_REGEX.test(type)) {
  26689. return 'hls';
  26690. }
  26691. if (DASH_REGEX.test(type)) {
  26692. return 'dash';
  26693. } // Denotes the special case of a manifest object passed to http-streaming instead of a
  26694. // source URL.
  26695. //
  26696. // See https://en.wikipedia.org/wiki/Media_type for details on specifying media types.
  26697. //
  26698. // In this case, vnd stands for vendor, video.js for the organization, VHS for this
  26699. // project, and the +json suffix identifies the structure of the media type.
  26700. if (type === 'application/vnd.videojs.vhs+json') {
  26701. return 'vhs-json';
  26702. }
  26703. return null;
  26704. };
  26705. // const log2 = Math.log2 ? Math.log2 : (x) => (Math.log(x) / Math.log(2));
  26706. // we used to do this with log2 but BigInt does not support builtin math
  26707. // Math.ceil(log2(x));
  26708. var countBits = function countBits(x) {
  26709. return x.toString(2).length;
  26710. }; // count the number of whole bytes it would take to represent a number
  26711. var countBytes = function countBytes(x) {
  26712. return Math.ceil(countBits(x) / 8);
  26713. };
  26714. var isArrayBufferView = function isArrayBufferView(obj) {
  26715. if (ArrayBuffer.isView === 'function') {
  26716. return ArrayBuffer.isView(obj);
  26717. }
  26718. return obj && obj.buffer instanceof ArrayBuffer;
  26719. };
  26720. var isTypedArray = function isTypedArray(obj) {
  26721. return isArrayBufferView(obj);
  26722. };
  26723. var toUint8 = function toUint8(bytes) {
  26724. if (bytes instanceof Uint8Array) {
  26725. return bytes;
  26726. }
  26727. if (!Array.isArray(bytes) && !isTypedArray(bytes) && !(bytes instanceof ArrayBuffer)) {
  26728. // any non-number or NaN leads to empty uint8array
  26729. // eslint-disable-next-line
  26730. if (typeof bytes !== 'number' || typeof bytes === 'number' && bytes !== bytes) {
  26731. bytes = 0;
  26732. } else {
  26733. bytes = [bytes];
  26734. }
  26735. }
  26736. return new Uint8Array(bytes && bytes.buffer || bytes, bytes && bytes.byteOffset || 0, bytes && bytes.byteLength || 0);
  26737. };
  26738. var BigInt = window.BigInt || Number;
  26739. var BYTE_TABLE = [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
  26740. var bytesToNumber = function bytesToNumber(bytes, _temp) {
  26741. var _ref = _temp === void 0 ? {} : _temp,
  26742. _ref$signed = _ref.signed,
  26743. signed = _ref$signed === void 0 ? false : _ref$signed,
  26744. _ref$le = _ref.le,
  26745. le = _ref$le === void 0 ? false : _ref$le;
  26746. bytes = toUint8(bytes);
  26747. var fn = le ? 'reduce' : 'reduceRight';
  26748. var obj = bytes[fn] ? bytes[fn] : Array.prototype[fn];
  26749. var number = obj.call(bytes, function (total, _byte, i) {
  26750. var exponent = le ? i : Math.abs(i + 1 - bytes.length);
  26751. return total + BigInt(_byte) * BYTE_TABLE[exponent];
  26752. }, BigInt(0));
  26753. if (signed) {
  26754. var max = BYTE_TABLE[bytes.length] / BigInt(2) - BigInt(1);
  26755. number = BigInt(number);
  26756. if (number > max) {
  26757. number -= max;
  26758. number -= max;
  26759. number -= BigInt(2);
  26760. }
  26761. }
  26762. return Number(number);
  26763. };
  26764. var numberToBytes = function numberToBytes(number, _temp2) {
  26765. var _ref2 = _temp2 === void 0 ? {} : _temp2,
  26766. _ref2$le = _ref2.le,
  26767. le = _ref2$le === void 0 ? false : _ref2$le; // eslint-disable-next-line
  26768. if (typeof number !== 'bigint' && typeof number !== 'number' || typeof number === 'number' && number !== number) {
  26769. number = 0;
  26770. }
  26771. number = BigInt(number);
  26772. var byteCount = countBytes(number);
  26773. var bytes = new Uint8Array(new ArrayBuffer(byteCount));
  26774. for (var i = 0; i < byteCount; i++) {
  26775. var byteIndex = le ? i : Math.abs(i + 1 - bytes.length);
  26776. bytes[byteIndex] = Number(number / BYTE_TABLE[i] & BigInt(0xFF));
  26777. if (number < 0) {
  26778. bytes[byteIndex] = Math.abs(~bytes[byteIndex]);
  26779. bytes[byteIndex] -= i === 0 ? 1 : 2;
  26780. }
  26781. }
  26782. return bytes;
  26783. };
  26784. var stringToBytes = function stringToBytes(string, stringIsBytes) {
  26785. if (typeof string !== 'string' && string && typeof string.toString === 'function') {
  26786. string = string.toString();
  26787. }
  26788. if (typeof string !== 'string') {
  26789. return new Uint8Array();
  26790. } // If the string already is bytes, we don't have to do this
  26791. // otherwise we do this so that we split multi length characters
  26792. // into individual bytes
  26793. if (!stringIsBytes) {
  26794. string = unescape(encodeURIComponent(string));
  26795. }
  26796. var view = new Uint8Array(string.length);
  26797. for (var i = 0; i < string.length; i++) {
  26798. view[i] = string.charCodeAt(i);
  26799. }
  26800. return view;
  26801. };
  26802. var concatTypedArrays = function concatTypedArrays() {
  26803. for (var _len = arguments.length, buffers = new Array(_len), _key = 0; _key < _len; _key++) {
  26804. buffers[_key] = arguments[_key];
  26805. }
  26806. buffers = buffers.filter(function (b) {
  26807. return b && (b.byteLength || b.length) && typeof b !== 'string';
  26808. });
  26809. if (buffers.length <= 1) {
  26810. // for 0 length we will return empty uint8
  26811. // for 1 length we return the first uint8
  26812. return toUint8(buffers[0]);
  26813. }
  26814. var totalLen = buffers.reduce(function (total, buf, i) {
  26815. return total + (buf.byteLength || buf.length);
  26816. }, 0);
  26817. var tempBuffer = new Uint8Array(totalLen);
  26818. var offset = 0;
  26819. buffers.forEach(function (buf) {
  26820. buf = toUint8(buf);
  26821. tempBuffer.set(buf, offset);
  26822. offset += buf.byteLength;
  26823. });
  26824. return tempBuffer;
  26825. };
  26826. /**
  26827. * Check if the bytes "b" are contained within bytes "a".
  26828. *
  26829. * @param {Uint8Array|Array} a
  26830. * Bytes to check in
  26831. *
  26832. * @param {Uint8Array|Array} b
  26833. * Bytes to check for
  26834. *
  26835. * @param {Object} options
  26836. * options
  26837. *
  26838. * @param {Array|Uint8Array} [offset=0]
  26839. * offset to use when looking at bytes in a
  26840. *
  26841. * @param {Array|Uint8Array} [mask=[]]
  26842. * mask to use on bytes before comparison.
  26843. *
  26844. * @return {boolean}
  26845. * If all bytes in b are inside of a, taking into account
  26846. * bit masks.
  26847. */
  26848. var bytesMatch = function bytesMatch(a, b, _temp3) {
  26849. var _ref3 = _temp3 === void 0 ? {} : _temp3,
  26850. _ref3$offset = _ref3.offset,
  26851. offset = _ref3$offset === void 0 ? 0 : _ref3$offset,
  26852. _ref3$mask = _ref3.mask,
  26853. mask = _ref3$mask === void 0 ? [] : _ref3$mask;
  26854. a = toUint8(a);
  26855. b = toUint8(b); // ie 11 does not support uint8 every
  26856. var fn = b.every ? b.every : Array.prototype.every;
  26857. return b.length && a.length - offset >= b.length && // ie 11 doesn't support every on uin8
  26858. fn.call(b, function (bByte, i) {
  26859. var aByte = mask[i] ? mask[i] & a[offset + i] : a[offset + i];
  26860. return bByte === aByte;
  26861. });
  26862. };
  26863. var DEFAULT_LOCATION = 'http://example.com';
  26864. var resolveUrl$1 = function resolveUrl(baseUrl, relativeUrl) {
  26865. // return early if we don't need to resolve
  26866. if (/^[a-z]+:/i.test(relativeUrl)) {
  26867. return relativeUrl;
  26868. } // if baseUrl is a data URI, ignore it and resolve everything relative to window.location
  26869. if (/^data:/.test(baseUrl)) {
  26870. baseUrl = window.location && window.location.href || '';
  26871. } // IE11 supports URL but not the URL constructor
  26872. // feature detect the behavior we want
  26873. var nativeURL = typeof window.URL === 'function';
  26874. var protocolLess = /^\/\//.test(baseUrl); // remove location if window.location isn't available (i.e. we're in node)
  26875. // and if baseUrl isn't an absolute url
  26876. var removeLocation = !window.location && !/\/\//i.test(baseUrl); // if the base URL is relative then combine with the current location
  26877. if (nativeURL) {
  26878. baseUrl = new window.URL(baseUrl, window.location || DEFAULT_LOCATION);
  26879. } else if (!/\/\//i.test(baseUrl)) {
  26880. baseUrl = urlToolkit.buildAbsoluteURL(window.location && window.location.href || '', baseUrl);
  26881. }
  26882. if (nativeURL) {
  26883. var newUrl = new URL(relativeUrl, baseUrl); // if we're a protocol-less url, remove the protocol
  26884. // and if we're location-less, remove the location
  26885. // otherwise, return the url unmodified
  26886. if (removeLocation) {
  26887. return newUrl.href.slice(DEFAULT_LOCATION.length);
  26888. } else if (protocolLess) {
  26889. return newUrl.href.slice(newUrl.protocol.length);
  26890. }
  26891. return newUrl.href;
  26892. }
  26893. return urlToolkit.buildAbsoluteURL(baseUrl, relativeUrl);
  26894. };
  26895. /**
  26896. * Loops through all supported media groups in master and calls the provided
  26897. * callback for each group
  26898. *
  26899. * @param {Object} master
  26900. * The parsed master manifest object
  26901. * @param {string[]} groups
  26902. * The media groups to call the callback for
  26903. * @param {Function} callback
  26904. * Callback to call for each media group
  26905. */
  26906. var forEachMediaGroup$1 = function forEachMediaGroup(master, groups, callback) {
  26907. groups.forEach(function (mediaType) {
  26908. for (var groupKey in master.mediaGroups[mediaType]) {
  26909. for (var labelKey in master.mediaGroups[mediaType][groupKey]) {
  26910. var mediaProperties = master.mediaGroups[mediaType][groupKey][labelKey];
  26911. callback(mediaProperties, mediaType, groupKey, labelKey);
  26912. }
  26913. }
  26914. });
  26915. };
  26916. var atob = function atob(s) {
  26917. return window.atob ? window.atob(s) : Buffer.from(s, 'base64').toString('binary');
  26918. };
  26919. function decodeB64ToUint8Array(b64Text) {
  26920. var decodedString = atob(b64Text);
  26921. var array = new Uint8Array(decodedString.length);
  26922. for (var i = 0; i < decodedString.length; i++) {
  26923. array[i] = decodedString.charCodeAt(i);
  26924. }
  26925. return array;
  26926. }
  26927. /**
  26928. * Ponyfill for `Array.prototype.find` which is only available in ES6 runtimes.
  26929. *
  26930. * Works with anything that has a `length` property and index access properties, including NodeList.
  26931. *
  26932. * @template {unknown} T
  26933. * @param {Array<T> | ({length:number, [number]: T})} list
  26934. * @param {function (item: T, index: number, list:Array<T> | ({length:number, [number]: T})):boolean} predicate
  26935. * @param {Partial<Pick<ArrayConstructor['prototype'], 'find'>>?} ac `Array.prototype` by default,
  26936. * allows injecting a custom implementation in tests
  26937. * @returns {T | undefined}
  26938. *
  26939. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
  26940. * @see https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.find
  26941. */
  26942. function find$1(list, predicate, ac) {
  26943. if (ac === undefined) {
  26944. ac = Array.prototype;
  26945. }
  26946. if (list && typeof ac.find === 'function') {
  26947. return ac.find.call(list, predicate);
  26948. }
  26949. for (var i = 0; i < list.length; i++) {
  26950. if (Object.prototype.hasOwnProperty.call(list, i)) {
  26951. var item = list[i];
  26952. if (predicate.call(undefined, item, i, list)) {
  26953. return item;
  26954. }
  26955. }
  26956. }
  26957. }
  26958. /**
  26959. * "Shallow freezes" an object to render it immutable.
  26960. * Uses `Object.freeze` if available,
  26961. * otherwise the immutability is only in the type.
  26962. *
  26963. * Is used to create "enum like" objects.
  26964. *
  26965. * @template T
  26966. * @param {T} object the object to freeze
  26967. * @param {Pick<ObjectConstructor, 'freeze'> = Object} oc `Object` by default,
  26968. * allows to inject custom object constructor for tests
  26969. * @returns {Readonly<T>}
  26970. *
  26971. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
  26972. */
  26973. function freeze(object, oc) {
  26974. if (oc === undefined) {
  26975. oc = Object;
  26976. }
  26977. return oc && typeof oc.freeze === 'function' ? oc.freeze(object) : object;
  26978. }
  26979. /**
  26980. * Since we can not rely on `Object.assign` we provide a simplified version
  26981. * that is sufficient for our needs.
  26982. *
  26983. * @param {Object} target
  26984. * @param {Object | null | undefined} source
  26985. *
  26986. * @returns {Object} target
  26987. * @throws TypeError if target is not an object
  26988. *
  26989. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  26990. * @see https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.assign
  26991. */
  26992. function assign(target, source) {
  26993. if (target === null || typeof target !== 'object') {
  26994. throw new TypeError('target is not an object');
  26995. }
  26996. for (var key in source) {
  26997. if (Object.prototype.hasOwnProperty.call(source, key)) {
  26998. target[key] = source[key];
  26999. }
  27000. }
  27001. return target;
  27002. }
  27003. /**
  27004. * All mime types that are allowed as input to `DOMParser.parseFromString`
  27005. *
  27006. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#Argument02 MDN
  27007. * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#domparsersupportedtype WHATWG HTML Spec
  27008. * @see DOMParser.prototype.parseFromString
  27009. */
  27010. var MIME_TYPE = freeze({
  27011. /**
  27012. * `text/html`, the only mime type that triggers treating an XML document as HTML.
  27013. *
  27014. * @see DOMParser.SupportedType.isHTML
  27015. * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration
  27016. * @see https://en.wikipedia.org/wiki/HTML Wikipedia
  27017. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN
  27018. * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring WHATWG HTML Spec
  27019. */
  27020. HTML: 'text/html',
  27021. /**
  27022. * Helper method to check a mime type if it indicates an HTML document
  27023. *
  27024. * @param {string} [value]
  27025. * @returns {boolean}
  27026. *
  27027. * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration
  27028. * @see https://en.wikipedia.org/wiki/HTML Wikipedia
  27029. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN
  27030. * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring */
  27031. isHTML: function isHTML(value) {
  27032. return value === MIME_TYPE.HTML;
  27033. },
  27034. /**
  27035. * `application/xml`, the standard mime type for XML documents.
  27036. *
  27037. * @see https://www.iana.org/assignments/media-types/application/xml IANA MimeType registration
  27038. * @see https://tools.ietf.org/html/rfc7303#section-9.1 RFC 7303
  27039. * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia
  27040. */
  27041. XML_APPLICATION: 'application/xml',
  27042. /**
  27043. * `text/html`, an alias for `application/xml`.
  27044. *
  27045. * @see https://tools.ietf.org/html/rfc7303#section-9.2 RFC 7303
  27046. * @see https://www.iana.org/assignments/media-types/text/xml IANA MimeType registration
  27047. * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia
  27048. */
  27049. XML_TEXT: 'text/xml',
  27050. /**
  27051. * `application/xhtml+xml`, indicates an XML document that has the default HTML namespace,
  27052. * but is parsed as an XML document.
  27053. *
  27054. * @see https://www.iana.org/assignments/media-types/application/xhtml+xml IANA MimeType registration
  27055. * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument WHATWG DOM Spec
  27056. * @see https://en.wikipedia.org/wiki/XHTML Wikipedia
  27057. */
  27058. XML_XHTML_APPLICATION: 'application/xhtml+xml',
  27059. /**
  27060. * `image/svg+xml`,
  27061. *
  27062. * @see https://www.iana.org/assignments/media-types/image/svg+xml IANA MimeType registration
  27063. * @see https://www.w3.org/TR/SVG11/ W3C SVG 1.1
  27064. * @see https://en.wikipedia.org/wiki/Scalable_Vector_Graphics Wikipedia
  27065. */
  27066. XML_SVG_IMAGE: 'image/svg+xml'
  27067. });
  27068. /**
  27069. * Namespaces that are used in this code base.
  27070. *
  27071. * @see http://www.w3.org/TR/REC-xml-names
  27072. */
  27073. var NAMESPACE$3 = freeze({
  27074. /**
  27075. * The XHTML namespace.
  27076. *
  27077. * @see http://www.w3.org/1999/xhtml
  27078. */
  27079. HTML: 'http://www.w3.org/1999/xhtml',
  27080. /**
  27081. * Checks if `uri` equals `NAMESPACE.HTML`.
  27082. *
  27083. * @param {string} [uri]
  27084. *
  27085. * @see NAMESPACE.HTML
  27086. */
  27087. isHTML: function isHTML(uri) {
  27088. return uri === NAMESPACE$3.HTML;
  27089. },
  27090. /**
  27091. * The SVG namespace.
  27092. *
  27093. * @see http://www.w3.org/2000/svg
  27094. */
  27095. SVG: 'http://www.w3.org/2000/svg',
  27096. /**
  27097. * The `xml:` namespace.
  27098. *
  27099. * @see http://www.w3.org/XML/1998/namespace
  27100. */
  27101. XML: 'http://www.w3.org/XML/1998/namespace',
  27102. /**
  27103. * The `xmlns:` namespace
  27104. *
  27105. * @see https://www.w3.org/2000/xmlns/
  27106. */
  27107. XMLNS: 'http://www.w3.org/2000/xmlns/'
  27108. });
  27109. var assign_1 = assign;
  27110. var find_1 = find$1;
  27111. var freeze_1 = freeze;
  27112. var MIME_TYPE_1 = MIME_TYPE;
  27113. var NAMESPACE_1 = NAMESPACE$3;
  27114. var conventions = {
  27115. assign: assign_1,
  27116. find: find_1,
  27117. freeze: freeze_1,
  27118. MIME_TYPE: MIME_TYPE_1,
  27119. NAMESPACE: NAMESPACE_1
  27120. };
  27121. var find = conventions.find;
  27122. var NAMESPACE$2 = conventions.NAMESPACE;
  27123. /**
  27124. * A prerequisite for `[].filter`, to drop elements that are empty
  27125. * @param {string} input
  27126. * @returns {boolean}
  27127. */
  27128. function notEmptyString(input) {
  27129. return input !== '';
  27130. }
  27131. /**
  27132. * @see https://infra.spec.whatwg.org/#split-on-ascii-whitespace
  27133. * @see https://infra.spec.whatwg.org/#ascii-whitespace
  27134. *
  27135. * @param {string} input
  27136. * @returns {string[]} (can be empty)
  27137. */
  27138. function splitOnASCIIWhitespace(input) {
  27139. // U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, U+0020 SPACE
  27140. return input ? input.split(/[\t\n\f\r ]+/).filter(notEmptyString) : [];
  27141. }
  27142. /**
  27143. * Adds element as a key to current if it is not already present.
  27144. *
  27145. * @param {Record<string, boolean | undefined>} current
  27146. * @param {string} element
  27147. * @returns {Record<string, boolean | undefined>}
  27148. */
  27149. function orderedSetReducer(current, element) {
  27150. if (!current.hasOwnProperty(element)) {
  27151. current[element] = true;
  27152. }
  27153. return current;
  27154. }
  27155. /**
  27156. * @see https://infra.spec.whatwg.org/#ordered-set
  27157. * @param {string} input
  27158. * @returns {string[]}
  27159. */
  27160. function toOrderedSet(input) {
  27161. if (!input) return [];
  27162. var list = splitOnASCIIWhitespace(input);
  27163. return Object.keys(list.reduce(orderedSetReducer, {}));
  27164. }
  27165. /**
  27166. * Uses `list.indexOf` to implement something like `Array.prototype.includes`,
  27167. * which we can not rely on being available.
  27168. *
  27169. * @param {any[]} list
  27170. * @returns {function(any): boolean}
  27171. */
  27172. function arrayIncludes(list) {
  27173. return function (element) {
  27174. return list && list.indexOf(element) !== -1;
  27175. };
  27176. }
  27177. function copy(src, dest) {
  27178. for (var p in src) {
  27179. if (Object.prototype.hasOwnProperty.call(src, p)) {
  27180. dest[p] = src[p];
  27181. }
  27182. }
  27183. }
  27184. /**
  27185. ^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
  27186. ^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
  27187. */
  27188. function _extends(Class, Super) {
  27189. var pt = Class.prototype;
  27190. if (!(pt instanceof Super)) {
  27191. var t = function t() {};
  27192. t.prototype = Super.prototype;
  27193. t = new t();
  27194. copy(pt, t);
  27195. Class.prototype = pt = t;
  27196. }
  27197. if (pt.constructor != Class) {
  27198. if (typeof Class != 'function') {
  27199. console.error("unknown Class:" + Class);
  27200. }
  27201. pt.constructor = Class;
  27202. }
  27203. } // Node Types
  27204. var NodeType = {};
  27205. var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
  27206. var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
  27207. var TEXT_NODE = NodeType.TEXT_NODE = 3;
  27208. var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
  27209. var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
  27210. var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
  27211. var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
  27212. var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
  27213. var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
  27214. var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
  27215. var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
  27216. var NOTATION_NODE = NodeType.NOTATION_NODE = 12; // ExceptionCode
  27217. var ExceptionCode = {};
  27218. var ExceptionMessage = {};
  27219. ExceptionCode.INDEX_SIZE_ERR = (ExceptionMessage[1] = "Index size error", 1);
  27220. ExceptionCode.DOMSTRING_SIZE_ERR = (ExceptionMessage[2] = "DOMString size error", 2);
  27221. var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = (ExceptionMessage[3] = "Hierarchy request error", 3);
  27222. ExceptionCode.WRONG_DOCUMENT_ERR = (ExceptionMessage[4] = "Wrong document", 4);
  27223. ExceptionCode.INVALID_CHARACTER_ERR = (ExceptionMessage[5] = "Invalid character", 5);
  27224. ExceptionCode.NO_DATA_ALLOWED_ERR = (ExceptionMessage[6] = "No data allowed", 6);
  27225. ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = (ExceptionMessage[7] = "No modification allowed", 7);
  27226. var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = (ExceptionMessage[8] = "Not found", 8);
  27227. ExceptionCode.NOT_SUPPORTED_ERR = (ExceptionMessage[9] = "Not supported", 9);
  27228. var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = (ExceptionMessage[10] = "Attribute in use", 10); //level2
  27229. ExceptionCode.INVALID_STATE_ERR = (ExceptionMessage[11] = "Invalid state", 11);
  27230. ExceptionCode.SYNTAX_ERR = (ExceptionMessage[12] = "Syntax error", 12);
  27231. ExceptionCode.INVALID_MODIFICATION_ERR = (ExceptionMessage[13] = "Invalid modification", 13);
  27232. ExceptionCode.NAMESPACE_ERR = (ExceptionMessage[14] = "Invalid namespace", 14);
  27233. ExceptionCode.INVALID_ACCESS_ERR = (ExceptionMessage[15] = "Invalid access", 15);
  27234. /**
  27235. * DOM Level 2
  27236. * Object DOMException
  27237. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
  27238. * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
  27239. */
  27240. function DOMException(code, message) {
  27241. if (message instanceof Error) {
  27242. var error = message;
  27243. } else {
  27244. error = this;
  27245. Error.call(this, ExceptionMessage[code]);
  27246. this.message = ExceptionMessage[code];
  27247. if (Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
  27248. }
  27249. error.code = code;
  27250. if (message) this.message = this.message + ": " + message;
  27251. return error;
  27252. }
  27253. DOMException.prototype = Error.prototype;
  27254. copy(ExceptionCode, DOMException);
  27255. /**
  27256. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
  27257. * 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.
  27258. * The items in the NodeList are accessible via an integral index, starting from 0.
  27259. */
  27260. function NodeList() {}
  27261. NodeList.prototype = {
  27262. /**
  27263. * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
  27264. * @standard level1
  27265. */
  27266. length: 0,
  27267. /**
  27268. * 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.
  27269. * @standard level1
  27270. * @param index unsigned long
  27271. * Index into the collection.
  27272. * @return Node
  27273. * The node at the indexth position in the NodeList, or null if that is not a valid index.
  27274. */
  27275. item: function item(index) {
  27276. return this[index] || null;
  27277. },
  27278. toString: function toString(isHTML, nodeFilter) {
  27279. for (var buf = [], i = 0; i < this.length; i++) {
  27280. serializeToString(this[i], buf, isHTML, nodeFilter);
  27281. }
  27282. return buf.join('');
  27283. },
  27284. /**
  27285. * @private
  27286. * @param {function (Node):boolean} predicate
  27287. * @returns {Node[]}
  27288. */
  27289. filter: function filter(predicate) {
  27290. return Array.prototype.filter.call(this, predicate);
  27291. },
  27292. /**
  27293. * @private
  27294. * @param {Node} item
  27295. * @returns {number}
  27296. */
  27297. indexOf: function indexOf(item) {
  27298. return Array.prototype.indexOf.call(this, item);
  27299. }
  27300. };
  27301. function LiveNodeList(node, refresh) {
  27302. this._node = node;
  27303. this._refresh = refresh;
  27304. _updateLiveList(this);
  27305. }
  27306. function _updateLiveList(list) {
  27307. var inc = list._node._inc || list._node.ownerDocument._inc;
  27308. if (list._inc != inc) {
  27309. var ls = list._refresh(list._node); //console.log(ls.length)
  27310. __set__(list, 'length', ls.length);
  27311. copy(ls, list);
  27312. list._inc = inc;
  27313. }
  27314. }
  27315. LiveNodeList.prototype.item = function (i) {
  27316. _updateLiveList(this);
  27317. return this[i];
  27318. };
  27319. _extends(LiveNodeList, NodeList);
  27320. /**
  27321. * Objects implementing the NamedNodeMap interface are used
  27322. * to represent collections of nodes that can be accessed by name.
  27323. * Note that NamedNodeMap does not inherit from NodeList;
  27324. * NamedNodeMaps are not maintained in any particular order.
  27325. * Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index,
  27326. * but this is simply to allow convenient enumeration of the contents of a NamedNodeMap,
  27327. * and does not imply that the DOM specifies an order to these Nodes.
  27328. * NamedNodeMap objects in the DOM are live.
  27329. * used for attributes or DocumentType entities
  27330. */
  27331. function NamedNodeMap() {}
  27332. function _findNodeIndex(list, node) {
  27333. var i = list.length;
  27334. while (i--) {
  27335. if (list[i] === node) {
  27336. return i;
  27337. }
  27338. }
  27339. }
  27340. function _addNamedNode(el, list, newAttr, oldAttr) {
  27341. if (oldAttr) {
  27342. list[_findNodeIndex(list, oldAttr)] = newAttr;
  27343. } else {
  27344. list[list.length++] = newAttr;
  27345. }
  27346. if (el) {
  27347. newAttr.ownerElement = el;
  27348. var doc = el.ownerDocument;
  27349. if (doc) {
  27350. oldAttr && _onRemoveAttribute(doc, el, oldAttr);
  27351. _onAddAttribute(doc, el, newAttr);
  27352. }
  27353. }
  27354. }
  27355. function _removeNamedNode(el, list, attr) {
  27356. //console.log('remove attr:'+attr)
  27357. var i = _findNodeIndex(list, attr);
  27358. if (i >= 0) {
  27359. var lastIndex = list.length - 1;
  27360. while (i < lastIndex) {
  27361. list[i] = list[++i];
  27362. }
  27363. list.length = lastIndex;
  27364. if (el) {
  27365. var doc = el.ownerDocument;
  27366. if (doc) {
  27367. _onRemoveAttribute(doc, el, attr);
  27368. attr.ownerElement = null;
  27369. }
  27370. }
  27371. } else {
  27372. throw new DOMException(NOT_FOUND_ERR, new Error(el.tagName + '@' + attr));
  27373. }
  27374. }
  27375. NamedNodeMap.prototype = {
  27376. length: 0,
  27377. item: NodeList.prototype.item,
  27378. getNamedItem: function getNamedItem(key) {
  27379. // if(key.indexOf(':')>0 || key == 'xmlns'){
  27380. // return null;
  27381. // }
  27382. //console.log()
  27383. var i = this.length;
  27384. while (i--) {
  27385. var attr = this[i]; //console.log(attr.nodeName,key)
  27386. if (attr.nodeName == key) {
  27387. return attr;
  27388. }
  27389. }
  27390. },
  27391. setNamedItem: function setNamedItem(attr) {
  27392. var el = attr.ownerElement;
  27393. if (el && el != this._ownerElement) {
  27394. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  27395. }
  27396. var oldAttr = this.getNamedItem(attr.nodeName);
  27397. _addNamedNode(this._ownerElement, this, attr, oldAttr);
  27398. return oldAttr;
  27399. },
  27400. /* returns Node */
  27401. setNamedItemNS: function setNamedItemNS(attr) {
  27402. // raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
  27403. var el = attr.ownerElement,
  27404. oldAttr;
  27405. if (el && el != this._ownerElement) {
  27406. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  27407. }
  27408. oldAttr = this.getNamedItemNS(attr.namespaceURI, attr.localName);
  27409. _addNamedNode(this._ownerElement, this, attr, oldAttr);
  27410. return oldAttr;
  27411. },
  27412. /* returns Node */
  27413. removeNamedItem: function removeNamedItem(key) {
  27414. var attr = this.getNamedItem(key);
  27415. _removeNamedNode(this._ownerElement, this, attr);
  27416. return attr;
  27417. },
  27418. // raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
  27419. //for level2
  27420. removeNamedItemNS: function removeNamedItemNS(namespaceURI, localName) {
  27421. var attr = this.getNamedItemNS(namespaceURI, localName);
  27422. _removeNamedNode(this._ownerElement, this, attr);
  27423. return attr;
  27424. },
  27425. getNamedItemNS: function getNamedItemNS(namespaceURI, localName) {
  27426. var i = this.length;
  27427. while (i--) {
  27428. var node = this[i];
  27429. if (node.localName == localName && node.namespaceURI == namespaceURI) {
  27430. return node;
  27431. }
  27432. }
  27433. return null;
  27434. }
  27435. };
  27436. /**
  27437. * The DOMImplementation interface represents an object providing methods
  27438. * which are not dependent on any particular document.
  27439. * Such an object is returned by the `Document.implementation` property.
  27440. *
  27441. * __The individual methods describe the differences compared to the specs.__
  27442. *
  27443. * @constructor
  27444. *
  27445. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation MDN
  27446. * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490 DOM Level 1 Core (Initial)
  27447. * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-102161490 DOM Level 2 Core
  27448. * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-102161490 DOM Level 3 Core
  27449. * @see https://dom.spec.whatwg.org/#domimplementation DOM Living Standard
  27450. */
  27451. function DOMImplementation$1() {}
  27452. DOMImplementation$1.prototype = {
  27453. /**
  27454. * The DOMImplementation.hasFeature() method returns a Boolean flag indicating if a given feature is supported.
  27455. * The different implementations fairly diverged in what kind of features were reported.
  27456. * The latest version of the spec settled to force this method to always return true, where the functionality was accurate and in use.
  27457. *
  27458. * @deprecated It is deprecated and modern browsers return true in all cases.
  27459. *
  27460. * @param {string} feature
  27461. * @param {string} [version]
  27462. * @returns {boolean} always true
  27463. *
  27464. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/hasFeature MDN
  27465. * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-5CED94D7 DOM Level 1 Core
  27466. * @see https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature DOM Living Standard
  27467. */
  27468. hasFeature: function hasFeature(feature, version) {
  27469. return true;
  27470. },
  27471. /**
  27472. * Creates an XML Document object of the specified type with its document element.
  27473. *
  27474. * __It behaves slightly different from the description in the living standard__:
  27475. * - There is no interface/class `XMLDocument`, it returns a `Document` instance.
  27476. * - `contentType`, `encoding`, `mode`, `origin`, `url` fields are currently not declared.
  27477. * - this implementation is not validating names or qualified names
  27478. * (when parsing XML strings, the SAX parser takes care of that)
  27479. *
  27480. * @param {string|null} namespaceURI
  27481. * @param {string} qualifiedName
  27482. * @param {DocumentType=null} doctype
  27483. * @returns {Document}
  27484. *
  27485. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument MDN
  27486. * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocument DOM Level 2 Core (initial)
  27487. * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument DOM Level 2 Core
  27488. *
  27489. * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract
  27490. * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names
  27491. * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names
  27492. */
  27493. createDocument: function createDocument(namespaceURI, qualifiedName, doctype) {
  27494. var doc = new Document();
  27495. doc.implementation = this;
  27496. doc.childNodes = new NodeList();
  27497. doc.doctype = doctype || null;
  27498. if (doctype) {
  27499. doc.appendChild(doctype);
  27500. }
  27501. if (qualifiedName) {
  27502. var root = doc.createElementNS(namespaceURI, qualifiedName);
  27503. doc.appendChild(root);
  27504. }
  27505. return doc;
  27506. },
  27507. /**
  27508. * Returns a doctype, with the given `qualifiedName`, `publicId`, and `systemId`.
  27509. *
  27510. * __This behavior is slightly different from the in the specs__:
  27511. * - this implementation is not validating names or qualified names
  27512. * (when parsing XML strings, the SAX parser takes care of that)
  27513. *
  27514. * @param {string} qualifiedName
  27515. * @param {string} [publicId]
  27516. * @param {string} [systemId]
  27517. * @returns {DocumentType} which can either be used with `DOMImplementation.createDocument` upon document creation
  27518. * or can be put into the document via methods like `Node.insertBefore()` or `Node.replaceChild()`
  27519. *
  27520. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocumentType MDN
  27521. * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocType DOM Level 2 Core
  27522. * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype DOM Living Standard
  27523. *
  27524. * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract
  27525. * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names
  27526. * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names
  27527. */
  27528. createDocumentType: function createDocumentType(qualifiedName, publicId, systemId) {
  27529. var node = new DocumentType();
  27530. node.name = qualifiedName;
  27531. node.nodeName = qualifiedName;
  27532. node.publicId = publicId || '';
  27533. node.systemId = systemId || '';
  27534. return node;
  27535. }
  27536. };
  27537. /**
  27538. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
  27539. */
  27540. function Node() {}
  27541. Node.prototype = {
  27542. firstChild: null,
  27543. lastChild: null,
  27544. previousSibling: null,
  27545. nextSibling: null,
  27546. attributes: null,
  27547. parentNode: null,
  27548. childNodes: null,
  27549. ownerDocument: null,
  27550. nodeValue: null,
  27551. namespaceURI: null,
  27552. prefix: null,
  27553. localName: null,
  27554. // Modified in DOM Level 2:
  27555. insertBefore: function insertBefore(newChild, refChild) {
  27556. //raises
  27557. return _insertBefore(this, newChild, refChild);
  27558. },
  27559. replaceChild: function replaceChild(newChild, oldChild) {
  27560. //raises
  27561. _insertBefore(this, newChild, oldChild, assertPreReplacementValidityInDocument);
  27562. if (oldChild) {
  27563. this.removeChild(oldChild);
  27564. }
  27565. },
  27566. removeChild: function removeChild(oldChild) {
  27567. return _removeChild(this, oldChild);
  27568. },
  27569. appendChild: function appendChild(newChild) {
  27570. return this.insertBefore(newChild, null);
  27571. },
  27572. hasChildNodes: function hasChildNodes() {
  27573. return this.firstChild != null;
  27574. },
  27575. cloneNode: function cloneNode(deep) {
  27576. return _cloneNode(this.ownerDocument || this, this, deep);
  27577. },
  27578. // Modified in DOM Level 2:
  27579. normalize: function normalize() {
  27580. var child = this.firstChild;
  27581. while (child) {
  27582. var next = child.nextSibling;
  27583. if (next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE) {
  27584. this.removeChild(next);
  27585. child.appendData(next.data);
  27586. } else {
  27587. child.normalize();
  27588. child = next;
  27589. }
  27590. }
  27591. },
  27592. // Introduced in DOM Level 2:
  27593. isSupported: function isSupported(feature, version) {
  27594. return this.ownerDocument.implementation.hasFeature(feature, version);
  27595. },
  27596. // Introduced in DOM Level 2:
  27597. hasAttributes: function hasAttributes() {
  27598. return this.attributes.length > 0;
  27599. },
  27600. /**
  27601. * Look up the prefix associated to the given namespace URI, starting from this node.
  27602. * **The default namespace declarations are ignored by this method.**
  27603. * See Namespace Prefix Lookup for details on the algorithm used by this method.
  27604. *
  27605. * _Note: The implementation seems to be incomplete when compared to the algorithm described in the specs._
  27606. *
  27607. * @param {string | null} namespaceURI
  27608. * @returns {string | null}
  27609. * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespacePrefix
  27610. * @see https://www.w3.org/TR/DOM-Level-3-Core/namespaces-algorithms.html#lookupNamespacePrefixAlgo
  27611. * @see https://dom.spec.whatwg.org/#dom-node-lookupprefix
  27612. * @see https://github.com/xmldom/xmldom/issues/322
  27613. */
  27614. lookupPrefix: function lookupPrefix(namespaceURI) {
  27615. var el = this;
  27616. while (el) {
  27617. var map = el._nsMap; //console.dir(map)
  27618. if (map) {
  27619. for (var n in map) {
  27620. if (Object.prototype.hasOwnProperty.call(map, n) && map[n] === namespaceURI) {
  27621. return n;
  27622. }
  27623. }
  27624. }
  27625. el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode;
  27626. }
  27627. return null;
  27628. },
  27629. // Introduced in DOM Level 3:
  27630. lookupNamespaceURI: function lookupNamespaceURI(prefix) {
  27631. var el = this;
  27632. while (el) {
  27633. var map = el._nsMap; //console.dir(map)
  27634. if (map) {
  27635. if (Object.prototype.hasOwnProperty.call(map, prefix)) {
  27636. return map[prefix];
  27637. }
  27638. }
  27639. el = el.nodeType == ATTRIBUTE_NODE ? el.ownerDocument : el.parentNode;
  27640. }
  27641. return null;
  27642. },
  27643. // Introduced in DOM Level 3:
  27644. isDefaultNamespace: function isDefaultNamespace(namespaceURI) {
  27645. var prefix = this.lookupPrefix(namespaceURI);
  27646. return prefix == null;
  27647. }
  27648. };
  27649. function _xmlEncoder(c) {
  27650. return c == '<' && '&lt;' || c == '>' && '&gt;' || c == '&' && '&amp;' || c == '"' && '&quot;' || '&#' + c.charCodeAt() + ';';
  27651. }
  27652. copy(NodeType, Node);
  27653. copy(NodeType, Node.prototype);
  27654. /**
  27655. * @param callback return true for continue,false for break
  27656. * @return boolean true: break visit;
  27657. */
  27658. function _visitNode(node, callback) {
  27659. if (callback(node)) {
  27660. return true;
  27661. }
  27662. if (node = node.firstChild) {
  27663. do {
  27664. if (_visitNode(node, callback)) {
  27665. return true;
  27666. }
  27667. } while (node = node.nextSibling);
  27668. }
  27669. }
  27670. function Document() {
  27671. this.ownerDocument = this;
  27672. }
  27673. function _onAddAttribute(doc, el, newAttr) {
  27674. doc && doc._inc++;
  27675. var ns = newAttr.namespaceURI;
  27676. if (ns === NAMESPACE$2.XMLNS) {
  27677. //update namespace
  27678. el._nsMap[newAttr.prefix ? newAttr.localName : ''] = newAttr.value;
  27679. }
  27680. }
  27681. function _onRemoveAttribute(doc, el, newAttr, remove) {
  27682. doc && doc._inc++;
  27683. var ns = newAttr.namespaceURI;
  27684. if (ns === NAMESPACE$2.XMLNS) {
  27685. //update namespace
  27686. delete el._nsMap[newAttr.prefix ? newAttr.localName : ''];
  27687. }
  27688. }
  27689. /**
  27690. * Updates `el.childNodes`, updating the indexed items and it's `length`.
  27691. * Passing `newChild` means it will be appended.
  27692. * Otherwise it's assumed that an item has been removed,
  27693. * and `el.firstNode` and it's `.nextSibling` are used
  27694. * to walk the current list of child nodes.
  27695. *
  27696. * @param {Document} doc
  27697. * @param {Node} el
  27698. * @param {Node} [newChild]
  27699. * @private
  27700. */
  27701. function _onUpdateChild(doc, el, newChild) {
  27702. if (doc && doc._inc) {
  27703. doc._inc++; //update childNodes
  27704. var cs = el.childNodes;
  27705. if (newChild) {
  27706. cs[cs.length++] = newChild;
  27707. } else {
  27708. var child = el.firstChild;
  27709. var i = 0;
  27710. while (child) {
  27711. cs[i++] = child;
  27712. child = child.nextSibling;
  27713. }
  27714. cs.length = i;
  27715. delete cs[cs.length];
  27716. }
  27717. }
  27718. }
  27719. /**
  27720. * Removes the connections between `parentNode` and `child`
  27721. * and any existing `child.previousSibling` or `child.nextSibling`.
  27722. *
  27723. * @see https://github.com/xmldom/xmldom/issues/135
  27724. * @see https://github.com/xmldom/xmldom/issues/145
  27725. *
  27726. * @param {Node} parentNode
  27727. * @param {Node} child
  27728. * @returns {Node} the child that was removed.
  27729. * @private
  27730. */
  27731. function _removeChild(parentNode, child) {
  27732. var previous = child.previousSibling;
  27733. var next = child.nextSibling;
  27734. if (previous) {
  27735. previous.nextSibling = next;
  27736. } else {
  27737. parentNode.firstChild = next;
  27738. }
  27739. if (next) {
  27740. next.previousSibling = previous;
  27741. } else {
  27742. parentNode.lastChild = previous;
  27743. }
  27744. child.parentNode = null;
  27745. child.previousSibling = null;
  27746. child.nextSibling = null;
  27747. _onUpdateChild(parentNode.ownerDocument, parentNode);
  27748. return child;
  27749. }
  27750. /**
  27751. * Returns `true` if `node` can be a parent for insertion.
  27752. * @param {Node} node
  27753. * @returns {boolean}
  27754. */
  27755. function hasValidParentNodeType(node) {
  27756. return node && (node.nodeType === Node.DOCUMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || node.nodeType === Node.ELEMENT_NODE);
  27757. }
  27758. /**
  27759. * Returns `true` if `node` can be inserted according to it's `nodeType`.
  27760. * @param {Node} node
  27761. * @returns {boolean}
  27762. */
  27763. function hasInsertableNodeType(node) {
  27764. 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);
  27765. }
  27766. /**
  27767. * Returns true if `node` is a DOCTYPE node
  27768. * @param {Node} node
  27769. * @returns {boolean}
  27770. */
  27771. function isDocTypeNode(node) {
  27772. return node && node.nodeType === Node.DOCUMENT_TYPE_NODE;
  27773. }
  27774. /**
  27775. * Returns true if the node is an element
  27776. * @param {Node} node
  27777. * @returns {boolean}
  27778. */
  27779. function isElementNode(node) {
  27780. return node && node.nodeType === Node.ELEMENT_NODE;
  27781. }
  27782. /**
  27783. * Returns true if `node` is a text node
  27784. * @param {Node} node
  27785. * @returns {boolean}
  27786. */
  27787. function isTextNode(node) {
  27788. return node && node.nodeType === Node.TEXT_NODE;
  27789. }
  27790. /**
  27791. * Check if en element node can be inserted before `child`, or at the end if child is falsy,
  27792. * according to the presence and position of a doctype node on the same level.
  27793. *
  27794. * @param {Document} doc The document node
  27795. * @param {Node} child the node that would become the nextSibling if the element would be inserted
  27796. * @returns {boolean} `true` if an element can be inserted before child
  27797. * @private
  27798. * https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  27799. */
  27800. function isElementInsertionPossible(doc, child) {
  27801. var parentChildNodes = doc.childNodes || [];
  27802. if (find(parentChildNodes, isElementNode) || isDocTypeNode(child)) {
  27803. return false;
  27804. }
  27805. var docTypeNode = find(parentChildNodes, isDocTypeNode);
  27806. return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child));
  27807. }
  27808. /**
  27809. * Check if en element node can be inserted before `child`, or at the end if child is falsy,
  27810. * according to the presence and position of a doctype node on the same level.
  27811. *
  27812. * @param {Node} doc The document node
  27813. * @param {Node} child the node that would become the nextSibling if the element would be inserted
  27814. * @returns {boolean} `true` if an element can be inserted before child
  27815. * @private
  27816. * https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  27817. */
  27818. function isElementReplacementPossible(doc, child) {
  27819. var parentChildNodes = doc.childNodes || [];
  27820. function hasElementChildThatIsNotChild(node) {
  27821. return isElementNode(node) && node !== child;
  27822. }
  27823. if (find(parentChildNodes, hasElementChildThatIsNotChild)) {
  27824. return false;
  27825. }
  27826. var docTypeNode = find(parentChildNodes, isDocTypeNode);
  27827. return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child));
  27828. }
  27829. /**
  27830. * @private
  27831. * Steps 1-5 of the checks before inserting and before replacing a child are the same.
  27832. *
  27833. * @param {Node} parent the parent node to insert `node` into
  27834. * @param {Node} node the node to insert
  27835. * @param {Node=} child the node that should become the `nextSibling` of `node`
  27836. * @returns {Node}
  27837. * @throws DOMException for several node combinations that would create a DOM that is not well-formed.
  27838. * @throws DOMException if `child` is provided but is not a child of `parent`.
  27839. * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  27840. * @see https://dom.spec.whatwg.org/#concept-node-replace
  27841. */
  27842. function assertPreInsertionValidity1to5(parent, node, child) {
  27843. // 1. If `parent` is not a Document, DocumentFragment, or Element node, then throw a "HierarchyRequestError" DOMException.
  27844. if (!hasValidParentNodeType(parent)) {
  27845. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Unexpected parent node type ' + parent.nodeType);
  27846. } // 2. If `node` is a host-including inclusive ancestor of `parent`, then throw a "HierarchyRequestError" DOMException.
  27847. // not implemented!
  27848. // 3. If `child` is non-null and its parent is not `parent`, then throw a "NotFoundError" DOMException.
  27849. if (child && child.parentNode !== parent) {
  27850. throw new DOMException(NOT_FOUND_ERR, 'child not in parent');
  27851. }
  27852. if ( // 4. If `node` is not a DocumentFragment, DocumentType, Element, or CharacterData node, then throw a "HierarchyRequestError" DOMException.
  27853. !hasInsertableNodeType(node) || // 5. If either `node` is a Text node and `parent` is a document,
  27854. // the sax parser currently adds top level text nodes, this will be fixed in 0.9.0
  27855. // || (node.nodeType === Node.TEXT_NODE && parent.nodeType === Node.DOCUMENT_NODE)
  27856. // or `node` is a doctype and `parent` is not a document, then throw a "HierarchyRequestError" DOMException.
  27857. isDocTypeNode(node) && parent.nodeType !== Node.DOCUMENT_NODE) {
  27858. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Unexpected node type ' + node.nodeType + ' for parent node type ' + parent.nodeType);
  27859. }
  27860. }
  27861. /**
  27862. * @private
  27863. * Step 6 of the checks before inserting and before replacing a child are different.
  27864. *
  27865. * @param {Document} parent the parent node to insert `node` into
  27866. * @param {Node} node the node to insert
  27867. * @param {Node | undefined} child the node that should become the `nextSibling` of `node`
  27868. * @returns {Node}
  27869. * @throws DOMException for several node combinations that would create a DOM that is not well-formed.
  27870. * @throws DOMException if `child` is provided but is not a child of `parent`.
  27871. * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  27872. * @see https://dom.spec.whatwg.org/#concept-node-replace
  27873. */
  27874. function assertPreInsertionValidityInDocument(parent, node, child) {
  27875. var parentChildNodes = parent.childNodes || [];
  27876. var nodeChildNodes = node.childNodes || []; // DocumentFragment
  27877. if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
  27878. var nodeChildElements = nodeChildNodes.filter(isElementNode); // If node has more than one element child or has a Text node child.
  27879. if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) {
  27880. throw new DOMException(HIERARCHY_REQUEST_ERR, 'More than one element or text in fragment');
  27881. } // Otherwise, if `node` has one element child and either `parent` has an element child,
  27882. // `child` is a doctype, or `child` is non-null and a doctype is following `child`.
  27883. if (nodeChildElements.length === 1 && !isElementInsertionPossible(parent, child)) {
  27884. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Element in fragment can not be inserted before doctype');
  27885. }
  27886. } // Element
  27887. if (isElementNode(node)) {
  27888. // `parent` has an element child, `child` is a doctype,
  27889. // or `child` is non-null and a doctype is following `child`.
  27890. if (!isElementInsertionPossible(parent, child)) {
  27891. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one element can be added and only after doctype');
  27892. }
  27893. } // DocumentType
  27894. if (isDocTypeNode(node)) {
  27895. // `parent` has a doctype child,
  27896. if (find(parentChildNodes, isDocTypeNode)) {
  27897. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one doctype is allowed');
  27898. }
  27899. var parentElementChild = find(parentChildNodes, isElementNode); // `child` is non-null and an element is preceding `child`,
  27900. if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) {
  27901. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can only be inserted before an element');
  27902. } // or `child` is null and `parent` has an element child.
  27903. if (!child && parentElementChild) {
  27904. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can not be appended since element is present');
  27905. }
  27906. }
  27907. }
  27908. /**
  27909. * @private
  27910. * Step 6 of the checks before inserting and before replacing a child are different.
  27911. *
  27912. * @param {Document} parent the parent node to insert `node` into
  27913. * @param {Node} node the node to insert
  27914. * @param {Node | undefined} child the node that should become the `nextSibling` of `node`
  27915. * @returns {Node}
  27916. * @throws DOMException for several node combinations that would create a DOM that is not well-formed.
  27917. * @throws DOMException if `child` is provided but is not a child of `parent`.
  27918. * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  27919. * @see https://dom.spec.whatwg.org/#concept-node-replace
  27920. */
  27921. function assertPreReplacementValidityInDocument(parent, node, child) {
  27922. var parentChildNodes = parent.childNodes || [];
  27923. var nodeChildNodes = node.childNodes || []; // DocumentFragment
  27924. if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
  27925. var nodeChildElements = nodeChildNodes.filter(isElementNode); // If `node` has more than one element child or has a Text node child.
  27926. if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) {
  27927. throw new DOMException(HIERARCHY_REQUEST_ERR, 'More than one element or text in fragment');
  27928. } // Otherwise, if `node` has one element child and either `parent` has an element child that is not `child` or a doctype is following `child`.
  27929. if (nodeChildElements.length === 1 && !isElementReplacementPossible(parent, child)) {
  27930. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Element in fragment can not be inserted before doctype');
  27931. }
  27932. } // Element
  27933. if (isElementNode(node)) {
  27934. // `parent` has an element child that is not `child` or a doctype is following `child`.
  27935. if (!isElementReplacementPossible(parent, child)) {
  27936. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one element can be added and only after doctype');
  27937. }
  27938. } // DocumentType
  27939. if (isDocTypeNode(node)) {
  27940. var hasDoctypeChildThatIsNotChild = function hasDoctypeChildThatIsNotChild(node) {
  27941. return isDocTypeNode(node) && node !== child;
  27942. }; // `parent` has a doctype child that is not `child`,
  27943. if (find(parentChildNodes, hasDoctypeChildThatIsNotChild)) {
  27944. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one doctype is allowed');
  27945. }
  27946. var parentElementChild = find(parentChildNodes, isElementNode); // or an element is preceding `child`.
  27947. if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) {
  27948. throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can only be inserted before an element');
  27949. }
  27950. }
  27951. }
  27952. /**
  27953. * @private
  27954. * @param {Node} parent the parent node to insert `node` into
  27955. * @param {Node} node the node to insert
  27956. * @param {Node=} child the node that should become the `nextSibling` of `node`
  27957. * @returns {Node}
  27958. * @throws DOMException for several node combinations that would create a DOM that is not well-formed.
  27959. * @throws DOMException if `child` is provided but is not a child of `parent`.
  27960. * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity
  27961. */
  27962. function _insertBefore(parent, node, child, _inDocumentAssertion) {
  27963. // To ensure pre-insertion validity of a node into a parent before a child, run these steps:
  27964. assertPreInsertionValidity1to5(parent, node, child); // If parent is a document, and any of the statements below, switched on the interface node implements,
  27965. // are true, then throw a "HierarchyRequestError" DOMException.
  27966. if (parent.nodeType === Node.DOCUMENT_NODE) {
  27967. (_inDocumentAssertion || assertPreInsertionValidityInDocument)(parent, node, child);
  27968. }
  27969. var cp = node.parentNode;
  27970. if (cp) {
  27971. cp.removeChild(node); //remove and update
  27972. }
  27973. if (node.nodeType === DOCUMENT_FRAGMENT_NODE) {
  27974. var newFirst = node.firstChild;
  27975. if (newFirst == null) {
  27976. return node;
  27977. }
  27978. var newLast = node.lastChild;
  27979. } else {
  27980. newFirst = newLast = node;
  27981. }
  27982. var pre = child ? child.previousSibling : parent.lastChild;
  27983. newFirst.previousSibling = pre;
  27984. newLast.nextSibling = child;
  27985. if (pre) {
  27986. pre.nextSibling = newFirst;
  27987. } else {
  27988. parent.firstChild = newFirst;
  27989. }
  27990. if (child == null) {
  27991. parent.lastChild = newLast;
  27992. } else {
  27993. child.previousSibling = newLast;
  27994. }
  27995. do {
  27996. newFirst.parentNode = parent;
  27997. } while (newFirst !== newLast && (newFirst = newFirst.nextSibling));
  27998. _onUpdateChild(parent.ownerDocument || parent, parent); //console.log(parent.lastChild.nextSibling == null)
  27999. if (node.nodeType == DOCUMENT_FRAGMENT_NODE) {
  28000. node.firstChild = node.lastChild = null;
  28001. }
  28002. return node;
  28003. }
  28004. /**
  28005. * Appends `newChild` to `parentNode`.
  28006. * If `newChild` is already connected to a `parentNode` it is first removed from it.
  28007. *
  28008. * @see https://github.com/xmldom/xmldom/issues/135
  28009. * @see https://github.com/xmldom/xmldom/issues/145
  28010. * @param {Node} parentNode
  28011. * @param {Node} newChild
  28012. * @returns {Node}
  28013. * @private
  28014. */
  28015. function _appendSingleChild(parentNode, newChild) {
  28016. if (newChild.parentNode) {
  28017. newChild.parentNode.removeChild(newChild);
  28018. }
  28019. newChild.parentNode = parentNode;
  28020. newChild.previousSibling = parentNode.lastChild;
  28021. newChild.nextSibling = null;
  28022. if (newChild.previousSibling) {
  28023. newChild.previousSibling.nextSibling = newChild;
  28024. } else {
  28025. parentNode.firstChild = newChild;
  28026. }
  28027. parentNode.lastChild = newChild;
  28028. _onUpdateChild(parentNode.ownerDocument, parentNode, newChild);
  28029. return newChild;
  28030. }
  28031. Document.prototype = {
  28032. //implementation : null,
  28033. nodeName: '#document',
  28034. nodeType: DOCUMENT_NODE,
  28035. /**
  28036. * The DocumentType node of the document.
  28037. *
  28038. * @readonly
  28039. * @type DocumentType
  28040. */
  28041. doctype: null,
  28042. documentElement: null,
  28043. _inc: 1,
  28044. insertBefore: function insertBefore(newChild, refChild) {
  28045. //raises
  28046. if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
  28047. var child = newChild.firstChild;
  28048. while (child) {
  28049. var next = child.nextSibling;
  28050. this.insertBefore(child, refChild);
  28051. child = next;
  28052. }
  28053. return newChild;
  28054. }
  28055. _insertBefore(this, newChild, refChild);
  28056. newChild.ownerDocument = this;
  28057. if (this.documentElement === null && newChild.nodeType === ELEMENT_NODE) {
  28058. this.documentElement = newChild;
  28059. }
  28060. return newChild;
  28061. },
  28062. removeChild: function removeChild(oldChild) {
  28063. if (this.documentElement == oldChild) {
  28064. this.documentElement = null;
  28065. }
  28066. return _removeChild(this, oldChild);
  28067. },
  28068. replaceChild: function replaceChild(newChild, oldChild) {
  28069. //raises
  28070. _insertBefore(this, newChild, oldChild, assertPreReplacementValidityInDocument);
  28071. newChild.ownerDocument = this;
  28072. if (oldChild) {
  28073. this.removeChild(oldChild);
  28074. }
  28075. if (isElementNode(newChild)) {
  28076. this.documentElement = newChild;
  28077. }
  28078. },
  28079. // Introduced in DOM Level 2:
  28080. importNode: function importNode(importedNode, deep) {
  28081. return _importNode(this, importedNode, deep);
  28082. },
  28083. // Introduced in DOM Level 2:
  28084. getElementById: function getElementById(id) {
  28085. var rtv = null;
  28086. _visitNode(this.documentElement, function (node) {
  28087. if (node.nodeType == ELEMENT_NODE) {
  28088. if (node.getAttribute('id') == id) {
  28089. rtv = node;
  28090. return true;
  28091. }
  28092. }
  28093. });
  28094. return rtv;
  28095. },
  28096. /**
  28097. * The `getElementsByClassName` method of `Document` interface returns an array-like object
  28098. * of all child elements which have **all** of the given class name(s).
  28099. *
  28100. * Returns an empty list if `classeNames` is an empty string or only contains HTML white space characters.
  28101. *
  28102. *
  28103. * Warning: This is a live LiveNodeList.
  28104. * Changes in the DOM will reflect in the array as the changes occur.
  28105. * If an element selected by this array no longer qualifies for the selector,
  28106. * it will automatically be removed. Be aware of this for iteration purposes.
  28107. *
  28108. * @param {string} classNames is a string representing the class name(s) to match; multiple class names are separated by (ASCII-)whitespace
  28109. *
  28110. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
  28111. * @see https://dom.spec.whatwg.org/#concept-getelementsbyclassname
  28112. */
  28113. getElementsByClassName: function getElementsByClassName(classNames) {
  28114. var classNamesSet = toOrderedSet(classNames);
  28115. return new LiveNodeList(this, function (base) {
  28116. var ls = [];
  28117. if (classNamesSet.length > 0) {
  28118. _visitNode(base.documentElement, function (node) {
  28119. if (node !== base && node.nodeType === ELEMENT_NODE) {
  28120. var nodeClassNames = node.getAttribute('class'); // can be null if the attribute does not exist
  28121. if (nodeClassNames) {
  28122. // before splitting and iterating just compare them for the most common case
  28123. var matches = classNames === nodeClassNames;
  28124. if (!matches) {
  28125. var nodeClassNamesSet = toOrderedSet(nodeClassNames);
  28126. matches = classNamesSet.every(arrayIncludes(nodeClassNamesSet));
  28127. }
  28128. if (matches) {
  28129. ls.push(node);
  28130. }
  28131. }
  28132. }
  28133. });
  28134. }
  28135. return ls;
  28136. });
  28137. },
  28138. //document factory method:
  28139. createElement: function createElement(tagName) {
  28140. var node = new Element();
  28141. node.ownerDocument = this;
  28142. node.nodeName = tagName;
  28143. node.tagName = tagName;
  28144. node.localName = tagName;
  28145. node.childNodes = new NodeList();
  28146. var attrs = node.attributes = new NamedNodeMap();
  28147. attrs._ownerElement = node;
  28148. return node;
  28149. },
  28150. createDocumentFragment: function createDocumentFragment() {
  28151. var node = new DocumentFragment();
  28152. node.ownerDocument = this;
  28153. node.childNodes = new NodeList();
  28154. return node;
  28155. },
  28156. createTextNode: function createTextNode(data) {
  28157. var node = new Text();
  28158. node.ownerDocument = this;
  28159. node.appendData(data);
  28160. return node;
  28161. },
  28162. createComment: function createComment(data) {
  28163. var node = new Comment();
  28164. node.ownerDocument = this;
  28165. node.appendData(data);
  28166. return node;
  28167. },
  28168. createCDATASection: function createCDATASection(data) {
  28169. var node = new CDATASection();
  28170. node.ownerDocument = this;
  28171. node.appendData(data);
  28172. return node;
  28173. },
  28174. createProcessingInstruction: function createProcessingInstruction(target, data) {
  28175. var node = new ProcessingInstruction();
  28176. node.ownerDocument = this;
  28177. node.tagName = node.target = target;
  28178. node.nodeValue = node.data = data;
  28179. return node;
  28180. },
  28181. createAttribute: function createAttribute(name) {
  28182. var node = new Attr();
  28183. node.ownerDocument = this;
  28184. node.name = name;
  28185. node.nodeName = name;
  28186. node.localName = name;
  28187. node.specified = true;
  28188. return node;
  28189. },
  28190. createEntityReference: function createEntityReference(name) {
  28191. var node = new EntityReference();
  28192. node.ownerDocument = this;
  28193. node.nodeName = name;
  28194. return node;
  28195. },
  28196. // Introduced in DOM Level 2:
  28197. createElementNS: function createElementNS(namespaceURI, qualifiedName) {
  28198. var node = new Element();
  28199. var pl = qualifiedName.split(':');
  28200. var attrs = node.attributes = new NamedNodeMap();
  28201. node.childNodes = new NodeList();
  28202. node.ownerDocument = this;
  28203. node.nodeName = qualifiedName;
  28204. node.tagName = qualifiedName;
  28205. node.namespaceURI = namespaceURI;
  28206. if (pl.length == 2) {
  28207. node.prefix = pl[0];
  28208. node.localName = pl[1];
  28209. } else {
  28210. //el.prefix = null;
  28211. node.localName = qualifiedName;
  28212. }
  28213. attrs._ownerElement = node;
  28214. return node;
  28215. },
  28216. // Introduced in DOM Level 2:
  28217. createAttributeNS: function createAttributeNS(namespaceURI, qualifiedName) {
  28218. var node = new Attr();
  28219. var pl = qualifiedName.split(':');
  28220. node.ownerDocument = this;
  28221. node.nodeName = qualifiedName;
  28222. node.name = qualifiedName;
  28223. node.namespaceURI = namespaceURI;
  28224. node.specified = true;
  28225. if (pl.length == 2) {
  28226. node.prefix = pl[0];
  28227. node.localName = pl[1];
  28228. } else {
  28229. //el.prefix = null;
  28230. node.localName = qualifiedName;
  28231. }
  28232. return node;
  28233. }
  28234. };
  28235. _extends(Document, Node);
  28236. function Element() {
  28237. this._nsMap = {};
  28238. }
  28239. Element.prototype = {
  28240. nodeType: ELEMENT_NODE,
  28241. hasAttribute: function hasAttribute(name) {
  28242. return this.getAttributeNode(name) != null;
  28243. },
  28244. getAttribute: function getAttribute(name) {
  28245. var attr = this.getAttributeNode(name);
  28246. return attr && attr.value || '';
  28247. },
  28248. getAttributeNode: function getAttributeNode(name) {
  28249. return this.attributes.getNamedItem(name);
  28250. },
  28251. setAttribute: function setAttribute(name, value) {
  28252. var attr = this.ownerDocument.createAttribute(name);
  28253. attr.value = attr.nodeValue = "" + value;
  28254. this.setAttributeNode(attr);
  28255. },
  28256. removeAttribute: function removeAttribute(name) {
  28257. var attr = this.getAttributeNode(name);
  28258. attr && this.removeAttributeNode(attr);
  28259. },
  28260. //four real opeartion method
  28261. appendChild: function appendChild(newChild) {
  28262. if (newChild.nodeType === DOCUMENT_FRAGMENT_NODE) {
  28263. return this.insertBefore(newChild, null);
  28264. } else {
  28265. return _appendSingleChild(this, newChild);
  28266. }
  28267. },
  28268. setAttributeNode: function setAttributeNode(newAttr) {
  28269. return this.attributes.setNamedItem(newAttr);
  28270. },
  28271. setAttributeNodeNS: function setAttributeNodeNS(newAttr) {
  28272. return this.attributes.setNamedItemNS(newAttr);
  28273. },
  28274. removeAttributeNode: function removeAttributeNode(oldAttr) {
  28275. //console.log(this == oldAttr.ownerElement)
  28276. return this.attributes.removeNamedItem(oldAttr.nodeName);
  28277. },
  28278. //get real attribute name,and remove it by removeAttributeNode
  28279. removeAttributeNS: function removeAttributeNS(namespaceURI, localName) {
  28280. var old = this.getAttributeNodeNS(namespaceURI, localName);
  28281. old && this.removeAttributeNode(old);
  28282. },
  28283. hasAttributeNS: function hasAttributeNS(namespaceURI, localName) {
  28284. return this.getAttributeNodeNS(namespaceURI, localName) != null;
  28285. },
  28286. getAttributeNS: function getAttributeNS(namespaceURI, localName) {
  28287. var attr = this.getAttributeNodeNS(namespaceURI, localName);
  28288. return attr && attr.value || '';
  28289. },
  28290. setAttributeNS: function setAttributeNS(namespaceURI, qualifiedName, value) {
  28291. var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
  28292. attr.value = attr.nodeValue = "" + value;
  28293. this.setAttributeNode(attr);
  28294. },
  28295. getAttributeNodeNS: function getAttributeNodeNS(namespaceURI, localName) {
  28296. return this.attributes.getNamedItemNS(namespaceURI, localName);
  28297. },
  28298. getElementsByTagName: function getElementsByTagName(tagName) {
  28299. return new LiveNodeList(this, function (base) {
  28300. var ls = [];
  28301. _visitNode(base, function (node) {
  28302. if (node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)) {
  28303. ls.push(node);
  28304. }
  28305. });
  28306. return ls;
  28307. });
  28308. },
  28309. getElementsByTagNameNS: function getElementsByTagNameNS(namespaceURI, localName) {
  28310. return new LiveNodeList(this, function (base) {
  28311. var ls = [];
  28312. _visitNode(base, function (node) {
  28313. if (node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)) {
  28314. ls.push(node);
  28315. }
  28316. });
  28317. return ls;
  28318. });
  28319. }
  28320. };
  28321. Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
  28322. Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
  28323. _extends(Element, Node);
  28324. function Attr() {}
  28325. Attr.prototype.nodeType = ATTRIBUTE_NODE;
  28326. _extends(Attr, Node);
  28327. function CharacterData() {}
  28328. CharacterData.prototype = {
  28329. data: '',
  28330. substringData: function substringData(offset, count) {
  28331. return this.data.substring(offset, offset + count);
  28332. },
  28333. appendData: function appendData(text) {
  28334. text = this.data + text;
  28335. this.nodeValue = this.data = text;
  28336. this.length = text.length;
  28337. },
  28338. insertData: function insertData(offset, text) {
  28339. this.replaceData(offset, 0, text);
  28340. },
  28341. appendChild: function appendChild(newChild) {
  28342. throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR]);
  28343. },
  28344. deleteData: function deleteData(offset, count) {
  28345. this.replaceData(offset, count, "");
  28346. },
  28347. replaceData: function replaceData(offset, count, text) {
  28348. var start = this.data.substring(0, offset);
  28349. var end = this.data.substring(offset + count);
  28350. text = start + text + end;
  28351. this.nodeValue = this.data = text;
  28352. this.length = text.length;
  28353. }
  28354. };
  28355. _extends(CharacterData, Node);
  28356. function Text() {}
  28357. Text.prototype = {
  28358. nodeName: "#text",
  28359. nodeType: TEXT_NODE,
  28360. splitText: function splitText(offset) {
  28361. var text = this.data;
  28362. var newText = text.substring(offset);
  28363. text = text.substring(0, offset);
  28364. this.data = this.nodeValue = text;
  28365. this.length = text.length;
  28366. var newNode = this.ownerDocument.createTextNode(newText);
  28367. if (this.parentNode) {
  28368. this.parentNode.insertBefore(newNode, this.nextSibling);
  28369. }
  28370. return newNode;
  28371. }
  28372. };
  28373. _extends(Text, CharacterData);
  28374. function Comment() {}
  28375. Comment.prototype = {
  28376. nodeName: "#comment",
  28377. nodeType: COMMENT_NODE
  28378. };
  28379. _extends(Comment, CharacterData);
  28380. function CDATASection() {}
  28381. CDATASection.prototype = {
  28382. nodeName: "#cdata-section",
  28383. nodeType: CDATA_SECTION_NODE
  28384. };
  28385. _extends(CDATASection, CharacterData);
  28386. function DocumentType() {}
  28387. DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
  28388. _extends(DocumentType, Node);
  28389. function Notation() {}
  28390. Notation.prototype.nodeType = NOTATION_NODE;
  28391. _extends(Notation, Node);
  28392. function Entity() {}
  28393. Entity.prototype.nodeType = ENTITY_NODE;
  28394. _extends(Entity, Node);
  28395. function EntityReference() {}
  28396. EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
  28397. _extends(EntityReference, Node);
  28398. function DocumentFragment() {}
  28399. DocumentFragment.prototype.nodeName = "#document-fragment";
  28400. DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
  28401. _extends(DocumentFragment, Node);
  28402. function ProcessingInstruction() {}
  28403. ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
  28404. _extends(ProcessingInstruction, Node);
  28405. function XMLSerializer() {}
  28406. XMLSerializer.prototype.serializeToString = function (node, isHtml, nodeFilter) {
  28407. return nodeSerializeToString.call(node, isHtml, nodeFilter);
  28408. };
  28409. Node.prototype.toString = nodeSerializeToString;
  28410. function nodeSerializeToString(isHtml, nodeFilter) {
  28411. var buf = [];
  28412. var refNode = this.nodeType == 9 && this.documentElement || this;
  28413. var prefix = refNode.prefix;
  28414. var uri = refNode.namespaceURI;
  28415. if (uri && prefix == null) {
  28416. //console.log(prefix)
  28417. var prefix = refNode.lookupPrefix(uri);
  28418. if (prefix == null) {
  28419. //isHTML = true;
  28420. var visibleNamespaces = [{
  28421. namespace: uri,
  28422. prefix: null
  28423. } //{namespace:uri,prefix:''}
  28424. ];
  28425. }
  28426. }
  28427. serializeToString(this, buf, isHtml, nodeFilter, visibleNamespaces); //console.log('###',this.nodeType,uri,prefix,buf.join(''))
  28428. return buf.join('');
  28429. }
  28430. function needNamespaceDefine(node, isHTML, visibleNamespaces) {
  28431. var prefix = node.prefix || '';
  28432. var uri = node.namespaceURI; // According to [Namespaces in XML 1.0](https://www.w3.org/TR/REC-xml-names/#ns-using) ,
  28433. // and more specifically https://www.w3.org/TR/REC-xml-names/#nsc-NoPrefixUndecl :
  28434. // > In a namespace declaration for a prefix [...], the attribute value MUST NOT be empty.
  28435. // in a similar manner [Namespaces in XML 1.1](https://www.w3.org/TR/xml-names11/#ns-using)
  28436. // and more specifically https://www.w3.org/TR/xml-names11/#nsc-NSDeclared :
  28437. // > [...] Furthermore, the attribute value [...] must not be an empty string.
  28438. // so serializing empty namespace value like xmlns:ds="" would produce an invalid XML document.
  28439. if (!uri) {
  28440. return false;
  28441. }
  28442. if (prefix === "xml" && uri === NAMESPACE$2.XML || uri === NAMESPACE$2.XMLNS) {
  28443. return false;
  28444. }
  28445. var i = visibleNamespaces.length;
  28446. while (i--) {
  28447. var ns = visibleNamespaces[i]; // get namespace prefix
  28448. if (ns.prefix === prefix) {
  28449. return ns.namespace !== uri;
  28450. }
  28451. }
  28452. return true;
  28453. }
  28454. /**
  28455. * Well-formed constraint: No < in Attribute Values
  28456. * > The replacement text of any entity referred to directly or indirectly
  28457. * > in an attribute value must not contain a <.
  28458. * @see https://www.w3.org/TR/xml11/#CleanAttrVals
  28459. * @see https://www.w3.org/TR/xml11/#NT-AttValue
  28460. *
  28461. * Literal whitespace other than space that appear in attribute values
  28462. * are serialized as their entity references, so they will be preserved.
  28463. * (In contrast to whitespace literals in the input which are normalized to spaces)
  28464. * @see https://www.w3.org/TR/xml11/#AVNormalize
  28465. * @see https://w3c.github.io/DOM-Parsing/#serializing-an-element-s-attributes
  28466. */
  28467. function addSerializedAttribute(buf, qualifiedName, value) {
  28468. buf.push(' ', qualifiedName, '="', value.replace(/[<>&"\t\n\r]/g, _xmlEncoder), '"');
  28469. }
  28470. function serializeToString(node, buf, isHTML, nodeFilter, visibleNamespaces) {
  28471. if (!visibleNamespaces) {
  28472. visibleNamespaces = [];
  28473. }
  28474. if (nodeFilter) {
  28475. node = nodeFilter(node);
  28476. if (node) {
  28477. if (typeof node == 'string') {
  28478. buf.push(node);
  28479. return;
  28480. }
  28481. } else {
  28482. return;
  28483. } //buf.sort.apply(attrs, attributeSorter);
  28484. }
  28485. switch (node.nodeType) {
  28486. case ELEMENT_NODE:
  28487. var attrs = node.attributes;
  28488. var len = attrs.length;
  28489. var child = node.firstChild;
  28490. var nodeName = node.tagName;
  28491. isHTML = NAMESPACE$2.isHTML(node.namespaceURI) || isHTML;
  28492. var prefixedNodeName = nodeName;
  28493. if (!isHTML && !node.prefix && node.namespaceURI) {
  28494. var defaultNS; // lookup current default ns from `xmlns` attribute
  28495. for (var ai = 0; ai < attrs.length; ai++) {
  28496. if (attrs.item(ai).name === 'xmlns') {
  28497. defaultNS = attrs.item(ai).value;
  28498. break;
  28499. }
  28500. }
  28501. if (!defaultNS) {
  28502. // lookup current default ns in visibleNamespaces
  28503. for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) {
  28504. var namespace = visibleNamespaces[nsi];
  28505. if (namespace.prefix === '' && namespace.namespace === node.namespaceURI) {
  28506. defaultNS = namespace.namespace;
  28507. break;
  28508. }
  28509. }
  28510. }
  28511. if (defaultNS !== node.namespaceURI) {
  28512. for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) {
  28513. var namespace = visibleNamespaces[nsi];
  28514. if (namespace.namespace === node.namespaceURI) {
  28515. if (namespace.prefix) {
  28516. prefixedNodeName = namespace.prefix + ':' + nodeName;
  28517. }
  28518. break;
  28519. }
  28520. }
  28521. }
  28522. }
  28523. buf.push('<', prefixedNodeName);
  28524. for (var i = 0; i < len; i++) {
  28525. // add namespaces for attributes
  28526. var attr = attrs.item(i);
  28527. if (attr.prefix == 'xmlns') {
  28528. visibleNamespaces.push({
  28529. prefix: attr.localName,
  28530. namespace: attr.value
  28531. });
  28532. } else if (attr.nodeName == 'xmlns') {
  28533. visibleNamespaces.push({
  28534. prefix: '',
  28535. namespace: attr.value
  28536. });
  28537. }
  28538. }
  28539. for (var i = 0; i < len; i++) {
  28540. var attr = attrs.item(i);
  28541. if (needNamespaceDefine(attr, isHTML, visibleNamespaces)) {
  28542. var prefix = attr.prefix || '';
  28543. var uri = attr.namespaceURI;
  28544. addSerializedAttribute(buf, prefix ? 'xmlns:' + prefix : "xmlns", uri);
  28545. visibleNamespaces.push({
  28546. prefix: prefix,
  28547. namespace: uri
  28548. });
  28549. }
  28550. serializeToString(attr, buf, isHTML, nodeFilter, visibleNamespaces);
  28551. } // add namespace for current node
  28552. if (nodeName === prefixedNodeName && needNamespaceDefine(node, isHTML, visibleNamespaces)) {
  28553. var prefix = node.prefix || '';
  28554. var uri = node.namespaceURI;
  28555. addSerializedAttribute(buf, prefix ? 'xmlns:' + prefix : "xmlns", uri);
  28556. visibleNamespaces.push({
  28557. prefix: prefix,
  28558. namespace: uri
  28559. });
  28560. }
  28561. if (child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)) {
  28562. buf.push('>'); //if is cdata child node
  28563. if (isHTML && /^script$/i.test(nodeName)) {
  28564. while (child) {
  28565. if (child.data) {
  28566. buf.push(child.data);
  28567. } else {
  28568. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
  28569. }
  28570. child = child.nextSibling;
  28571. }
  28572. } else {
  28573. while (child) {
  28574. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
  28575. child = child.nextSibling;
  28576. }
  28577. }
  28578. buf.push('</', prefixedNodeName, '>');
  28579. } else {
  28580. buf.push('/>');
  28581. } // remove added visible namespaces
  28582. //visibleNamespaces.length = startVisibleNamespaces;
  28583. return;
  28584. case DOCUMENT_NODE:
  28585. case DOCUMENT_FRAGMENT_NODE:
  28586. var child = node.firstChild;
  28587. while (child) {
  28588. serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
  28589. child = child.nextSibling;
  28590. }
  28591. return;
  28592. case ATTRIBUTE_NODE:
  28593. return addSerializedAttribute(buf, node.name, node.value);
  28594. case TEXT_NODE:
  28595. /**
  28596. * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form,
  28597. * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section.
  28598. * If they are needed elsewhere, they must be escaped using either numeric character references or the strings
  28599. * `&amp;` and `&lt;` respectively.
  28600. * The right angle bracket (>) may be represented using the string " &gt; ", and must, for compatibility,
  28601. * be escaped using either `&gt;` or a character reference when it appears in the string `]]>` in content,
  28602. * when that string is not marking the end of a CDATA section.
  28603. *
  28604. * In the content of elements, character data is any string of characters
  28605. * which does not contain the start-delimiter of any markup
  28606. * and does not include the CDATA-section-close delimiter, `]]>`.
  28607. *
  28608. * @see https://www.w3.org/TR/xml/#NT-CharData
  28609. * @see https://w3c.github.io/DOM-Parsing/#xml-serializing-a-text-node
  28610. */
  28611. return buf.push(node.data.replace(/[<&>]/g, _xmlEncoder));
  28612. case CDATA_SECTION_NODE:
  28613. return buf.push('<![CDATA[', node.data, ']]>');
  28614. case COMMENT_NODE:
  28615. return buf.push("<!--", node.data, "-->");
  28616. case DOCUMENT_TYPE_NODE:
  28617. var pubid = node.publicId;
  28618. var sysid = node.systemId;
  28619. buf.push('<!DOCTYPE ', node.name);
  28620. if (pubid) {
  28621. buf.push(' PUBLIC ', pubid);
  28622. if (sysid && sysid != '.') {
  28623. buf.push(' ', sysid);
  28624. }
  28625. buf.push('>');
  28626. } else if (sysid && sysid != '.') {
  28627. buf.push(' SYSTEM ', sysid, '>');
  28628. } else {
  28629. var sub = node.internalSubset;
  28630. if (sub) {
  28631. buf.push(" [", sub, "]");
  28632. }
  28633. buf.push(">");
  28634. }
  28635. return;
  28636. case PROCESSING_INSTRUCTION_NODE:
  28637. return buf.push("<?", node.target, " ", node.data, "?>");
  28638. case ENTITY_REFERENCE_NODE:
  28639. return buf.push('&', node.nodeName, ';');
  28640. //case ENTITY_NODE:
  28641. //case NOTATION_NODE:
  28642. default:
  28643. buf.push('??', node.nodeName);
  28644. }
  28645. }
  28646. function _importNode(doc, node, deep) {
  28647. var node2;
  28648. switch (node.nodeType) {
  28649. case ELEMENT_NODE:
  28650. node2 = node.cloneNode(false);
  28651. node2.ownerDocument = doc;
  28652. //var attrs = node2.attributes;
  28653. //var len = attrs.length;
  28654. //for(var i=0;i<len;i++){
  28655. //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
  28656. //}
  28657. case DOCUMENT_FRAGMENT_NODE:
  28658. break;
  28659. case ATTRIBUTE_NODE:
  28660. deep = true;
  28661. break;
  28662. //case ENTITY_REFERENCE_NODE:
  28663. //case PROCESSING_INSTRUCTION_NODE:
  28664. ////case TEXT_NODE:
  28665. //case CDATA_SECTION_NODE:
  28666. //case COMMENT_NODE:
  28667. // deep = false;
  28668. // break;
  28669. //case DOCUMENT_NODE:
  28670. //case DOCUMENT_TYPE_NODE:
  28671. //cannot be imported.
  28672. //case ENTITY_NODE:
  28673. //case NOTATION_NODE:
  28674. //can not hit in level3
  28675. //default:throw e;
  28676. }
  28677. if (!node2) {
  28678. node2 = node.cloneNode(false); //false
  28679. }
  28680. node2.ownerDocument = doc;
  28681. node2.parentNode = null;
  28682. if (deep) {
  28683. var child = node.firstChild;
  28684. while (child) {
  28685. node2.appendChild(_importNode(doc, child, deep));
  28686. child = child.nextSibling;
  28687. }
  28688. }
  28689. return node2;
  28690. } //
  28691. //var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
  28692. // attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};
  28693. function _cloneNode(doc, node, deep) {
  28694. var node2 = new node.constructor();
  28695. for (var n in node) {
  28696. if (Object.prototype.hasOwnProperty.call(node, n)) {
  28697. var v = node[n];
  28698. if (typeof v != "object") {
  28699. if (v != node2[n]) {
  28700. node2[n] = v;
  28701. }
  28702. }
  28703. }
  28704. }
  28705. if (node.childNodes) {
  28706. node2.childNodes = new NodeList();
  28707. }
  28708. node2.ownerDocument = doc;
  28709. switch (node2.nodeType) {
  28710. case ELEMENT_NODE:
  28711. var attrs = node.attributes;
  28712. var attrs2 = node2.attributes = new NamedNodeMap();
  28713. var len = attrs.length;
  28714. attrs2._ownerElement = node2;
  28715. for (var i = 0; i < len; i++) {
  28716. node2.setAttributeNode(_cloneNode(doc, attrs.item(i), true));
  28717. }
  28718. break;
  28719. case ATTRIBUTE_NODE:
  28720. deep = true;
  28721. }
  28722. if (deep) {
  28723. var child = node.firstChild;
  28724. while (child) {
  28725. node2.appendChild(_cloneNode(doc, child, deep));
  28726. child = child.nextSibling;
  28727. }
  28728. }
  28729. return node2;
  28730. }
  28731. function __set__(object, key, value) {
  28732. object[key] = value;
  28733. } //do dynamic
  28734. try {
  28735. if (Object.defineProperty) {
  28736. var getTextContent = function getTextContent(node) {
  28737. switch (node.nodeType) {
  28738. case ELEMENT_NODE:
  28739. case DOCUMENT_FRAGMENT_NODE:
  28740. var buf = [];
  28741. node = node.firstChild;
  28742. while (node) {
  28743. if (node.nodeType !== 7 && node.nodeType !== 8) {
  28744. buf.push(getTextContent(node));
  28745. }
  28746. node = node.nextSibling;
  28747. }
  28748. return buf.join('');
  28749. default:
  28750. return node.nodeValue;
  28751. }
  28752. };
  28753. Object.defineProperty(LiveNodeList.prototype, 'length', {
  28754. get: function get() {
  28755. _updateLiveList(this);
  28756. return this.$$length;
  28757. }
  28758. });
  28759. Object.defineProperty(Node.prototype, 'textContent', {
  28760. get: function get() {
  28761. return getTextContent(this);
  28762. },
  28763. set: function set(data) {
  28764. switch (this.nodeType) {
  28765. case ELEMENT_NODE:
  28766. case DOCUMENT_FRAGMENT_NODE:
  28767. while (this.firstChild) {
  28768. this.removeChild(this.firstChild);
  28769. }
  28770. if (data || String(data)) {
  28771. this.appendChild(this.ownerDocument.createTextNode(data));
  28772. }
  28773. break;
  28774. default:
  28775. this.data = data;
  28776. this.value = data;
  28777. this.nodeValue = data;
  28778. }
  28779. }
  28780. });
  28781. __set__ = function __set__(object, key, value) {
  28782. //console.log(value)
  28783. object['$$' + key] = value;
  28784. };
  28785. }
  28786. } catch (e) {//ie8
  28787. } //if(typeof require == 'function'){
  28788. var DocumentType_1 = DocumentType;
  28789. var DOMException_1 = DOMException;
  28790. var DOMImplementation_1 = DOMImplementation$1;
  28791. var Element_1 = Element;
  28792. var Node_1 = Node;
  28793. var NodeList_1 = NodeList;
  28794. var XMLSerializer_1 = XMLSerializer; //}
  28795. var dom = {
  28796. DocumentType: DocumentType_1,
  28797. DOMException: DOMException_1,
  28798. DOMImplementation: DOMImplementation_1,
  28799. Element: Element_1,
  28800. Node: Node_1,
  28801. NodeList: NodeList_1,
  28802. XMLSerializer: XMLSerializer_1
  28803. };
  28804. var entities = createCommonjsModule(function (module, exports) {
  28805. var freeze = conventions.freeze;
  28806. /**
  28807. * The entities that are predefined in every XML document.
  28808. *
  28809. * @see https://www.w3.org/TR/2006/REC-xml11-20060816/#sec-predefined-ent W3C XML 1.1
  28810. * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-predefined-ent W3C XML 1.0
  28811. * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Predefined_entities_in_XML Wikipedia
  28812. */
  28813. exports.XML_ENTITIES = freeze({
  28814. amp: '&',
  28815. apos: "'",
  28816. gt: '>',
  28817. lt: '<',
  28818. quot: '"'
  28819. });
  28820. /**
  28821. * A map of currently 241 entities that are detected in an HTML document.
  28822. * They contain all entries from `XML_ENTITIES`.
  28823. *
  28824. * @see XML_ENTITIES
  28825. * @see DOMParser.parseFromString
  28826. * @see DOMImplementation.prototype.createHTMLDocument
  28827. * @see https://html.spec.whatwg.org/#named-character-references WHATWG HTML(5) Spec
  28828. * @see https://www.w3.org/TR/xml-entity-names/ W3C XML Entity Names
  28829. * @see https://www.w3.org/TR/html4/sgml/entities.html W3C HTML4/SGML
  28830. * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Character_entity_references_in_HTML Wikipedia (HTML)
  28831. * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Entities_representing_special_characters_in_XHTML Wikpedia (XHTML)
  28832. */
  28833. exports.HTML_ENTITIES = freeze({
  28834. lt: '<',
  28835. gt: '>',
  28836. amp: '&',
  28837. quot: '"',
  28838. apos: "'",
  28839. Agrave: "À",
  28840. Aacute: "Á",
  28841. Acirc: "Â",
  28842. Atilde: "Ã",
  28843. Auml: "Ä",
  28844. Aring: "Å",
  28845. AElig: "Æ",
  28846. Ccedil: "Ç",
  28847. Egrave: "È",
  28848. Eacute: "É",
  28849. Ecirc: "Ê",
  28850. Euml: "Ë",
  28851. Igrave: "Ì",
  28852. Iacute: "Í",
  28853. Icirc: "Î",
  28854. Iuml: "Ï",
  28855. ETH: "Ð",
  28856. Ntilde: "Ñ",
  28857. Ograve: "Ò",
  28858. Oacute: "Ó",
  28859. Ocirc: "Ô",
  28860. Otilde: "Õ",
  28861. Ouml: "Ö",
  28862. Oslash: "Ø",
  28863. Ugrave: "Ù",
  28864. Uacute: "Ú",
  28865. Ucirc: "Û",
  28866. Uuml: "Ü",
  28867. Yacute: "Ý",
  28868. THORN: "Þ",
  28869. szlig: "ß",
  28870. agrave: "à",
  28871. aacute: "á",
  28872. acirc: "â",
  28873. atilde: "ã",
  28874. auml: "ä",
  28875. aring: "å",
  28876. aelig: "æ",
  28877. ccedil: "ç",
  28878. egrave: "è",
  28879. eacute: "é",
  28880. ecirc: "ê",
  28881. euml: "ë",
  28882. igrave: "ì",
  28883. iacute: "í",
  28884. icirc: "î",
  28885. iuml: "ï",
  28886. eth: "ð",
  28887. ntilde: "ñ",
  28888. ograve: "ò",
  28889. oacute: "ó",
  28890. ocirc: "ô",
  28891. otilde: "õ",
  28892. ouml: "ö",
  28893. oslash: "ø",
  28894. ugrave: "ù",
  28895. uacute: "ú",
  28896. ucirc: "û",
  28897. uuml: "ü",
  28898. yacute: "ý",
  28899. thorn: "þ",
  28900. yuml: "ÿ",
  28901. nbsp: "\xA0",
  28902. iexcl: "¡",
  28903. cent: "¢",
  28904. pound: "£",
  28905. curren: "¤",
  28906. yen: "¥",
  28907. brvbar: "¦",
  28908. sect: "§",
  28909. uml: "¨",
  28910. copy: "©",
  28911. ordf: "ª",
  28912. laquo: "«",
  28913. not: "¬",
  28914. shy: "­­",
  28915. reg: "®",
  28916. macr: "¯",
  28917. deg: "°",
  28918. plusmn: "±",
  28919. sup2: "²",
  28920. sup3: "³",
  28921. acute: "´",
  28922. micro: "µ",
  28923. para: "¶",
  28924. middot: "·",
  28925. cedil: "¸",
  28926. sup1: "¹",
  28927. ordm: "º",
  28928. raquo: "»",
  28929. frac14: "¼",
  28930. frac12: "½",
  28931. frac34: "¾",
  28932. iquest: "¿",
  28933. times: "×",
  28934. divide: "÷",
  28935. forall: "∀",
  28936. part: "∂",
  28937. exist: "∃",
  28938. empty: "∅",
  28939. nabla: "∇",
  28940. isin: "∈",
  28941. notin: "∉",
  28942. ni: "∋",
  28943. prod: "∏",
  28944. sum: "∑",
  28945. minus: "−",
  28946. lowast: "∗",
  28947. radic: "√",
  28948. prop: "∝",
  28949. infin: "∞",
  28950. ang: "∠",
  28951. and: "∧",
  28952. or: "∨",
  28953. cap: "∩",
  28954. cup: "∪",
  28955. 'int': "∫",
  28956. there4: "∴",
  28957. sim: "∼",
  28958. cong: "≅",
  28959. asymp: "≈",
  28960. ne: "≠",
  28961. equiv: "≡",
  28962. le: "≤",
  28963. ge: "≥",
  28964. sub: "⊂",
  28965. sup: "⊃",
  28966. nsub: "⊄",
  28967. sube: "⊆",
  28968. supe: "⊇",
  28969. oplus: "⊕",
  28970. otimes: "⊗",
  28971. perp: "⊥",
  28972. sdot: "⋅",
  28973. Alpha: "Α",
  28974. Beta: "Β",
  28975. Gamma: "Γ",
  28976. Delta: "Δ",
  28977. Epsilon: "Ε",
  28978. Zeta: "Ζ",
  28979. Eta: "Η",
  28980. Theta: "Θ",
  28981. Iota: "Ι",
  28982. Kappa: "Κ",
  28983. Lambda: "Λ",
  28984. Mu: "Μ",
  28985. Nu: "Ν",
  28986. Xi: "Ξ",
  28987. Omicron: "Ο",
  28988. Pi: "Π",
  28989. Rho: "Ρ",
  28990. Sigma: "Σ",
  28991. Tau: "Τ",
  28992. Upsilon: "Υ",
  28993. Phi: "Φ",
  28994. Chi: "Χ",
  28995. Psi: "Ψ",
  28996. Omega: "Ω",
  28997. alpha: "α",
  28998. beta: "β",
  28999. gamma: "γ",
  29000. delta: "δ",
  29001. epsilon: "ε",
  29002. zeta: "ζ",
  29003. eta: "η",
  29004. theta: "θ",
  29005. iota: "ι",
  29006. kappa: "κ",
  29007. lambda: "λ",
  29008. mu: "μ",
  29009. nu: "ν",
  29010. xi: "ξ",
  29011. omicron: "ο",
  29012. pi: "π",
  29013. rho: "ρ",
  29014. sigmaf: "ς",
  29015. sigma: "σ",
  29016. tau: "τ",
  29017. upsilon: "υ",
  29018. phi: "φ",
  29019. chi: "χ",
  29020. psi: "ψ",
  29021. omega: "ω",
  29022. thetasym: "ϑ",
  29023. upsih: "ϒ",
  29024. piv: "ϖ",
  29025. OElig: "Œ",
  29026. oelig: "œ",
  29027. Scaron: "Š",
  29028. scaron: "š",
  29029. Yuml: "Ÿ",
  29030. fnof: "ƒ",
  29031. circ: "ˆ",
  29032. tilde: "˜",
  29033. ensp: " ",
  29034. emsp: " ",
  29035. thinsp: " ",
  29036. zwnj: "‌",
  29037. zwj: "‍",
  29038. lrm: "‎",
  29039. rlm: "‏",
  29040. ndash: "–",
  29041. mdash: "—",
  29042. lsquo: "‘",
  29043. rsquo: "’",
  29044. sbquo: "‚",
  29045. ldquo: "“",
  29046. rdquo: "”",
  29047. bdquo: "„",
  29048. dagger: "†",
  29049. Dagger: "‡",
  29050. bull: "•",
  29051. hellip: "…",
  29052. permil: "‰",
  29053. prime: "′",
  29054. Prime: "″",
  29055. lsaquo: "‹",
  29056. rsaquo: "›",
  29057. oline: "‾",
  29058. euro: "€",
  29059. trade: "™",
  29060. larr: "←",
  29061. uarr: "↑",
  29062. rarr: "→",
  29063. darr: "↓",
  29064. harr: "↔",
  29065. crarr: "↵",
  29066. lceil: "⌈",
  29067. rceil: "⌉",
  29068. lfloor: "⌊",
  29069. rfloor: "⌋",
  29070. loz: "◊",
  29071. spades: "♠",
  29072. clubs: "♣",
  29073. hearts: "♥",
  29074. diams: "♦"
  29075. });
  29076. /**
  29077. * @deprecated use `HTML_ENTITIES` instead
  29078. * @see HTML_ENTITIES
  29079. */
  29080. exports.entityMap = exports.HTML_ENTITIES;
  29081. });
  29082. entities.XML_ENTITIES;
  29083. entities.HTML_ENTITIES;
  29084. entities.entityMap;
  29085. 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]
  29086. //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
  29087. //[5] Name ::= NameStartChar (NameChar)*
  29088. 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
  29089. var nameChar = new RegExp("[\\-\\.0-9" + nameStartChar.source.slice(1, -1) + "\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
  29090. var tagNamePattern = new RegExp('^' + nameStartChar.source + nameChar.source + '*(?:\:' + nameStartChar.source + nameChar.source + '*)?$'); //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
  29091. //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(',')
  29092. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  29093. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  29094. var S_TAG = 0; //tag name offerring
  29095. var S_ATTR = 1; //attr name offerring
  29096. var S_ATTR_SPACE = 2; //attr name end and space offer
  29097. var S_EQ = 3; //=space?
  29098. var S_ATTR_NOQUOT_VALUE = 4; //attr value(no quot value only)
  29099. var S_ATTR_END = 5; //attr value end and no space(quot end)
  29100. var S_TAG_SPACE = 6; //(attr value end || tag end ) && (space offer)
  29101. var S_TAG_CLOSE = 7; //closed el<el />
  29102. /**
  29103. * Creates an error that will not be caught by XMLReader aka the SAX parser.
  29104. *
  29105. * @param {string} message
  29106. * @param {any?} locator Optional, can provide details about the location in the source
  29107. * @constructor
  29108. */
  29109. function ParseError$1(message, locator) {
  29110. this.message = message;
  29111. this.locator = locator;
  29112. if (Error.captureStackTrace) Error.captureStackTrace(this, ParseError$1);
  29113. }
  29114. ParseError$1.prototype = new Error();
  29115. ParseError$1.prototype.name = ParseError$1.name;
  29116. function XMLReader$1() {}
  29117. XMLReader$1.prototype = {
  29118. parse: function parse(source, defaultNSMap, entityMap) {
  29119. var domBuilder = this.domBuilder;
  29120. domBuilder.startDocument();
  29121. _copy(defaultNSMap, defaultNSMap = {});
  29122. _parse(source, defaultNSMap, entityMap, domBuilder, this.errorHandler);
  29123. domBuilder.endDocument();
  29124. }
  29125. };
  29126. function _parse(source, defaultNSMapCopy, entityMap, domBuilder, errorHandler) {
  29127. function fixedFromCharCode(code) {
  29128. // String.prototype.fromCharCode does not supports
  29129. // > 2 bytes unicode chars directly
  29130. if (code > 0xffff) {
  29131. code -= 0x10000;
  29132. var surrogate1 = 0xd800 + (code >> 10),
  29133. surrogate2 = 0xdc00 + (code & 0x3ff);
  29134. return String.fromCharCode(surrogate1, surrogate2);
  29135. } else {
  29136. return String.fromCharCode(code);
  29137. }
  29138. }
  29139. function entityReplacer(a) {
  29140. var k = a.slice(1, -1);
  29141. if (Object.hasOwnProperty.call(entityMap, k)) {
  29142. return entityMap[k];
  29143. } else if (k.charAt(0) === '#') {
  29144. return fixedFromCharCode(parseInt(k.substr(1).replace('x', '0x')));
  29145. } else {
  29146. errorHandler.error('entity not found:' + a);
  29147. return a;
  29148. }
  29149. }
  29150. function appendText(end) {
  29151. //has some bugs
  29152. if (end > start) {
  29153. var xt = source.substring(start, end).replace(/&#?\w+;/g, entityReplacer);
  29154. locator && position(start);
  29155. domBuilder.characters(xt, 0, end - start);
  29156. start = end;
  29157. }
  29158. }
  29159. function position(p, m) {
  29160. while (p >= lineEnd && (m = linePattern.exec(source))) {
  29161. lineStart = m.index;
  29162. lineEnd = lineStart + m[0].length;
  29163. locator.lineNumber++; //console.log('line++:',locator,startPos,endPos)
  29164. }
  29165. locator.columnNumber = p - lineStart + 1;
  29166. }
  29167. var lineStart = 0;
  29168. var lineEnd = 0;
  29169. var linePattern = /.*(?:\r\n?|\n)|.*$/g;
  29170. var locator = domBuilder.locator;
  29171. var parseStack = [{
  29172. currentNSMap: defaultNSMapCopy
  29173. }];
  29174. var closeMap = {};
  29175. var start = 0;
  29176. while (true) {
  29177. try {
  29178. var tagStart = source.indexOf('<', start);
  29179. if (tagStart < 0) {
  29180. if (!source.substr(start).match(/^\s*$/)) {
  29181. var doc = domBuilder.doc;
  29182. var text = doc.createTextNode(source.substr(start));
  29183. doc.appendChild(text);
  29184. domBuilder.currentElement = text;
  29185. }
  29186. return;
  29187. }
  29188. if (tagStart > start) {
  29189. appendText(tagStart);
  29190. }
  29191. switch (source.charAt(tagStart + 1)) {
  29192. case '/':
  29193. var end = source.indexOf('>', tagStart + 3);
  29194. var tagName = source.substring(tagStart + 2, end).replace(/[ \t\n\r]+$/g, '');
  29195. var config = parseStack.pop();
  29196. if (end < 0) {
  29197. tagName = source.substring(tagStart + 2).replace(/[\s<].*/, '');
  29198. errorHandler.error("end tag name: " + tagName + ' is not complete:' + config.tagName);
  29199. end = tagStart + 1 + tagName.length;
  29200. } else if (tagName.match(/\s</)) {
  29201. tagName = tagName.replace(/[\s<].*/, '');
  29202. errorHandler.error("end tag name: " + tagName + ' maybe not complete');
  29203. end = tagStart + 1 + tagName.length;
  29204. }
  29205. var localNSMap = config.localNSMap;
  29206. var endMatch = config.tagName == tagName;
  29207. var endIgnoreCaseMach = endMatch || config.tagName && config.tagName.toLowerCase() == tagName.toLowerCase();
  29208. if (endIgnoreCaseMach) {
  29209. domBuilder.endElement(config.uri, config.localName, tagName);
  29210. if (localNSMap) {
  29211. for (var prefix in localNSMap) {
  29212. if (Object.prototype.hasOwnProperty.call(localNSMap, prefix)) {
  29213. domBuilder.endPrefixMapping(prefix);
  29214. }
  29215. }
  29216. }
  29217. if (!endMatch) {
  29218. errorHandler.fatalError("end tag name: " + tagName + ' is not match the current start tagName:' + config.tagName); // No known test case
  29219. }
  29220. } else {
  29221. parseStack.push(config);
  29222. }
  29223. end++;
  29224. break;
  29225. // end elment
  29226. case '?':
  29227. // <?...?>
  29228. locator && position(tagStart);
  29229. end = parseInstruction(source, tagStart, domBuilder);
  29230. break;
  29231. case '!':
  29232. // <!doctype,<![CDATA,<!--
  29233. locator && position(tagStart);
  29234. end = parseDCC(source, tagStart, domBuilder, errorHandler);
  29235. break;
  29236. default:
  29237. locator && position(tagStart);
  29238. var el = new ElementAttributes();
  29239. var currentNSMap = parseStack[parseStack.length - 1].currentNSMap; //elStartEnd
  29240. var end = parseElementStartPart(source, tagStart, el, currentNSMap, entityReplacer, errorHandler);
  29241. var len = el.length;
  29242. if (!el.closed && fixSelfClosed(source, end, el.tagName, closeMap)) {
  29243. el.closed = true;
  29244. if (!entityMap.nbsp) {
  29245. errorHandler.warning('unclosed xml attribute');
  29246. }
  29247. }
  29248. if (locator && len) {
  29249. var locator2 = copyLocator(locator, {}); //try{//attribute position fixed
  29250. for (var i = 0; i < len; i++) {
  29251. var a = el[i];
  29252. position(a.offset);
  29253. a.locator = copyLocator(locator, {});
  29254. }
  29255. domBuilder.locator = locator2;
  29256. if (appendElement$1(el, domBuilder, currentNSMap)) {
  29257. parseStack.push(el);
  29258. }
  29259. domBuilder.locator = locator;
  29260. } else {
  29261. if (appendElement$1(el, domBuilder, currentNSMap)) {
  29262. parseStack.push(el);
  29263. }
  29264. }
  29265. if (NAMESPACE$1.isHTML(el.uri) && !el.closed) {
  29266. end = parseHtmlSpecialContent(source, end, el.tagName, entityReplacer, domBuilder);
  29267. } else {
  29268. end++;
  29269. }
  29270. }
  29271. } catch (e) {
  29272. if (e instanceof ParseError$1) {
  29273. throw e;
  29274. }
  29275. errorHandler.error('element parse error: ' + e);
  29276. end = -1;
  29277. }
  29278. if (end > start) {
  29279. start = end;
  29280. } else {
  29281. //TODO: 这里有可能sax回退,有位置错误风险
  29282. appendText(Math.max(tagStart, start) + 1);
  29283. }
  29284. }
  29285. }
  29286. function copyLocator(f, t) {
  29287. t.lineNumber = f.lineNumber;
  29288. t.columnNumber = f.columnNumber;
  29289. return t;
  29290. }
  29291. /**
  29292. * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
  29293. * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
  29294. */
  29295. function parseElementStartPart(source, start, el, currentNSMap, entityReplacer, errorHandler) {
  29296. /**
  29297. * @param {string} qname
  29298. * @param {string} value
  29299. * @param {number} startIndex
  29300. */
  29301. function addAttribute(qname, value, startIndex) {
  29302. if (el.attributeNames.hasOwnProperty(qname)) {
  29303. errorHandler.fatalError('Attribute ' + qname + ' redefined');
  29304. }
  29305. el.addValue(qname, // @see https://www.w3.org/TR/xml/#AVNormalize
  29306. // since the xmldom sax parser does not "interpret" DTD the following is not implemented:
  29307. // - recursive replacement of (DTD) entity references
  29308. // - trimming and collapsing multiple spaces into a single one for attributes that are not of type CDATA
  29309. value.replace(/[\t\n\r]/g, ' ').replace(/&#?\w+;/g, entityReplacer), startIndex);
  29310. }
  29311. var attrName;
  29312. var value;
  29313. var p = ++start;
  29314. var s = S_TAG; //status
  29315. while (true) {
  29316. var c = source.charAt(p);
  29317. switch (c) {
  29318. case '=':
  29319. if (s === S_ATTR) {
  29320. //attrName
  29321. attrName = source.slice(start, p);
  29322. s = S_EQ;
  29323. } else if (s === S_ATTR_SPACE) {
  29324. s = S_EQ;
  29325. } else {
  29326. //fatalError: equal must after attrName or space after attrName
  29327. throw new Error('attribute equal must after attrName'); // No known test case
  29328. }
  29329. break;
  29330. case '\'':
  29331. case '"':
  29332. if (s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
  29333. ) {
  29334. //equal
  29335. if (s === S_ATTR) {
  29336. errorHandler.warning('attribute value must after "="');
  29337. attrName = source.slice(start, p);
  29338. }
  29339. start = p + 1;
  29340. p = source.indexOf(c, start);
  29341. if (p > 0) {
  29342. value = source.slice(start, p);
  29343. addAttribute(attrName, value, start - 1);
  29344. s = S_ATTR_END;
  29345. } else {
  29346. //fatalError: no end quot match
  29347. throw new Error('attribute value no end \'' + c + '\' match');
  29348. }
  29349. } else if (s == S_ATTR_NOQUOT_VALUE) {
  29350. value = source.slice(start, p);
  29351. addAttribute(attrName, value, start);
  29352. errorHandler.warning('attribute "' + attrName + '" missed start quot(' + c + ')!!');
  29353. start = p + 1;
  29354. s = S_ATTR_END;
  29355. } else {
  29356. //fatalError: no equal before
  29357. throw new Error('attribute value must after "="'); // No known test case
  29358. }
  29359. break;
  29360. case '/':
  29361. switch (s) {
  29362. case S_TAG:
  29363. el.setTagName(source.slice(start, p));
  29364. case S_ATTR_END:
  29365. case S_TAG_SPACE:
  29366. case S_TAG_CLOSE:
  29367. s = S_TAG_CLOSE;
  29368. el.closed = true;
  29369. case S_ATTR_NOQUOT_VALUE:
  29370. case S_ATTR:
  29371. case S_ATTR_SPACE:
  29372. break;
  29373. //case S_EQ:
  29374. default:
  29375. throw new Error("attribute invalid close char('/')");
  29376. // No known test case
  29377. }
  29378. break;
  29379. case '':
  29380. //end document
  29381. errorHandler.error('unexpected end of input');
  29382. if (s == S_TAG) {
  29383. el.setTagName(source.slice(start, p));
  29384. }
  29385. return p;
  29386. case '>':
  29387. switch (s) {
  29388. case S_TAG:
  29389. el.setTagName(source.slice(start, p));
  29390. case S_ATTR_END:
  29391. case S_TAG_SPACE:
  29392. case S_TAG_CLOSE:
  29393. break;
  29394. //normal
  29395. case S_ATTR_NOQUOT_VALUE: //Compatible state
  29396. case S_ATTR:
  29397. value = source.slice(start, p);
  29398. if (value.slice(-1) === '/') {
  29399. el.closed = true;
  29400. value = value.slice(0, -1);
  29401. }
  29402. case S_ATTR_SPACE:
  29403. if (s === S_ATTR_SPACE) {
  29404. value = attrName;
  29405. }
  29406. if (s == S_ATTR_NOQUOT_VALUE) {
  29407. errorHandler.warning('attribute "' + value + '" missed quot(")!');
  29408. addAttribute(attrName, value, start);
  29409. } else {
  29410. if (!NAMESPACE$1.isHTML(currentNSMap['']) || !value.match(/^(?:disabled|checked|selected)$/i)) {
  29411. errorHandler.warning('attribute "' + value + '" missed value!! "' + value + '" instead!!');
  29412. }
  29413. addAttribute(value, value, start);
  29414. }
  29415. break;
  29416. case S_EQ:
  29417. throw new Error('attribute value missed!!');
  29418. } // console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
  29419. return p;
  29420. /*xml space '\x20' | #x9 | #xD | #xA; */
  29421. case "\x80":
  29422. c = ' ';
  29423. default:
  29424. if (c <= ' ') {
  29425. //space
  29426. switch (s) {
  29427. case S_TAG:
  29428. el.setTagName(source.slice(start, p)); //tagName
  29429. s = S_TAG_SPACE;
  29430. break;
  29431. case S_ATTR:
  29432. attrName = source.slice(start, p);
  29433. s = S_ATTR_SPACE;
  29434. break;
  29435. case S_ATTR_NOQUOT_VALUE:
  29436. var value = source.slice(start, p);
  29437. errorHandler.warning('attribute "' + value + '" missed quot(")!!');
  29438. addAttribute(attrName, value, start);
  29439. case S_ATTR_END:
  29440. s = S_TAG_SPACE;
  29441. break;
  29442. //case S_TAG_SPACE:
  29443. //case S_EQ:
  29444. //case S_ATTR_SPACE:
  29445. // void();break;
  29446. //case S_TAG_CLOSE:
  29447. //ignore warning
  29448. }
  29449. } else {
  29450. //not space
  29451. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  29452. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  29453. switch (s) {
  29454. //case S_TAG:void();break;
  29455. //case S_ATTR:void();break;
  29456. //case S_ATTR_NOQUOT_VALUE:void();break;
  29457. case S_ATTR_SPACE:
  29458. el.tagName;
  29459. if (!NAMESPACE$1.isHTML(currentNSMap['']) || !attrName.match(/^(?:disabled|checked|selected)$/i)) {
  29460. errorHandler.warning('attribute "' + attrName + '" missed value!! "' + attrName + '" instead2!!');
  29461. }
  29462. addAttribute(attrName, attrName, start);
  29463. start = p;
  29464. s = S_ATTR;
  29465. break;
  29466. case S_ATTR_END:
  29467. errorHandler.warning('attribute space is required"' + attrName + '"!!');
  29468. case S_TAG_SPACE:
  29469. s = S_ATTR;
  29470. start = p;
  29471. break;
  29472. case S_EQ:
  29473. s = S_ATTR_NOQUOT_VALUE;
  29474. start = p;
  29475. break;
  29476. case S_TAG_CLOSE:
  29477. throw new Error("elements closed character '/' and '>' must be connected to");
  29478. }
  29479. }
  29480. } //end outer switch
  29481. //console.log('p++',p)
  29482. p++;
  29483. }
  29484. }
  29485. /**
  29486. * @return true if has new namespace define
  29487. */
  29488. function appendElement$1(el, domBuilder, currentNSMap) {
  29489. var tagName = el.tagName;
  29490. var localNSMap = null; //var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
  29491. var i = el.length;
  29492. while (i--) {
  29493. var a = el[i];
  29494. var qName = a.qName;
  29495. var value = a.value;
  29496. var nsp = qName.indexOf(':');
  29497. if (nsp > 0) {
  29498. var prefix = a.prefix = qName.slice(0, nsp);
  29499. var localName = qName.slice(nsp + 1);
  29500. var nsPrefix = prefix === 'xmlns' && localName;
  29501. } else {
  29502. localName = qName;
  29503. prefix = null;
  29504. nsPrefix = qName === 'xmlns' && '';
  29505. } //can not set prefix,because prefix !== ''
  29506. a.localName = localName; //prefix == null for no ns prefix attribute
  29507. if (nsPrefix !== false) {
  29508. //hack!!
  29509. if (localNSMap == null) {
  29510. localNSMap = {}; //console.log(currentNSMap,0)
  29511. _copy(currentNSMap, currentNSMap = {}); //console.log(currentNSMap,1)
  29512. }
  29513. currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
  29514. a.uri = NAMESPACE$1.XMLNS;
  29515. domBuilder.startPrefixMapping(nsPrefix, value);
  29516. }
  29517. }
  29518. var i = el.length;
  29519. while (i--) {
  29520. a = el[i];
  29521. var prefix = a.prefix;
  29522. if (prefix) {
  29523. //no prefix attribute has no namespace
  29524. if (prefix === 'xml') {
  29525. a.uri = NAMESPACE$1.XML;
  29526. }
  29527. if (prefix !== 'xmlns') {
  29528. a.uri = currentNSMap[prefix || '']; //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
  29529. }
  29530. }
  29531. }
  29532. var nsp = tagName.indexOf(':');
  29533. if (nsp > 0) {
  29534. prefix = el.prefix = tagName.slice(0, nsp);
  29535. localName = el.localName = tagName.slice(nsp + 1);
  29536. } else {
  29537. prefix = null; //important!!
  29538. localName = el.localName = tagName;
  29539. } //no prefix element has default namespace
  29540. var ns = el.uri = currentNSMap[prefix || ''];
  29541. domBuilder.startElement(ns, localName, tagName, el); //endPrefixMapping and startPrefixMapping have not any help for dom builder
  29542. //localNSMap = null
  29543. if (el.closed) {
  29544. domBuilder.endElement(ns, localName, tagName);
  29545. if (localNSMap) {
  29546. for (prefix in localNSMap) {
  29547. if (Object.prototype.hasOwnProperty.call(localNSMap, prefix)) {
  29548. domBuilder.endPrefixMapping(prefix);
  29549. }
  29550. }
  29551. }
  29552. } else {
  29553. el.currentNSMap = currentNSMap;
  29554. el.localNSMap = localNSMap; //parseStack.push(el);
  29555. return true;
  29556. }
  29557. }
  29558. function parseHtmlSpecialContent(source, elStartEnd, tagName, entityReplacer, domBuilder) {
  29559. if (/^(?:script|textarea)$/i.test(tagName)) {
  29560. var elEndStart = source.indexOf('</' + tagName + '>', elStartEnd);
  29561. var text = source.substring(elStartEnd + 1, elEndStart);
  29562. if (/[&<]/.test(text)) {
  29563. if (/^script$/i.test(tagName)) {
  29564. //if(!/\]\]>/.test(text)){
  29565. //lexHandler.startCDATA();
  29566. domBuilder.characters(text, 0, text.length); //lexHandler.endCDATA();
  29567. return elEndStart; //}
  29568. } //}else{//text area
  29569. text = text.replace(/&#?\w+;/g, entityReplacer);
  29570. domBuilder.characters(text, 0, text.length);
  29571. return elEndStart; //}
  29572. }
  29573. }
  29574. return elStartEnd + 1;
  29575. }
  29576. function fixSelfClosed(source, elStartEnd, tagName, closeMap) {
  29577. //if(tagName in closeMap){
  29578. var pos = closeMap[tagName];
  29579. if (pos == null) {
  29580. //console.log(tagName)
  29581. pos = source.lastIndexOf('</' + tagName + '>');
  29582. if (pos < elStartEnd) {
  29583. //忘记闭合
  29584. pos = source.lastIndexOf('</' + tagName);
  29585. }
  29586. closeMap[tagName] = pos;
  29587. }
  29588. return pos < elStartEnd; //}
  29589. }
  29590. function _copy(source, target) {
  29591. for (var n in source) {
  29592. if (Object.prototype.hasOwnProperty.call(source, n)) {
  29593. target[n] = source[n];
  29594. }
  29595. }
  29596. }
  29597. function parseDCC(source, start, domBuilder, errorHandler) {
  29598. //sure start with '<!'
  29599. var next = source.charAt(start + 2);
  29600. switch (next) {
  29601. case '-':
  29602. if (source.charAt(start + 3) === '-') {
  29603. var end = source.indexOf('-->', start + 4); //append comment source.substring(4,end)//<!--
  29604. if (end > start) {
  29605. domBuilder.comment(source, start + 4, end - start - 4);
  29606. return end + 3;
  29607. } else {
  29608. errorHandler.error("Unclosed comment");
  29609. return -1;
  29610. }
  29611. } else {
  29612. //error
  29613. return -1;
  29614. }
  29615. default:
  29616. if (source.substr(start + 3, 6) == 'CDATA[') {
  29617. var end = source.indexOf(']]>', start + 9);
  29618. domBuilder.startCDATA();
  29619. domBuilder.characters(source, start + 9, end - start - 9);
  29620. domBuilder.endCDATA();
  29621. return end + 3;
  29622. } //<!DOCTYPE
  29623. //startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
  29624. var matchs = split(source, start);
  29625. var len = matchs.length;
  29626. if (len > 1 && /!doctype/i.test(matchs[0][0])) {
  29627. var name = matchs[1][0];
  29628. var pubid = false;
  29629. var sysid = false;
  29630. if (len > 3) {
  29631. if (/^public$/i.test(matchs[2][0])) {
  29632. pubid = matchs[3][0];
  29633. sysid = len > 4 && matchs[4][0];
  29634. } else if (/^system$/i.test(matchs[2][0])) {
  29635. sysid = matchs[3][0];
  29636. }
  29637. }
  29638. var lastMatch = matchs[len - 1];
  29639. domBuilder.startDTD(name, pubid, sysid);
  29640. domBuilder.endDTD();
  29641. return lastMatch.index + lastMatch[0].length;
  29642. }
  29643. }
  29644. return -1;
  29645. }
  29646. function parseInstruction(source, start, domBuilder) {
  29647. var end = source.indexOf('?>', start);
  29648. if (end) {
  29649. var match = source.substring(start, end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
  29650. if (match) {
  29651. match[0].length;
  29652. domBuilder.processingInstruction(match[1], match[2]);
  29653. return end + 2;
  29654. } else {
  29655. //error
  29656. return -1;
  29657. }
  29658. }
  29659. return -1;
  29660. }
  29661. function ElementAttributes() {
  29662. this.attributeNames = {};
  29663. }
  29664. ElementAttributes.prototype = {
  29665. setTagName: function setTagName(tagName) {
  29666. if (!tagNamePattern.test(tagName)) {
  29667. throw new Error('invalid tagName:' + tagName);
  29668. }
  29669. this.tagName = tagName;
  29670. },
  29671. addValue: function addValue(qName, value, offset) {
  29672. if (!tagNamePattern.test(qName)) {
  29673. throw new Error('invalid attribute:' + qName);
  29674. }
  29675. this.attributeNames[qName] = this.length;
  29676. this[this.length++] = {
  29677. qName: qName,
  29678. value: value,
  29679. offset: offset
  29680. };
  29681. },
  29682. length: 0,
  29683. getLocalName: function getLocalName(i) {
  29684. return this[i].localName;
  29685. },
  29686. getLocator: function getLocator(i) {
  29687. return this[i].locator;
  29688. },
  29689. getQName: function getQName(i) {
  29690. return this[i].qName;
  29691. },
  29692. getURI: function getURI(i) {
  29693. return this[i].uri;
  29694. },
  29695. getValue: function getValue(i) {
  29696. return this[i].value;
  29697. } // ,getIndex:function(uri, localName)){
  29698. // if(localName){
  29699. //
  29700. // }else{
  29701. // var qName = uri
  29702. // }
  29703. // },
  29704. // getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
  29705. // getType:function(uri,localName){}
  29706. // getType:function(i){},
  29707. };
  29708. function split(source, start) {
  29709. var match;
  29710. var buf = [];
  29711. var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
  29712. reg.lastIndex = start;
  29713. reg.exec(source); //skip <
  29714. while (match = reg.exec(source)) {
  29715. buf.push(match);
  29716. if (match[1]) return buf;
  29717. }
  29718. }
  29719. var XMLReader_1 = XMLReader$1;
  29720. var ParseError_1 = ParseError$1;
  29721. var sax = {
  29722. XMLReader: XMLReader_1,
  29723. ParseError: ParseError_1
  29724. };
  29725. var DOMImplementation = dom.DOMImplementation;
  29726. var NAMESPACE = conventions.NAMESPACE;
  29727. var ParseError = sax.ParseError;
  29728. var XMLReader = sax.XMLReader;
  29729. /**
  29730. * Normalizes line ending according to https://www.w3.org/TR/xml11/#sec-line-ends:
  29731. *
  29732. * > XML parsed entities are often stored in computer files which,
  29733. * > for editing convenience, are organized into lines.
  29734. * > These lines are typically separated by some combination
  29735. * > of the characters CARRIAGE RETURN (#xD) and LINE FEED (#xA).
  29736. * >
  29737. * > To simplify the tasks of applications, the XML processor must behave
  29738. * > as if it normalized all line breaks in external parsed entities (including the document entity)
  29739. * > on input, before parsing, by translating all of the following to a single #xA character:
  29740. * >
  29741. * > 1. the two-character sequence #xD #xA
  29742. * > 2. the two-character sequence #xD #x85
  29743. * > 3. the single character #x85
  29744. * > 4. the single character #x2028
  29745. * > 5. any #xD character that is not immediately followed by #xA or #x85.
  29746. *
  29747. * @param {string} input
  29748. * @returns {string}
  29749. */
  29750. function normalizeLineEndings(input) {
  29751. return input.replace(/\r[\n\u0085]/g, '\n').replace(/[\r\u0085\u2028]/g, '\n');
  29752. }
  29753. /**
  29754. * @typedef Locator
  29755. * @property {number} [columnNumber]
  29756. * @property {number} [lineNumber]
  29757. */
  29758. /**
  29759. * @typedef DOMParserOptions
  29760. * @property {DOMHandler} [domBuilder]
  29761. * @property {Function} [errorHandler]
  29762. * @property {(string) => string} [normalizeLineEndings] used to replace line endings before parsing
  29763. * defaults to `normalizeLineEndings`
  29764. * @property {Locator} [locator]
  29765. * @property {Record<string, string>} [xmlns]
  29766. *
  29767. * @see normalizeLineEndings
  29768. */
  29769. /**
  29770. * The DOMParser interface provides the ability to parse XML or HTML source code
  29771. * from a string into a DOM `Document`.
  29772. *
  29773. * _xmldom is different from the spec in that it allows an `options` parameter,
  29774. * to override the default behavior._
  29775. *
  29776. * @param {DOMParserOptions} [options]
  29777. * @constructor
  29778. *
  29779. * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
  29780. * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-parsing-and-serialization
  29781. */
  29782. function DOMParser$1(options) {
  29783. this.options = options || {
  29784. locator: {}
  29785. };
  29786. }
  29787. DOMParser$1.prototype.parseFromString = function (source, mimeType) {
  29788. var options = this.options;
  29789. var sax = new XMLReader();
  29790. var domBuilder = options.domBuilder || new DOMHandler(); //contentHandler and LexicalHandler
  29791. var errorHandler = options.errorHandler;
  29792. var locator = options.locator;
  29793. var defaultNSMap = options.xmlns || {};
  29794. var isHTML = /\/x?html?$/.test(mimeType); //mimeType.toLowerCase().indexOf('html') > -1;
  29795. var entityMap = isHTML ? entities.HTML_ENTITIES : entities.XML_ENTITIES;
  29796. if (locator) {
  29797. domBuilder.setDocumentLocator(locator);
  29798. }
  29799. sax.errorHandler = buildErrorHandler(errorHandler, domBuilder, locator);
  29800. sax.domBuilder = options.domBuilder || domBuilder;
  29801. if (isHTML) {
  29802. defaultNSMap[''] = NAMESPACE.HTML;
  29803. }
  29804. defaultNSMap.xml = defaultNSMap.xml || NAMESPACE.XML;
  29805. var normalize = options.normalizeLineEndings || normalizeLineEndings;
  29806. if (source && typeof source === 'string') {
  29807. sax.parse(normalize(source), defaultNSMap, entityMap);
  29808. } else {
  29809. sax.errorHandler.error('invalid doc source');
  29810. }
  29811. return domBuilder.doc;
  29812. };
  29813. function buildErrorHandler(errorImpl, domBuilder, locator) {
  29814. if (!errorImpl) {
  29815. if (domBuilder instanceof DOMHandler) {
  29816. return domBuilder;
  29817. }
  29818. errorImpl = domBuilder;
  29819. }
  29820. var errorHandler = {};
  29821. var isCallback = errorImpl instanceof Function;
  29822. locator = locator || {};
  29823. function build(key) {
  29824. var fn = errorImpl[key];
  29825. if (!fn && isCallback) {
  29826. fn = errorImpl.length == 2 ? function (msg) {
  29827. errorImpl(key, msg);
  29828. } : errorImpl;
  29829. }
  29830. errorHandler[key] = fn && function (msg) {
  29831. fn('[xmldom ' + key + ']\t' + msg + _locator(locator));
  29832. } || function () {};
  29833. }
  29834. build('warning');
  29835. build('error');
  29836. build('fatalError');
  29837. return errorHandler;
  29838. } //console.log('#\n\n\n\n\n\n\n####')
  29839. /**
  29840. * +ContentHandler+ErrorHandler
  29841. * +LexicalHandler+EntityResolver2
  29842. * -DeclHandler-DTDHandler
  29843. *
  29844. * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
  29845. * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
  29846. * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
  29847. */
  29848. function DOMHandler() {
  29849. this.cdata = false;
  29850. }
  29851. function position(locator, node) {
  29852. node.lineNumber = locator.lineNumber;
  29853. node.columnNumber = locator.columnNumber;
  29854. }
  29855. /**
  29856. * @see org.xml.sax.ContentHandler#startDocument
  29857. * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
  29858. */
  29859. DOMHandler.prototype = {
  29860. startDocument: function startDocument() {
  29861. this.doc = new DOMImplementation().createDocument(null, null, null);
  29862. if (this.locator) {
  29863. this.doc.documentURI = this.locator.systemId;
  29864. }
  29865. },
  29866. startElement: function startElement(namespaceURI, localName, qName, attrs) {
  29867. var doc = this.doc;
  29868. var el = doc.createElementNS(namespaceURI, qName || localName);
  29869. var len = attrs.length;
  29870. appendElement(this, el);
  29871. this.currentElement = el;
  29872. this.locator && position(this.locator, el);
  29873. for (var i = 0; i < len; i++) {
  29874. var namespaceURI = attrs.getURI(i);
  29875. var value = attrs.getValue(i);
  29876. var qName = attrs.getQName(i);
  29877. var attr = doc.createAttributeNS(namespaceURI, qName);
  29878. this.locator && position(attrs.getLocator(i), attr);
  29879. attr.value = attr.nodeValue = value;
  29880. el.setAttributeNode(attr);
  29881. }
  29882. },
  29883. endElement: function endElement(namespaceURI, localName, qName) {
  29884. var current = this.currentElement;
  29885. current.tagName;
  29886. this.currentElement = current.parentNode;
  29887. },
  29888. startPrefixMapping: function startPrefixMapping(prefix, uri) {},
  29889. endPrefixMapping: function endPrefixMapping(prefix) {},
  29890. processingInstruction: function processingInstruction(target, data) {
  29891. var ins = this.doc.createProcessingInstruction(target, data);
  29892. this.locator && position(this.locator, ins);
  29893. appendElement(this, ins);
  29894. },
  29895. ignorableWhitespace: function ignorableWhitespace(ch, start, length) {},
  29896. characters: function characters(chars, start, length) {
  29897. chars = _toString.apply(this, arguments); //console.log(chars)
  29898. if (chars) {
  29899. if (this.cdata) {
  29900. var charNode = this.doc.createCDATASection(chars);
  29901. } else {
  29902. var charNode = this.doc.createTextNode(chars);
  29903. }
  29904. if (this.currentElement) {
  29905. this.currentElement.appendChild(charNode);
  29906. } else if (/^\s*$/.test(chars)) {
  29907. this.doc.appendChild(charNode); //process xml
  29908. }
  29909. this.locator && position(this.locator, charNode);
  29910. }
  29911. },
  29912. skippedEntity: function skippedEntity(name) {},
  29913. endDocument: function endDocument() {
  29914. this.doc.normalize();
  29915. },
  29916. setDocumentLocator: function setDocumentLocator(locator) {
  29917. if (this.locator = locator) {
  29918. // && !('lineNumber' in locator)){
  29919. locator.lineNumber = 0;
  29920. }
  29921. },
  29922. //LexicalHandler
  29923. comment: function comment(chars, start, length) {
  29924. chars = _toString.apply(this, arguments);
  29925. var comm = this.doc.createComment(chars);
  29926. this.locator && position(this.locator, comm);
  29927. appendElement(this, comm);
  29928. },
  29929. startCDATA: function startCDATA() {
  29930. //used in characters() methods
  29931. this.cdata = true;
  29932. },
  29933. endCDATA: function endCDATA() {
  29934. this.cdata = false;
  29935. },
  29936. startDTD: function startDTD(name, publicId, systemId) {
  29937. var impl = this.doc.implementation;
  29938. if (impl && impl.createDocumentType) {
  29939. var dt = impl.createDocumentType(name, publicId, systemId);
  29940. this.locator && position(this.locator, dt);
  29941. appendElement(this, dt);
  29942. this.doc.doctype = dt;
  29943. }
  29944. },
  29945. /**
  29946. * @see org.xml.sax.ErrorHandler
  29947. * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
  29948. */
  29949. warning: function warning(error) {
  29950. console.warn('[xmldom warning]\t' + error, _locator(this.locator));
  29951. },
  29952. error: function error(_error) {
  29953. console.error('[xmldom error]\t' + _error, _locator(this.locator));
  29954. },
  29955. fatalError: function fatalError(error) {
  29956. throw new ParseError(error, this.locator);
  29957. }
  29958. };
  29959. function _locator(l) {
  29960. if (l) {
  29961. return '\n@' + (l.systemId || '') + '#[line:' + l.lineNumber + ',col:' + l.columnNumber + ']';
  29962. }
  29963. }
  29964. function _toString(chars, start, length) {
  29965. if (typeof chars == 'string') {
  29966. return chars.substr(start, length);
  29967. } else {
  29968. //java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
  29969. if (chars.length >= start + length || start) {
  29970. return new java.lang.String(chars, start, length) + '';
  29971. }
  29972. return chars;
  29973. }
  29974. }
  29975. /*
  29976. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
  29977. * used method of org.xml.sax.ext.LexicalHandler:
  29978. * #comment(chars, start, length)
  29979. * #startCDATA()
  29980. * #endCDATA()
  29981. * #startDTD(name, publicId, systemId)
  29982. *
  29983. *
  29984. * IGNORED method of org.xml.sax.ext.LexicalHandler:
  29985. * #endDTD()
  29986. * #startEntity(name)
  29987. * #endEntity(name)
  29988. *
  29989. *
  29990. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
  29991. * IGNORED method of org.xml.sax.ext.DeclHandler
  29992. * #attributeDecl(eName, aName, type, mode, value)
  29993. * #elementDecl(name, model)
  29994. * #externalEntityDecl(name, publicId, systemId)
  29995. * #internalEntityDecl(name, value)
  29996. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
  29997. * IGNORED method of org.xml.sax.EntityResolver2
  29998. * #resolveEntity(String name,String publicId,String baseURI,String systemId)
  29999. * #resolveEntity(publicId, systemId)
  30000. * #getExternalSubset(name, baseURI)
  30001. * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
  30002. * IGNORED method of org.xml.sax.DTDHandler
  30003. * #notationDecl(name, publicId, systemId) {};
  30004. * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
  30005. */
  30006. "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g, function (key) {
  30007. DOMHandler.prototype[key] = function () {
  30008. return null;
  30009. };
  30010. });
  30011. /* 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 */
  30012. function appendElement(hander, node) {
  30013. if (!hander.currentElement) {
  30014. hander.doc.appendChild(node);
  30015. } else {
  30016. hander.currentElement.appendChild(node);
  30017. }
  30018. } //appendChild and setAttributeNS are preformance key
  30019. var __DOMHandler = DOMHandler;
  30020. var normalizeLineEndings_1 = normalizeLineEndings;
  30021. var DOMParser_1 = DOMParser$1;
  30022. var domParser = {
  30023. __DOMHandler: __DOMHandler,
  30024. normalizeLineEndings: normalizeLineEndings_1,
  30025. DOMParser: DOMParser_1
  30026. };
  30027. var DOMParser = domParser.DOMParser;
  30028. /*! @name mpd-parser @version 0.22.1 @license Apache-2.0 */
  30029. var isObject = function isObject(obj) {
  30030. return !!obj && typeof obj === 'object';
  30031. };
  30032. var merge = function merge() {
  30033. for (var _len = arguments.length, objects = new Array(_len), _key = 0; _key < _len; _key++) {
  30034. objects[_key] = arguments[_key];
  30035. }
  30036. return objects.reduce(function (result, source) {
  30037. if (typeof source !== 'object') {
  30038. return result;
  30039. }
  30040. Object.keys(source).forEach(function (key) {
  30041. if (Array.isArray(result[key]) && Array.isArray(source[key])) {
  30042. result[key] = result[key].concat(source[key]);
  30043. } else if (isObject(result[key]) && isObject(source[key])) {
  30044. result[key] = merge(result[key], source[key]);
  30045. } else {
  30046. result[key] = source[key];
  30047. }
  30048. });
  30049. return result;
  30050. }, {});
  30051. };
  30052. var values = function values(o) {
  30053. return Object.keys(o).map(function (k) {
  30054. return o[k];
  30055. });
  30056. };
  30057. var range = function range(start, end) {
  30058. var result = [];
  30059. for (var i = start; i < end; i++) {
  30060. result.push(i);
  30061. }
  30062. return result;
  30063. };
  30064. var flatten = function flatten(lists) {
  30065. return lists.reduce(function (x, y) {
  30066. return x.concat(y);
  30067. }, []);
  30068. };
  30069. var from = function from(list) {
  30070. if (!list.length) {
  30071. return [];
  30072. }
  30073. var result = [];
  30074. for (var i = 0; i < list.length; i++) {
  30075. result.push(list[i]);
  30076. }
  30077. return result;
  30078. };
  30079. var findIndexes = function findIndexes(l, key) {
  30080. return l.reduce(function (a, e, i) {
  30081. if (e[key]) {
  30082. a.push(i);
  30083. }
  30084. return a;
  30085. }, []);
  30086. };
  30087. /**
  30088. * Returns the first index that satisfies the matching function, or -1 if not found.
  30089. *
  30090. * Only necessary because of IE11 support.
  30091. *
  30092. * @param {Array} list - the list to search through
  30093. * @param {Function} matchingFunction - the matching function
  30094. *
  30095. * @return {number} the matching index or -1 if not found
  30096. */
  30097. var findIndex = function findIndex(list, matchingFunction) {
  30098. for (var i = 0; i < list.length; i++) {
  30099. if (matchingFunction(list[i])) {
  30100. return i;
  30101. }
  30102. }
  30103. return -1;
  30104. };
  30105. /**
  30106. * Returns a union of the included lists provided each element can be identified by a key.
  30107. *
  30108. * @param {Array} list - list of lists to get the union of
  30109. * @param {Function} keyFunction - the function to use as a key for each element
  30110. *
  30111. * @return {Array} the union of the arrays
  30112. */
  30113. var union = function union(lists, keyFunction) {
  30114. return values(lists.reduce(function (acc, list) {
  30115. list.forEach(function (el) {
  30116. acc[keyFunction(el)] = el;
  30117. });
  30118. return acc;
  30119. }, {}));
  30120. };
  30121. var errors = {
  30122. INVALID_NUMBER_OF_PERIOD: 'INVALID_NUMBER_OF_PERIOD',
  30123. DASH_EMPTY_MANIFEST: 'DASH_EMPTY_MANIFEST',
  30124. DASH_INVALID_XML: 'DASH_INVALID_XML',
  30125. NO_BASE_URL: 'NO_BASE_URL',
  30126. MISSING_SEGMENT_INFORMATION: 'MISSING_SEGMENT_INFORMATION',
  30127. SEGMENT_TIME_UNSPECIFIED: 'SEGMENT_TIME_UNSPECIFIED',
  30128. UNSUPPORTED_UTC_TIMING_SCHEME: 'UNSUPPORTED_UTC_TIMING_SCHEME'
  30129. };
  30130. /**
  30131. * @typedef {Object} SingleUri
  30132. * @property {string} uri - relative location of segment
  30133. * @property {string} resolvedUri - resolved location of segment
  30134. * @property {Object} byterange - Object containing information on how to make byte range
  30135. * requests following byte-range-spec per RFC2616.
  30136. * @property {String} byterange.length - length of range request
  30137. * @property {String} byterange.offset - byte offset of range request
  30138. *
  30139. * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.1
  30140. */
  30141. /**
  30142. * Converts a URLType node (5.3.9.2.3 Table 13) to a segment object
  30143. * that conforms to how m3u8-parser is structured
  30144. *
  30145. * @see https://github.com/videojs/m3u8-parser
  30146. *
  30147. * @param {string} baseUrl - baseUrl provided by <BaseUrl> nodes
  30148. * @param {string} source - source url for segment
  30149. * @param {string} range - optional range used for range calls,
  30150. * follows RFC 2616, Clause 14.35.1
  30151. * @return {SingleUri} full segment information transformed into a format similar
  30152. * to m3u8-parser
  30153. */
  30154. var urlTypeToSegment = function urlTypeToSegment(_ref) {
  30155. var _ref$baseUrl = _ref.baseUrl,
  30156. baseUrl = _ref$baseUrl === void 0 ? '' : _ref$baseUrl,
  30157. _ref$source = _ref.source,
  30158. source = _ref$source === void 0 ? '' : _ref$source,
  30159. _ref$range = _ref.range,
  30160. range = _ref$range === void 0 ? '' : _ref$range,
  30161. _ref$indexRange = _ref.indexRange,
  30162. indexRange = _ref$indexRange === void 0 ? '' : _ref$indexRange;
  30163. var segment = {
  30164. uri: source,
  30165. resolvedUri: resolveUrl$1(baseUrl || '', source)
  30166. };
  30167. if (range || indexRange) {
  30168. var rangeStr = range ? range : indexRange;
  30169. var ranges = rangeStr.split('-'); // default to parsing this as a BigInt if possible
  30170. var startRange = window.BigInt ? window.BigInt(ranges[0]) : parseInt(ranges[0], 10);
  30171. var endRange = window.BigInt ? window.BigInt(ranges[1]) : parseInt(ranges[1], 10); // convert back to a number if less than MAX_SAFE_INTEGER
  30172. if (startRange < Number.MAX_SAFE_INTEGER && typeof startRange === 'bigint') {
  30173. startRange = Number(startRange);
  30174. }
  30175. if (endRange < Number.MAX_SAFE_INTEGER && typeof endRange === 'bigint') {
  30176. endRange = Number(endRange);
  30177. }
  30178. var length;
  30179. if (typeof endRange === 'bigint' || typeof startRange === 'bigint') {
  30180. length = window.BigInt(endRange) - window.BigInt(startRange) + window.BigInt(1);
  30181. } else {
  30182. length = endRange - startRange + 1;
  30183. }
  30184. if (typeof length === 'bigint' && length < Number.MAX_SAFE_INTEGER) {
  30185. length = Number(length);
  30186. } // byterange should be inclusive according to
  30187. // RFC 2616, Clause 14.35.1
  30188. segment.byterange = {
  30189. length: length,
  30190. offset: startRange
  30191. };
  30192. }
  30193. return segment;
  30194. };
  30195. var byteRangeToString = function byteRangeToString(byterange) {
  30196. // `endRange` is one less than `offset + length` because the HTTP range
  30197. // header uses inclusive ranges
  30198. var endRange;
  30199. if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {
  30200. endRange = window.BigInt(byterange.offset) + window.BigInt(byterange.length) - window.BigInt(1);
  30201. } else {
  30202. endRange = byterange.offset + byterange.length - 1;
  30203. }
  30204. return byterange.offset + "-" + endRange;
  30205. };
  30206. /**
  30207. * parse the end number attribue that can be a string
  30208. * number, or undefined.
  30209. *
  30210. * @param {string|number|undefined} endNumber
  30211. * The end number attribute.
  30212. *
  30213. * @return {number|null}
  30214. * The result of parsing the end number.
  30215. */
  30216. var parseEndNumber = function parseEndNumber(endNumber) {
  30217. if (endNumber && typeof endNumber !== 'number') {
  30218. endNumber = parseInt(endNumber, 10);
  30219. }
  30220. if (isNaN(endNumber)) {
  30221. return null;
  30222. }
  30223. return endNumber;
  30224. };
  30225. /**
  30226. * Functions for calculating the range of available segments in static and dynamic
  30227. * manifests.
  30228. */
  30229. var segmentRange = {
  30230. /**
  30231. * Returns the entire range of available segments for a static MPD
  30232. *
  30233. * @param {Object} attributes
  30234. * Inheritied MPD attributes
  30235. * @return {{ start: number, end: number }}
  30236. * The start and end numbers for available segments
  30237. */
  30238. "static": function _static(attributes) {
  30239. var duration = attributes.duration,
  30240. _attributes$timescale = attributes.timescale,
  30241. timescale = _attributes$timescale === void 0 ? 1 : _attributes$timescale,
  30242. sourceDuration = attributes.sourceDuration,
  30243. periodDuration = attributes.periodDuration;
  30244. var endNumber = parseEndNumber(attributes.endNumber);
  30245. var segmentDuration = duration / timescale;
  30246. if (typeof endNumber === 'number') {
  30247. return {
  30248. start: 0,
  30249. end: endNumber
  30250. };
  30251. }
  30252. if (typeof periodDuration === 'number') {
  30253. return {
  30254. start: 0,
  30255. end: periodDuration / segmentDuration
  30256. };
  30257. }
  30258. return {
  30259. start: 0,
  30260. end: sourceDuration / segmentDuration
  30261. };
  30262. },
  30263. /**
  30264. * Returns the current live window range of available segments for a dynamic MPD
  30265. *
  30266. * @param {Object} attributes
  30267. * Inheritied MPD attributes
  30268. * @return {{ start: number, end: number }}
  30269. * The start and end numbers for available segments
  30270. */
  30271. dynamic: function dynamic(attributes) {
  30272. var NOW = attributes.NOW,
  30273. clientOffset = attributes.clientOffset,
  30274. availabilityStartTime = attributes.availabilityStartTime,
  30275. _attributes$timescale2 = attributes.timescale,
  30276. timescale = _attributes$timescale2 === void 0 ? 1 : _attributes$timescale2,
  30277. duration = attributes.duration,
  30278. _attributes$periodSta = attributes.periodStart,
  30279. periodStart = _attributes$periodSta === void 0 ? 0 : _attributes$periodSta,
  30280. _attributes$minimumUp = attributes.minimumUpdatePeriod,
  30281. minimumUpdatePeriod = _attributes$minimumUp === void 0 ? 0 : _attributes$minimumUp,
  30282. _attributes$timeShift = attributes.timeShiftBufferDepth,
  30283. timeShiftBufferDepth = _attributes$timeShift === void 0 ? Infinity : _attributes$timeShift;
  30284. var endNumber = parseEndNumber(attributes.endNumber); // clientOffset is passed in at the top level of mpd-parser and is an offset calculated
  30285. // after retrieving UTC server time.
  30286. var now = (NOW + clientOffset) / 1000; // WC stands for Wall Clock.
  30287. // Convert the period start time to EPOCH.
  30288. var periodStartWC = availabilityStartTime + periodStart; // Period end in EPOCH is manifest's retrieval time + time until next update.
  30289. var periodEndWC = now + minimumUpdatePeriod;
  30290. var periodDuration = periodEndWC - periodStartWC;
  30291. var segmentCount = Math.ceil(periodDuration * timescale / duration);
  30292. var availableStart = Math.floor((now - periodStartWC - timeShiftBufferDepth) * timescale / duration);
  30293. var availableEnd = Math.floor((now - periodStartWC) * timescale / duration);
  30294. return {
  30295. start: Math.max(0, availableStart),
  30296. end: typeof endNumber === 'number' ? endNumber : Math.min(segmentCount, availableEnd)
  30297. };
  30298. }
  30299. };
  30300. /**
  30301. * Maps a range of numbers to objects with information needed to build the corresponding
  30302. * segment list
  30303. *
  30304. * @name toSegmentsCallback
  30305. * @function
  30306. * @param {number} number
  30307. * Number of the segment
  30308. * @param {number} index
  30309. * Index of the number in the range list
  30310. * @return {{ number: Number, duration: Number, timeline: Number, time: Number }}
  30311. * Object with segment timing and duration info
  30312. */
  30313. /**
  30314. * Returns a callback for Array.prototype.map for mapping a range of numbers to
  30315. * information needed to build the segment list.
  30316. *
  30317. * @param {Object} attributes
  30318. * Inherited MPD attributes
  30319. * @return {toSegmentsCallback}
  30320. * Callback map function
  30321. */
  30322. var toSegments = function toSegments(attributes) {
  30323. return function (number) {
  30324. var duration = attributes.duration,
  30325. _attributes$timescale3 = attributes.timescale,
  30326. timescale = _attributes$timescale3 === void 0 ? 1 : _attributes$timescale3,
  30327. periodStart = attributes.periodStart,
  30328. _attributes$startNumb = attributes.startNumber,
  30329. startNumber = _attributes$startNumb === void 0 ? 1 : _attributes$startNumb;
  30330. return {
  30331. number: startNumber + number,
  30332. duration: duration / timescale,
  30333. timeline: periodStart,
  30334. time: number * duration
  30335. };
  30336. };
  30337. };
  30338. /**
  30339. * Returns a list of objects containing segment timing and duration info used for
  30340. * building the list of segments. This uses the @duration attribute specified
  30341. * in the MPD manifest to derive the range of segments.
  30342. *
  30343. * @param {Object} attributes
  30344. * Inherited MPD attributes
  30345. * @return {{number: number, duration: number, time: number, timeline: number}[]}
  30346. * List of Objects with segment timing and duration info
  30347. */
  30348. var parseByDuration = function parseByDuration(attributes) {
  30349. var type = attributes.type,
  30350. duration = attributes.duration,
  30351. _attributes$timescale4 = attributes.timescale,
  30352. timescale = _attributes$timescale4 === void 0 ? 1 : _attributes$timescale4,
  30353. periodDuration = attributes.periodDuration,
  30354. sourceDuration = attributes.sourceDuration;
  30355. var _segmentRange$type = segmentRange[type](attributes),
  30356. start = _segmentRange$type.start,
  30357. end = _segmentRange$type.end;
  30358. var segments = range(start, end).map(toSegments(attributes));
  30359. if (type === 'static') {
  30360. var index = segments.length - 1; // section is either a period or the full source
  30361. var sectionDuration = typeof periodDuration === 'number' ? periodDuration : sourceDuration; // final segment may be less than full segment duration
  30362. segments[index].duration = sectionDuration - duration / timescale * index;
  30363. }
  30364. return segments;
  30365. };
  30366. /**
  30367. * Translates SegmentBase into a set of segments.
  30368. * (DASH SPEC Section 5.3.9.3.2) contains a set of <SegmentURL> nodes. Each
  30369. * node should be translated into segment.
  30370. *
  30371. * @param {Object} attributes
  30372. * Object containing all inherited attributes from parent elements with attribute
  30373. * names as keys
  30374. * @return {Object.<Array>} list of segments
  30375. */
  30376. var segmentsFromBase = function segmentsFromBase(attributes) {
  30377. var baseUrl = attributes.baseUrl,
  30378. _attributes$initializ = attributes.initialization,
  30379. initialization = _attributes$initializ === void 0 ? {} : _attributes$initializ,
  30380. sourceDuration = attributes.sourceDuration,
  30381. _attributes$indexRang = attributes.indexRange,
  30382. indexRange = _attributes$indexRang === void 0 ? '' : _attributes$indexRang,
  30383. periodStart = attributes.periodStart,
  30384. presentationTime = attributes.presentationTime,
  30385. _attributes$number = attributes.number,
  30386. number = _attributes$number === void 0 ? 0 : _attributes$number,
  30387. duration = attributes.duration; // base url is required for SegmentBase to work, per spec (Section 5.3.9.2.1)
  30388. if (!baseUrl) {
  30389. throw new Error(errors.NO_BASE_URL);
  30390. }
  30391. var initSegment = urlTypeToSegment({
  30392. baseUrl: baseUrl,
  30393. source: initialization.sourceURL,
  30394. range: initialization.range
  30395. });
  30396. var segment = urlTypeToSegment({
  30397. baseUrl: baseUrl,
  30398. source: baseUrl,
  30399. indexRange: indexRange
  30400. });
  30401. segment.map = initSegment; // If there is a duration, use it, otherwise use the given duration of the source
  30402. // (since SegmentBase is only for one total segment)
  30403. if (duration) {
  30404. var segmentTimeInfo = parseByDuration(attributes);
  30405. if (segmentTimeInfo.length) {
  30406. segment.duration = segmentTimeInfo[0].duration;
  30407. segment.timeline = segmentTimeInfo[0].timeline;
  30408. }
  30409. } else if (sourceDuration) {
  30410. segment.duration = sourceDuration;
  30411. segment.timeline = periodStart;
  30412. } // If presentation time is provided, these segments are being generated by SIDX
  30413. // references, and should use the time provided. For the general case of SegmentBase,
  30414. // there should only be one segment in the period, so its presentation time is the same
  30415. // as its period start.
  30416. segment.presentationTime = presentationTime || periodStart;
  30417. segment.number = number;
  30418. return [segment];
  30419. };
  30420. /**
  30421. * Given a playlist, a sidx box, and a baseUrl, update the segment list of the playlist
  30422. * according to the sidx information given.
  30423. *
  30424. * playlist.sidx has metadadata about the sidx where-as the sidx param
  30425. * is the parsed sidx box itself.
  30426. *
  30427. * @param {Object} playlist the playlist to update the sidx information for
  30428. * @param {Object} sidx the parsed sidx box
  30429. * @return {Object} the playlist object with the updated sidx information
  30430. */
  30431. var addSidxSegmentsToPlaylist$1 = function addSidxSegmentsToPlaylist(playlist, sidx, baseUrl) {
  30432. // Retain init segment information
  30433. var initSegment = playlist.sidx.map ? playlist.sidx.map : null; // Retain source duration from initial main manifest parsing
  30434. var sourceDuration = playlist.sidx.duration; // Retain source timeline
  30435. var timeline = playlist.timeline || 0;
  30436. var sidxByteRange = playlist.sidx.byterange;
  30437. var sidxEnd = sidxByteRange.offset + sidxByteRange.length; // Retain timescale of the parsed sidx
  30438. var timescale = sidx.timescale; // referenceType 1 refers to other sidx boxes
  30439. var mediaReferences = sidx.references.filter(function (r) {
  30440. return r.referenceType !== 1;
  30441. });
  30442. var segments = [];
  30443. var type = playlist.endList ? 'static' : 'dynamic';
  30444. var periodStart = playlist.sidx.timeline;
  30445. var presentationTime = periodStart;
  30446. var number = playlist.mediaSequence || 0; // firstOffset is the offset from the end of the sidx box
  30447. var startIndex; // eslint-disable-next-line
  30448. if (typeof sidx.firstOffset === 'bigint') {
  30449. startIndex = window.BigInt(sidxEnd) + sidx.firstOffset;
  30450. } else {
  30451. startIndex = sidxEnd + sidx.firstOffset;
  30452. }
  30453. for (var i = 0; i < mediaReferences.length; i++) {
  30454. var reference = sidx.references[i]; // size of the referenced (sub)segment
  30455. var size = reference.referencedSize; // duration of the referenced (sub)segment, in the timescale
  30456. // this will be converted to seconds when generating segments
  30457. var duration = reference.subsegmentDuration; // should be an inclusive range
  30458. var endIndex = void 0; // eslint-disable-next-line
  30459. if (typeof startIndex === 'bigint') {
  30460. endIndex = startIndex + window.BigInt(size) - window.BigInt(1);
  30461. } else {
  30462. endIndex = startIndex + size - 1;
  30463. }
  30464. var indexRange = startIndex + "-" + endIndex;
  30465. var attributes = {
  30466. baseUrl: baseUrl,
  30467. timescale: timescale,
  30468. timeline: timeline,
  30469. periodStart: periodStart,
  30470. presentationTime: presentationTime,
  30471. number: number,
  30472. duration: duration,
  30473. sourceDuration: sourceDuration,
  30474. indexRange: indexRange,
  30475. type: type
  30476. };
  30477. var segment = segmentsFromBase(attributes)[0];
  30478. if (initSegment) {
  30479. segment.map = initSegment;
  30480. }
  30481. segments.push(segment);
  30482. if (typeof startIndex === 'bigint') {
  30483. startIndex += window.BigInt(size);
  30484. } else {
  30485. startIndex += size;
  30486. }
  30487. presentationTime += duration / timescale;
  30488. number++;
  30489. }
  30490. playlist.segments = segments;
  30491. return playlist;
  30492. };
  30493. var SUPPORTED_MEDIA_TYPES = ['AUDIO', 'SUBTITLES']; // allow one 60fps frame as leniency (arbitrarily chosen)
  30494. var TIME_FUDGE = 1 / 60;
  30495. /**
  30496. * Given a list of timelineStarts, combines, dedupes, and sorts them.
  30497. *
  30498. * @param {TimelineStart[]} timelineStarts - list of timeline starts
  30499. *
  30500. * @return {TimelineStart[]} the combined and deduped timeline starts
  30501. */
  30502. var getUniqueTimelineStarts = function getUniqueTimelineStarts(timelineStarts) {
  30503. return union(timelineStarts, function (_ref) {
  30504. var timeline = _ref.timeline;
  30505. return timeline;
  30506. }).sort(function (a, b) {
  30507. return a.timeline > b.timeline ? 1 : -1;
  30508. });
  30509. };
  30510. /**
  30511. * Finds the playlist with the matching NAME attribute.
  30512. *
  30513. * @param {Array} playlists - playlists to search through
  30514. * @param {string} name - the NAME attribute to search for
  30515. *
  30516. * @return {Object|null} the matching playlist object, or null
  30517. */
  30518. var findPlaylistWithName = function findPlaylistWithName(playlists, name) {
  30519. for (var i = 0; i < playlists.length; i++) {
  30520. if (playlists[i].attributes.NAME === name) {
  30521. return playlists[i];
  30522. }
  30523. }
  30524. return null;
  30525. };
  30526. /**
  30527. * Gets a flattened array of media group playlists.
  30528. *
  30529. * @param {Object} manifest - the main manifest object
  30530. *
  30531. * @return {Array} the media group playlists
  30532. */
  30533. var getMediaGroupPlaylists = function getMediaGroupPlaylists(manifest) {
  30534. var mediaGroupPlaylists = [];
  30535. forEachMediaGroup$1(manifest, SUPPORTED_MEDIA_TYPES, function (properties, type, group, label) {
  30536. mediaGroupPlaylists = mediaGroupPlaylists.concat(properties.playlists || []);
  30537. });
  30538. return mediaGroupPlaylists;
  30539. };
  30540. /**
  30541. * Updates the playlist's media sequence numbers.
  30542. *
  30543. * @param {Object} config - options object
  30544. * @param {Object} config.playlist - the playlist to update
  30545. * @param {number} config.mediaSequence - the mediaSequence number to start with
  30546. */
  30547. var updateMediaSequenceForPlaylist = function updateMediaSequenceForPlaylist(_ref2) {
  30548. var playlist = _ref2.playlist,
  30549. mediaSequence = _ref2.mediaSequence;
  30550. playlist.mediaSequence = mediaSequence;
  30551. playlist.segments.forEach(function (segment, index) {
  30552. segment.number = playlist.mediaSequence + index;
  30553. });
  30554. };
  30555. /**
  30556. * Updates the media and discontinuity sequence numbers of newPlaylists given oldPlaylists
  30557. * and a complete list of timeline starts.
  30558. *
  30559. * If no matching playlist is found, only the discontinuity sequence number of the playlist
  30560. * will be updated.
  30561. *
  30562. * Since early available timelines are not supported, at least one segment must be present.
  30563. *
  30564. * @param {Object} config - options object
  30565. * @param {Object[]} oldPlaylists - the old playlists to use as a reference
  30566. * @param {Object[]} newPlaylists - the new playlists to update
  30567. * @param {Object} timelineStarts - all timelineStarts seen in the stream to this point
  30568. */
  30569. var updateSequenceNumbers = function updateSequenceNumbers(_ref3) {
  30570. var oldPlaylists = _ref3.oldPlaylists,
  30571. newPlaylists = _ref3.newPlaylists,
  30572. timelineStarts = _ref3.timelineStarts;
  30573. newPlaylists.forEach(function (playlist) {
  30574. playlist.discontinuitySequence = findIndex(timelineStarts, function (_ref4) {
  30575. var timeline = _ref4.timeline;
  30576. return timeline === playlist.timeline;
  30577. }); // Playlists NAMEs come from DASH Representation IDs, which are mandatory
  30578. // (see ISO_23009-1-2012 5.3.5.2).
  30579. //
  30580. // If the same Representation existed in a prior Period, it will retain the same NAME.
  30581. var oldPlaylist = findPlaylistWithName(oldPlaylists, playlist.attributes.NAME);
  30582. if (!oldPlaylist) {
  30583. // Since this is a new playlist, the media sequence values can start from 0 without
  30584. // consequence.
  30585. return;
  30586. } // TODO better support for live SIDX
  30587. //
  30588. // As of this writing, mpd-parser does not support multiperiod SIDX (in live or VOD).
  30589. // This is evident by a playlist only having a single SIDX reference. In a multiperiod
  30590. // playlist there would need to be multiple SIDX references. In addition, live SIDX is
  30591. // not supported when the SIDX properties change on refreshes.
  30592. //
  30593. // In the future, if support needs to be added, the merging logic here can be called
  30594. // after SIDX references are resolved. For now, exit early to prevent exceptions being
  30595. // thrown due to undefined references.
  30596. if (playlist.sidx) {
  30597. return;
  30598. } // Since we don't yet support early available timelines, we don't need to support
  30599. // playlists with no segments.
  30600. var firstNewSegment = playlist.segments[0];
  30601. var oldMatchingSegmentIndex = findIndex(oldPlaylist.segments, function (oldSegment) {
  30602. return Math.abs(oldSegment.presentationTime - firstNewSegment.presentationTime) < TIME_FUDGE;
  30603. }); // No matching segment from the old playlist means the entire playlist was refreshed.
  30604. // In this case the media sequence should account for this update, and the new segments
  30605. // should be marked as discontinuous from the prior content, since the last prior
  30606. // timeline was removed.
  30607. if (oldMatchingSegmentIndex === -1) {
  30608. updateMediaSequenceForPlaylist({
  30609. playlist: playlist,
  30610. mediaSequence: oldPlaylist.mediaSequence + oldPlaylist.segments.length
  30611. });
  30612. playlist.segments[0].discontinuity = true;
  30613. playlist.discontinuityStarts.unshift(0); // No matching segment does not necessarily mean there's missing content.
  30614. //
  30615. // If the new playlist's timeline is the same as the last seen segment's timeline,
  30616. // then a discontinuity can be added to identify that there's potentially missing
  30617. // content. If there's no missing content, the discontinuity should still be rather
  30618. // harmless. It's possible that if segment durations are accurate enough, that the
  30619. // existence of a gap can be determined using the presentation times and durations,
  30620. // but if the segment timing info is off, it may introduce more problems than simply
  30621. // adding the discontinuity.
  30622. //
  30623. // If the new playlist's timeline is different from the last seen segment's timeline,
  30624. // then a discontinuity can be added to identify that this is the first seen segment
  30625. // of a new timeline. However, the logic at the start of this function that
  30626. // determined the disconinuity sequence by timeline index is now off by one (the
  30627. // discontinuity of the newest timeline hasn't yet fallen off the manifest...since
  30628. // we added it), so the disconinuity sequence must be decremented.
  30629. //
  30630. // A period may also have a duration of zero, so the case of no segments is handled
  30631. // here even though we don't yet support early available periods.
  30632. if (!oldPlaylist.segments.length && playlist.timeline > oldPlaylist.timeline || oldPlaylist.segments.length && playlist.timeline > oldPlaylist.segments[oldPlaylist.segments.length - 1].timeline) {
  30633. playlist.discontinuitySequence--;
  30634. }
  30635. return;
  30636. } // If the first segment matched with a prior segment on a discontinuity (it's matching
  30637. // on the first segment of a period), then the discontinuitySequence shouldn't be the
  30638. // timeline's matching one, but instead should be the one prior, and the first segment
  30639. // of the new manifest should be marked with a discontinuity.
  30640. //
  30641. // The reason for this special case is that discontinuity sequence shows how many
  30642. // discontinuities have fallen off of the playlist, and discontinuities are marked on
  30643. // the first segment of a new "timeline." Because of this, while DASH will retain that
  30644. // Period while the "timeline" exists, HLS keeps track of it via the discontinuity
  30645. // sequence, and that first segment is an indicator, but can be removed before that
  30646. // timeline is gone.
  30647. var oldMatchingSegment = oldPlaylist.segments[oldMatchingSegmentIndex];
  30648. if (oldMatchingSegment.discontinuity && !firstNewSegment.discontinuity) {
  30649. firstNewSegment.discontinuity = true;
  30650. playlist.discontinuityStarts.unshift(0);
  30651. playlist.discontinuitySequence--;
  30652. }
  30653. updateMediaSequenceForPlaylist({
  30654. playlist: playlist,
  30655. mediaSequence: oldPlaylist.segments[oldMatchingSegmentIndex].number
  30656. });
  30657. });
  30658. };
  30659. /**
  30660. * Given an old parsed manifest object and a new parsed manifest object, updates the
  30661. * sequence and timing values within the new manifest to ensure that it lines up with the
  30662. * old.
  30663. *
  30664. * @param {Array} oldManifest - the old main manifest object
  30665. * @param {Array} newManifest - the new main manifest object
  30666. *
  30667. * @return {Object} the updated new manifest object
  30668. */
  30669. var positionManifestOnTimeline = function positionManifestOnTimeline(_ref5) {
  30670. var oldManifest = _ref5.oldManifest,
  30671. newManifest = _ref5.newManifest; // Starting from v4.1.2 of the IOP, section 4.4.3.3 states:
  30672. //
  30673. // "MPD@availabilityStartTime and Period@start shall not be changed over MPD updates."
  30674. //
  30675. // This was added from https://github.com/Dash-Industry-Forum/DASH-IF-IOP/issues/160
  30676. //
  30677. // Because of this change, and the difficulty of supporting periods with changing start
  30678. // times, periods with changing start times are not supported. This makes the logic much
  30679. // simpler, since periods with the same start time can be considerred the same period
  30680. // across refreshes.
  30681. //
  30682. // To give an example as to the difficulty of handling periods where the start time may
  30683. // change, if a single period manifest is refreshed with another manifest with a single
  30684. // period, and both the start and end times are increased, then the only way to determine
  30685. // if it's a new period or an old one that has changed is to look through the segments of
  30686. // each playlist and determine the presentation time bounds to find a match. In addition,
  30687. // if the period start changed to exceed the old period end, then there would be no
  30688. // match, and it would not be possible to determine whether the refreshed period is a new
  30689. // one or the old one.
  30690. var oldPlaylists = oldManifest.playlists.concat(getMediaGroupPlaylists(oldManifest));
  30691. var newPlaylists = newManifest.playlists.concat(getMediaGroupPlaylists(newManifest)); // Save all seen timelineStarts to the new manifest. Although this potentially means that
  30692. // there's a "memory leak" in that it will never stop growing, in reality, only a couple
  30693. // of properties are saved for each seen Period. Even long running live streams won't
  30694. // generate too many Periods, unless the stream is watched for decades. In the future,
  30695. // this can be optimized by mapping to discontinuity sequence numbers for each timeline,
  30696. // but it may not become an issue, and the additional info can be useful for debugging.
  30697. newManifest.timelineStarts = getUniqueTimelineStarts([oldManifest.timelineStarts, newManifest.timelineStarts]);
  30698. updateSequenceNumbers({
  30699. oldPlaylists: oldPlaylists,
  30700. newPlaylists: newPlaylists,
  30701. timelineStarts: newManifest.timelineStarts
  30702. });
  30703. return newManifest;
  30704. };
  30705. var generateSidxKey = function generateSidxKey(sidx) {
  30706. return sidx && sidx.uri + '-' + byteRangeToString(sidx.byterange);
  30707. };
  30708. var mergeDiscontiguousPlaylists = function mergeDiscontiguousPlaylists(playlists) {
  30709. var mergedPlaylists = values(playlists.reduce(function (acc, playlist) {
  30710. // assuming playlist IDs are the same across periods
  30711. // TODO: handle multiperiod where representation sets are not the same
  30712. // across periods
  30713. var name = playlist.attributes.id + (playlist.attributes.lang || '');
  30714. if (!acc[name]) {
  30715. // First Period
  30716. acc[name] = playlist;
  30717. acc[name].attributes.timelineStarts = [];
  30718. } else {
  30719. // Subsequent Periods
  30720. if (playlist.segments) {
  30721. var _acc$name$segments; // first segment of subsequent periods signal a discontinuity
  30722. if (playlist.segments[0]) {
  30723. playlist.segments[0].discontinuity = true;
  30724. }
  30725. (_acc$name$segments = acc[name].segments).push.apply(_acc$name$segments, playlist.segments);
  30726. } // bubble up contentProtection, this assumes all DRM content
  30727. // has the same contentProtection
  30728. if (playlist.attributes.contentProtection) {
  30729. acc[name].attributes.contentProtection = playlist.attributes.contentProtection;
  30730. }
  30731. }
  30732. acc[name].attributes.timelineStarts.push({
  30733. // Although they represent the same number, it's important to have both to make it
  30734. // compatible with HLS potentially having a similar attribute.
  30735. start: playlist.attributes.periodStart,
  30736. timeline: playlist.attributes.periodStart
  30737. });
  30738. return acc;
  30739. }, {}));
  30740. return mergedPlaylists.map(function (playlist) {
  30741. playlist.discontinuityStarts = findIndexes(playlist.segments || [], 'discontinuity');
  30742. return playlist;
  30743. });
  30744. };
  30745. var addSidxSegmentsToPlaylist = function addSidxSegmentsToPlaylist(playlist, sidxMapping) {
  30746. var sidxKey = generateSidxKey(playlist.sidx);
  30747. var sidxMatch = sidxKey && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx;
  30748. if (sidxMatch) {
  30749. addSidxSegmentsToPlaylist$1(playlist, sidxMatch, playlist.sidx.resolvedUri);
  30750. }
  30751. return playlist;
  30752. };
  30753. var addSidxSegmentsToPlaylists = function addSidxSegmentsToPlaylists(playlists, sidxMapping) {
  30754. if (sidxMapping === void 0) {
  30755. sidxMapping = {};
  30756. }
  30757. if (!Object.keys(sidxMapping).length) {
  30758. return playlists;
  30759. }
  30760. for (var i in playlists) {
  30761. playlists[i] = addSidxSegmentsToPlaylist(playlists[i], sidxMapping);
  30762. }
  30763. return playlists;
  30764. };
  30765. var formatAudioPlaylist = function formatAudioPlaylist(_ref, isAudioOnly) {
  30766. var _attributes;
  30767. var attributes = _ref.attributes,
  30768. segments = _ref.segments,
  30769. sidx = _ref.sidx,
  30770. mediaSequence = _ref.mediaSequence,
  30771. discontinuitySequence = _ref.discontinuitySequence,
  30772. discontinuityStarts = _ref.discontinuityStarts;
  30773. var playlist = {
  30774. attributes: (_attributes = {
  30775. NAME: attributes.id,
  30776. BANDWIDTH: attributes.bandwidth,
  30777. CODECS: attributes.codecs
  30778. }, _attributes['PROGRAM-ID'] = 1, _attributes),
  30779. uri: '',
  30780. endList: attributes.type === 'static',
  30781. timeline: attributes.periodStart,
  30782. resolvedUri: '',
  30783. targetDuration: attributes.duration,
  30784. discontinuitySequence: discontinuitySequence,
  30785. discontinuityStarts: discontinuityStarts,
  30786. timelineStarts: attributes.timelineStarts,
  30787. mediaSequence: mediaSequence,
  30788. segments: segments
  30789. };
  30790. if (attributes.contentProtection) {
  30791. playlist.contentProtection = attributes.contentProtection;
  30792. }
  30793. if (sidx) {
  30794. playlist.sidx = sidx;
  30795. }
  30796. if (isAudioOnly) {
  30797. playlist.attributes.AUDIO = 'audio';
  30798. playlist.attributes.SUBTITLES = 'subs';
  30799. }
  30800. return playlist;
  30801. };
  30802. var formatVttPlaylist = function formatVttPlaylist(_ref2) {
  30803. var _m3u8Attributes;
  30804. var attributes = _ref2.attributes,
  30805. segments = _ref2.segments,
  30806. mediaSequence = _ref2.mediaSequence,
  30807. discontinuityStarts = _ref2.discontinuityStarts,
  30808. discontinuitySequence = _ref2.discontinuitySequence;
  30809. if (typeof segments === 'undefined') {
  30810. // vtt tracks may use single file in BaseURL
  30811. segments = [{
  30812. uri: attributes.baseUrl,
  30813. timeline: attributes.periodStart,
  30814. resolvedUri: attributes.baseUrl || '',
  30815. duration: attributes.sourceDuration,
  30816. number: 0
  30817. }]; // targetDuration should be the same duration as the only segment
  30818. attributes.duration = attributes.sourceDuration;
  30819. }
  30820. var m3u8Attributes = (_m3u8Attributes = {
  30821. NAME: attributes.id,
  30822. BANDWIDTH: attributes.bandwidth
  30823. }, _m3u8Attributes['PROGRAM-ID'] = 1, _m3u8Attributes);
  30824. if (attributes.codecs) {
  30825. m3u8Attributes.CODECS = attributes.codecs;
  30826. }
  30827. return {
  30828. attributes: m3u8Attributes,
  30829. uri: '',
  30830. endList: attributes.type === 'static',
  30831. timeline: attributes.periodStart,
  30832. resolvedUri: attributes.baseUrl || '',
  30833. targetDuration: attributes.duration,
  30834. timelineStarts: attributes.timelineStarts,
  30835. discontinuityStarts: discontinuityStarts,
  30836. discontinuitySequence: discontinuitySequence,
  30837. mediaSequence: mediaSequence,
  30838. segments: segments
  30839. };
  30840. };
  30841. var organizeAudioPlaylists = function organizeAudioPlaylists(playlists, sidxMapping, isAudioOnly) {
  30842. if (sidxMapping === void 0) {
  30843. sidxMapping = {};
  30844. }
  30845. if (isAudioOnly === void 0) {
  30846. isAudioOnly = false;
  30847. }
  30848. var mainPlaylist;
  30849. var formattedPlaylists = playlists.reduce(function (a, playlist) {
  30850. var role = playlist.attributes.role && playlist.attributes.role.value || '';
  30851. var language = playlist.attributes.lang || '';
  30852. var label = playlist.attributes.label || 'main';
  30853. if (language && !playlist.attributes.label) {
  30854. var roleLabel = role ? " (" + role + ")" : '';
  30855. label = "" + playlist.attributes.lang + roleLabel;
  30856. }
  30857. if (!a[label]) {
  30858. a[label] = {
  30859. language: language,
  30860. autoselect: true,
  30861. "default": role === 'main',
  30862. playlists: [],
  30863. uri: ''
  30864. };
  30865. }
  30866. var formatted = addSidxSegmentsToPlaylist(formatAudioPlaylist(playlist, isAudioOnly), sidxMapping);
  30867. a[label].playlists.push(formatted);
  30868. if (typeof mainPlaylist === 'undefined' && role === 'main') {
  30869. mainPlaylist = playlist;
  30870. mainPlaylist["default"] = true;
  30871. }
  30872. return a;
  30873. }, {}); // if no playlists have role "main", mark the first as main
  30874. if (!mainPlaylist) {
  30875. var firstLabel = Object.keys(formattedPlaylists)[0];
  30876. formattedPlaylists[firstLabel]["default"] = true;
  30877. }
  30878. return formattedPlaylists;
  30879. };
  30880. var organizeVttPlaylists = function organizeVttPlaylists(playlists, sidxMapping) {
  30881. if (sidxMapping === void 0) {
  30882. sidxMapping = {};
  30883. }
  30884. return playlists.reduce(function (a, playlist) {
  30885. var label = playlist.attributes.lang || 'text';
  30886. if (!a[label]) {
  30887. a[label] = {
  30888. language: label,
  30889. "default": false,
  30890. autoselect: false,
  30891. playlists: [],
  30892. uri: ''
  30893. };
  30894. }
  30895. a[label].playlists.push(addSidxSegmentsToPlaylist(formatVttPlaylist(playlist), sidxMapping));
  30896. return a;
  30897. }, {});
  30898. };
  30899. var organizeCaptionServices = function organizeCaptionServices(captionServices) {
  30900. return captionServices.reduce(function (svcObj, svc) {
  30901. if (!svc) {
  30902. return svcObj;
  30903. }
  30904. svc.forEach(function (service) {
  30905. var channel = service.channel,
  30906. language = service.language;
  30907. svcObj[language] = {
  30908. autoselect: false,
  30909. "default": false,
  30910. instreamId: channel,
  30911. language: language
  30912. };
  30913. if (service.hasOwnProperty('aspectRatio')) {
  30914. svcObj[language].aspectRatio = service.aspectRatio;
  30915. }
  30916. if (service.hasOwnProperty('easyReader')) {
  30917. svcObj[language].easyReader = service.easyReader;
  30918. }
  30919. if (service.hasOwnProperty('3D')) {
  30920. svcObj[language]['3D'] = service['3D'];
  30921. }
  30922. });
  30923. return svcObj;
  30924. }, {});
  30925. };
  30926. var formatVideoPlaylist = function formatVideoPlaylist(_ref3) {
  30927. var _attributes2;
  30928. var attributes = _ref3.attributes,
  30929. segments = _ref3.segments,
  30930. sidx = _ref3.sidx,
  30931. discontinuityStarts = _ref3.discontinuityStarts;
  30932. var playlist = {
  30933. attributes: (_attributes2 = {
  30934. NAME: attributes.id,
  30935. AUDIO: 'audio',
  30936. SUBTITLES: 'subs',
  30937. RESOLUTION: {
  30938. width: attributes.width,
  30939. height: attributes.height
  30940. },
  30941. CODECS: attributes.codecs,
  30942. BANDWIDTH: attributes.bandwidth
  30943. }, _attributes2['PROGRAM-ID'] = 1, _attributes2),
  30944. uri: '',
  30945. endList: attributes.type === 'static',
  30946. timeline: attributes.periodStart,
  30947. resolvedUri: '',
  30948. targetDuration: attributes.duration,
  30949. discontinuityStarts: discontinuityStarts,
  30950. timelineStarts: attributes.timelineStarts,
  30951. segments: segments
  30952. };
  30953. if (attributes.frameRate) {
  30954. playlist.attributes['FRAME-RATE'] = attributes.frameRate;
  30955. }
  30956. if (attributes.contentProtection) {
  30957. playlist.contentProtection = attributes.contentProtection;
  30958. }
  30959. if (sidx) {
  30960. playlist.sidx = sidx;
  30961. }
  30962. return playlist;
  30963. };
  30964. var videoOnly = function videoOnly(_ref4) {
  30965. var attributes = _ref4.attributes;
  30966. return attributes.mimeType === 'video/mp4' || attributes.mimeType === 'video/webm' || attributes.contentType === 'video';
  30967. };
  30968. var audioOnly = function audioOnly(_ref5) {
  30969. var attributes = _ref5.attributes;
  30970. return attributes.mimeType === 'audio/mp4' || attributes.mimeType === 'audio/webm' || attributes.contentType === 'audio';
  30971. };
  30972. var vttOnly = function vttOnly(_ref6) {
  30973. var attributes = _ref6.attributes;
  30974. return attributes.mimeType === 'text/vtt' || attributes.contentType === 'text';
  30975. };
  30976. /**
  30977. * Contains start and timeline properties denoting a timeline start. For DASH, these will
  30978. * be the same number.
  30979. *
  30980. * @typedef {Object} TimelineStart
  30981. * @property {number} start - the start time of the timeline
  30982. * @property {number} timeline - the timeline number
  30983. */
  30984. /**
  30985. * Adds appropriate media and discontinuity sequence values to the segments and playlists.
  30986. *
  30987. * Throughout mpd-parser, the `number` attribute is used in relation to `startNumber`, a
  30988. * DASH specific attribute used in constructing segment URI's from templates. However, from
  30989. * an HLS perspective, the `number` attribute on a segment would be its `mediaSequence`
  30990. * value, which should start at the original media sequence value (or 0) and increment by 1
  30991. * for each segment thereafter. Since DASH's `startNumber` values are independent per
  30992. * period, it doesn't make sense to use it for `number`. Instead, assume everything starts
  30993. * from a 0 mediaSequence value and increment from there.
  30994. *
  30995. * Note that VHS currently doesn't use the `number` property, but it can be helpful for
  30996. * debugging and making sense of the manifest.
  30997. *
  30998. * For live playlists, to account for values increasing in manifests when periods are
  30999. * removed on refreshes, merging logic should be used to update the numbers to their
  31000. * appropriate values (to ensure they're sequential and increasing).
  31001. *
  31002. * @param {Object[]} playlists - the playlists to update
  31003. * @param {TimelineStart[]} timelineStarts - the timeline starts for the manifest
  31004. */
  31005. var addMediaSequenceValues = function addMediaSequenceValues(playlists, timelineStarts) {
  31006. // increment all segments sequentially
  31007. playlists.forEach(function (playlist) {
  31008. playlist.mediaSequence = 0;
  31009. playlist.discontinuitySequence = findIndex(timelineStarts, function (_ref7) {
  31010. var timeline = _ref7.timeline;
  31011. return timeline === playlist.timeline;
  31012. });
  31013. if (!playlist.segments) {
  31014. return;
  31015. }
  31016. playlist.segments.forEach(function (segment, index) {
  31017. segment.number = index;
  31018. });
  31019. });
  31020. };
  31021. /**
  31022. * Given a media group object, flattens all playlists within the media group into a single
  31023. * array.
  31024. *
  31025. * @param {Object} mediaGroupObject - the media group object
  31026. *
  31027. * @return {Object[]}
  31028. * The media group playlists
  31029. */
  31030. var flattenMediaGroupPlaylists = function flattenMediaGroupPlaylists(mediaGroupObject) {
  31031. if (!mediaGroupObject) {
  31032. return [];
  31033. }
  31034. return Object.keys(mediaGroupObject).reduce(function (acc, label) {
  31035. var labelContents = mediaGroupObject[label];
  31036. return acc.concat(labelContents.playlists);
  31037. }, []);
  31038. };
  31039. var toM3u8 = function toM3u8(_ref8) {
  31040. var _mediaGroups;
  31041. var dashPlaylists = _ref8.dashPlaylists,
  31042. locations = _ref8.locations,
  31043. _ref8$sidxMapping = _ref8.sidxMapping,
  31044. sidxMapping = _ref8$sidxMapping === void 0 ? {} : _ref8$sidxMapping,
  31045. previousManifest = _ref8.previousManifest;
  31046. if (!dashPlaylists.length) {
  31047. return {};
  31048. } // grab all main manifest attributes
  31049. var _dashPlaylists$0$attr = dashPlaylists[0].attributes,
  31050. duration = _dashPlaylists$0$attr.sourceDuration,
  31051. type = _dashPlaylists$0$attr.type,
  31052. suggestedPresentationDelay = _dashPlaylists$0$attr.suggestedPresentationDelay,
  31053. minimumUpdatePeriod = _dashPlaylists$0$attr.minimumUpdatePeriod;
  31054. var videoPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(videoOnly)).map(formatVideoPlaylist);
  31055. var audioPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(audioOnly));
  31056. var vttPlaylists = mergeDiscontiguousPlaylists(dashPlaylists.filter(vttOnly));
  31057. var captions = dashPlaylists.map(function (playlist) {
  31058. return playlist.attributes.captionServices;
  31059. }).filter(Boolean);
  31060. var manifest = {
  31061. allowCache: true,
  31062. discontinuityStarts: [],
  31063. segments: [],
  31064. endList: true,
  31065. mediaGroups: (_mediaGroups = {
  31066. AUDIO: {},
  31067. VIDEO: {}
  31068. }, _mediaGroups['CLOSED-CAPTIONS'] = {}, _mediaGroups.SUBTITLES = {}, _mediaGroups),
  31069. uri: '',
  31070. duration: duration,
  31071. playlists: addSidxSegmentsToPlaylists(videoPlaylists, sidxMapping)
  31072. };
  31073. if (minimumUpdatePeriod >= 0) {
  31074. manifest.minimumUpdatePeriod = minimumUpdatePeriod * 1000;
  31075. }
  31076. if (locations) {
  31077. manifest.locations = locations;
  31078. }
  31079. if (type === 'dynamic') {
  31080. manifest.suggestedPresentationDelay = suggestedPresentationDelay;
  31081. }
  31082. var isAudioOnly = manifest.playlists.length === 0;
  31083. var organizedAudioGroup = audioPlaylists.length ? organizeAudioPlaylists(audioPlaylists, sidxMapping, isAudioOnly) : null;
  31084. var organizedVttGroup = vttPlaylists.length ? organizeVttPlaylists(vttPlaylists, sidxMapping) : null;
  31085. var formattedPlaylists = videoPlaylists.concat(flattenMediaGroupPlaylists(organizedAudioGroup), flattenMediaGroupPlaylists(organizedVttGroup));
  31086. var playlistTimelineStarts = formattedPlaylists.map(function (_ref9) {
  31087. var timelineStarts = _ref9.timelineStarts;
  31088. return timelineStarts;
  31089. });
  31090. manifest.timelineStarts = getUniqueTimelineStarts(playlistTimelineStarts);
  31091. addMediaSequenceValues(formattedPlaylists, manifest.timelineStarts);
  31092. if (organizedAudioGroup) {
  31093. manifest.mediaGroups.AUDIO.audio = organizedAudioGroup;
  31094. }
  31095. if (organizedVttGroup) {
  31096. manifest.mediaGroups.SUBTITLES.subs = organizedVttGroup;
  31097. }
  31098. if (captions.length) {
  31099. manifest.mediaGroups['CLOSED-CAPTIONS'].cc = organizeCaptionServices(captions);
  31100. }
  31101. if (previousManifest) {
  31102. return positionManifestOnTimeline({
  31103. oldManifest: previousManifest,
  31104. newManifest: manifest
  31105. });
  31106. }
  31107. return manifest;
  31108. };
  31109. /**
  31110. * Calculates the R (repetition) value for a live stream (for the final segment
  31111. * in a manifest where the r value is negative 1)
  31112. *
  31113. * @param {Object} attributes
  31114. * Object containing all inherited attributes from parent elements with attribute
  31115. * names as keys
  31116. * @param {number} time
  31117. * current time (typically the total time up until the final segment)
  31118. * @param {number} duration
  31119. * duration property for the given <S />
  31120. *
  31121. * @return {number}
  31122. * R value to reach the end of the given period
  31123. */
  31124. var getLiveRValue = function getLiveRValue(attributes, time, duration) {
  31125. var NOW = attributes.NOW,
  31126. clientOffset = attributes.clientOffset,
  31127. availabilityStartTime = attributes.availabilityStartTime,
  31128. _attributes$timescale = attributes.timescale,
  31129. timescale = _attributes$timescale === void 0 ? 1 : _attributes$timescale,
  31130. _attributes$periodSta = attributes.periodStart,
  31131. periodStart = _attributes$periodSta === void 0 ? 0 : _attributes$periodSta,
  31132. _attributes$minimumUp = attributes.minimumUpdatePeriod,
  31133. minimumUpdatePeriod = _attributes$minimumUp === void 0 ? 0 : _attributes$minimumUp;
  31134. var now = (NOW + clientOffset) / 1000;
  31135. var periodStartWC = availabilityStartTime + periodStart;
  31136. var periodEndWC = now + minimumUpdatePeriod;
  31137. var periodDuration = periodEndWC - periodStartWC;
  31138. return Math.ceil((periodDuration * timescale - time) / duration);
  31139. };
  31140. /**
  31141. * Uses information provided by SegmentTemplate.SegmentTimeline to determine segment
  31142. * timing and duration
  31143. *
  31144. * @param {Object} attributes
  31145. * Object containing all inherited attributes from parent elements with attribute
  31146. * names as keys
  31147. * @param {Object[]} segmentTimeline
  31148. * List of objects representing the attributes of each S element contained within
  31149. *
  31150. * @return {{number: number, duration: number, time: number, timeline: number}[]}
  31151. * List of Objects with segment timing and duration info
  31152. */
  31153. var parseByTimeline = function parseByTimeline(attributes, segmentTimeline) {
  31154. var type = attributes.type,
  31155. _attributes$minimumUp2 = attributes.minimumUpdatePeriod,
  31156. minimumUpdatePeriod = _attributes$minimumUp2 === void 0 ? 0 : _attributes$minimumUp2,
  31157. _attributes$media = attributes.media,
  31158. media = _attributes$media === void 0 ? '' : _attributes$media,
  31159. sourceDuration = attributes.sourceDuration,
  31160. _attributes$timescale2 = attributes.timescale,
  31161. timescale = _attributes$timescale2 === void 0 ? 1 : _attributes$timescale2,
  31162. _attributes$startNumb = attributes.startNumber,
  31163. startNumber = _attributes$startNumb === void 0 ? 1 : _attributes$startNumb,
  31164. timeline = attributes.periodStart;
  31165. var segments = [];
  31166. var time = -1;
  31167. for (var sIndex = 0; sIndex < segmentTimeline.length; sIndex++) {
  31168. var S = segmentTimeline[sIndex];
  31169. var duration = S.d;
  31170. var repeat = S.r || 0;
  31171. var segmentTime = S.t || 0;
  31172. if (time < 0) {
  31173. // first segment
  31174. time = segmentTime;
  31175. }
  31176. if (segmentTime && segmentTime > time) {
  31177. // discontinuity
  31178. // TODO: How to handle this type of discontinuity
  31179. // timeline++ here would treat it like HLS discontuity and content would
  31180. // get appended without gap
  31181. // E.G.
  31182. // <S t="0" d="1" />
  31183. // <S d="1" />
  31184. // <S d="1" />
  31185. // <S t="5" d="1" />
  31186. // would have $Time$ values of [0, 1, 2, 5]
  31187. // should this be appened at time positions [0, 1, 2, 3],(#EXT-X-DISCONTINUITY)
  31188. // or [0, 1, 2, gap, gap, 5]? (#EXT-X-GAP)
  31189. // does the value of sourceDuration consider this when calculating arbitrary
  31190. // negative @r repeat value?
  31191. // E.G. Same elements as above with this added at the end
  31192. // <S d="1" r="-1" />
  31193. // with a sourceDuration of 10
  31194. // Would the 2 gaps be included in the time duration calculations resulting in
  31195. // 8 segments with $Time$ values of [0, 1, 2, 5, 6, 7, 8, 9] or 10 segments
  31196. // with $Time$ values of [0, 1, 2, 5, 6, 7, 8, 9, 10, 11] ?
  31197. time = segmentTime;
  31198. }
  31199. var count = void 0;
  31200. if (repeat < 0) {
  31201. var nextS = sIndex + 1;
  31202. if (nextS === segmentTimeline.length) {
  31203. // last segment
  31204. if (type === 'dynamic' && minimumUpdatePeriod > 0 && media.indexOf('$Number$') > 0) {
  31205. count = getLiveRValue(attributes, time, duration);
  31206. } else {
  31207. // TODO: This may be incorrect depending on conclusion of TODO above
  31208. count = (sourceDuration * timescale - time) / duration;
  31209. }
  31210. } else {
  31211. count = (segmentTimeline[nextS].t - time) / duration;
  31212. }
  31213. } else {
  31214. count = repeat + 1;
  31215. }
  31216. var end = startNumber + segments.length + count;
  31217. var number = startNumber + segments.length;
  31218. while (number < end) {
  31219. segments.push({
  31220. number: number,
  31221. duration: duration / timescale,
  31222. time: time,
  31223. timeline: timeline
  31224. });
  31225. time += duration;
  31226. number++;
  31227. }
  31228. }
  31229. return segments;
  31230. };
  31231. var identifierPattern = /\$([A-z]*)(?:(%0)([0-9]+)d)?\$/g;
  31232. /**
  31233. * Replaces template identifiers with corresponding values. To be used as the callback
  31234. * for String.prototype.replace
  31235. *
  31236. * @name replaceCallback
  31237. * @function
  31238. * @param {string} match
  31239. * Entire match of identifier
  31240. * @param {string} identifier
  31241. * Name of matched identifier
  31242. * @param {string} format
  31243. * Format tag string. Its presence indicates that padding is expected
  31244. * @param {string} width
  31245. * Desired length of the replaced value. Values less than this width shall be left
  31246. * zero padded
  31247. * @return {string}
  31248. * Replacement for the matched identifier
  31249. */
  31250. /**
  31251. * Returns a function to be used as a callback for String.prototype.replace to replace
  31252. * template identifiers
  31253. *
  31254. * @param {Obect} values
  31255. * Object containing values that shall be used to replace known identifiers
  31256. * @param {number} values.RepresentationID
  31257. * Value of the Representation@id attribute
  31258. * @param {number} values.Number
  31259. * Number of the corresponding segment
  31260. * @param {number} values.Bandwidth
  31261. * Value of the Representation@bandwidth attribute.
  31262. * @param {number} values.Time
  31263. * Timestamp value of the corresponding segment
  31264. * @return {replaceCallback}
  31265. * Callback to be used with String.prototype.replace to replace identifiers
  31266. */
  31267. var identifierReplacement = function identifierReplacement(values) {
  31268. return function (match, identifier, format, width) {
  31269. if (match === '$$') {
  31270. // escape sequence
  31271. return '$';
  31272. }
  31273. if (typeof values[identifier] === 'undefined') {
  31274. return match;
  31275. }
  31276. var value = '' + values[identifier];
  31277. if (identifier === 'RepresentationID') {
  31278. // Format tag shall not be present with RepresentationID
  31279. return value;
  31280. }
  31281. if (!format) {
  31282. width = 1;
  31283. } else {
  31284. width = parseInt(width, 10);
  31285. }
  31286. if (value.length >= width) {
  31287. return value;
  31288. }
  31289. return "" + new Array(width - value.length + 1).join('0') + value;
  31290. };
  31291. };
  31292. /**
  31293. * Constructs a segment url from a template string
  31294. *
  31295. * @param {string} url
  31296. * Template string to construct url from
  31297. * @param {Obect} values
  31298. * Object containing values that shall be used to replace known identifiers
  31299. * @param {number} values.RepresentationID
  31300. * Value of the Representation@id attribute
  31301. * @param {number} values.Number
  31302. * Number of the corresponding segment
  31303. * @param {number} values.Bandwidth
  31304. * Value of the Representation@bandwidth attribute.
  31305. * @param {number} values.Time
  31306. * Timestamp value of the corresponding segment
  31307. * @return {string}
  31308. * Segment url with identifiers replaced
  31309. */
  31310. var constructTemplateUrl = function constructTemplateUrl(url, values) {
  31311. return url.replace(identifierPattern, identifierReplacement(values));
  31312. };
  31313. /**
  31314. * Generates a list of objects containing timing and duration information about each
  31315. * segment needed to generate segment uris and the complete segment object
  31316. *
  31317. * @param {Object} attributes
  31318. * Object containing all inherited attributes from parent elements with attribute
  31319. * names as keys
  31320. * @param {Object[]|undefined} segmentTimeline
  31321. * List of objects representing the attributes of each S element contained within
  31322. * the SegmentTimeline element
  31323. * @return {{number: number, duration: number, time: number, timeline: number}[]}
  31324. * List of Objects with segment timing and duration info
  31325. */
  31326. var parseTemplateInfo = function parseTemplateInfo(attributes, segmentTimeline) {
  31327. if (!attributes.duration && !segmentTimeline) {
  31328. // if neither @duration or SegmentTimeline are present, then there shall be exactly
  31329. // one media segment
  31330. return [{
  31331. number: attributes.startNumber || 1,
  31332. duration: attributes.sourceDuration,
  31333. time: 0,
  31334. timeline: attributes.periodStart
  31335. }];
  31336. }
  31337. if (attributes.duration) {
  31338. return parseByDuration(attributes);
  31339. }
  31340. return parseByTimeline(attributes, segmentTimeline);
  31341. };
  31342. /**
  31343. * Generates a list of segments using information provided by the SegmentTemplate element
  31344. *
  31345. * @param {Object} attributes
  31346. * Object containing all inherited attributes from parent elements with attribute
  31347. * names as keys
  31348. * @param {Object[]|undefined} segmentTimeline
  31349. * List of objects representing the attributes of each S element contained within
  31350. * the SegmentTimeline element
  31351. * @return {Object[]}
  31352. * List of segment objects
  31353. */
  31354. var segmentsFromTemplate = function segmentsFromTemplate(attributes, segmentTimeline) {
  31355. var templateValues = {
  31356. RepresentationID: attributes.id,
  31357. Bandwidth: attributes.bandwidth || 0
  31358. };
  31359. var _attributes$initializ = attributes.initialization,
  31360. initialization = _attributes$initializ === void 0 ? {
  31361. sourceURL: '',
  31362. range: ''
  31363. } : _attributes$initializ;
  31364. var mapSegment = urlTypeToSegment({
  31365. baseUrl: attributes.baseUrl,
  31366. source: constructTemplateUrl(initialization.sourceURL, templateValues),
  31367. range: initialization.range
  31368. });
  31369. var segments = parseTemplateInfo(attributes, segmentTimeline);
  31370. return segments.map(function (segment) {
  31371. templateValues.Number = segment.number;
  31372. templateValues.Time = segment.time;
  31373. var uri = constructTemplateUrl(attributes.media || '', templateValues); // See DASH spec section 5.3.9.2.2
  31374. // - if timescale isn't present on any level, default to 1.
  31375. var timescale = attributes.timescale || 1; // - if presentationTimeOffset isn't present on any level, default to 0
  31376. var presentationTimeOffset = attributes.presentationTimeOffset || 0;
  31377. var presentationTime = // Even if the @t attribute is not specified for the segment, segment.time is
  31378. // calculated in mpd-parser prior to this, so it's assumed to be available.
  31379. attributes.periodStart + (segment.time - presentationTimeOffset) / timescale;
  31380. var map = {
  31381. uri: uri,
  31382. timeline: segment.timeline,
  31383. duration: segment.duration,
  31384. resolvedUri: resolveUrl$1(attributes.baseUrl || '', uri),
  31385. map: mapSegment,
  31386. number: segment.number,
  31387. presentationTime: presentationTime
  31388. };
  31389. return map;
  31390. });
  31391. };
  31392. /**
  31393. * Converts a <SegmentUrl> (of type URLType from the DASH spec 5.3.9.2 Table 14)
  31394. * to an object that matches the output of a segment in videojs/mpd-parser
  31395. *
  31396. * @param {Object} attributes
  31397. * Object containing all inherited attributes from parent elements with attribute
  31398. * names as keys
  31399. * @param {Object} segmentUrl
  31400. * <SegmentURL> node to translate into a segment object
  31401. * @return {Object} translated segment object
  31402. */
  31403. var SegmentURLToSegmentObject = function SegmentURLToSegmentObject(attributes, segmentUrl) {
  31404. var baseUrl = attributes.baseUrl,
  31405. _attributes$initializ = attributes.initialization,
  31406. initialization = _attributes$initializ === void 0 ? {} : _attributes$initializ;
  31407. var initSegment = urlTypeToSegment({
  31408. baseUrl: baseUrl,
  31409. source: initialization.sourceURL,
  31410. range: initialization.range
  31411. });
  31412. var segment = urlTypeToSegment({
  31413. baseUrl: baseUrl,
  31414. source: segmentUrl.media,
  31415. range: segmentUrl.mediaRange
  31416. });
  31417. segment.map = initSegment;
  31418. return segment;
  31419. };
  31420. /**
  31421. * Generates a list of segments using information provided by the SegmentList element
  31422. * SegmentList (DASH SPEC Section 5.3.9.3.2) contains a set of <SegmentURL> nodes. Each
  31423. * node should be translated into segment.
  31424. *
  31425. * @param {Object} attributes
  31426. * Object containing all inherited attributes from parent elements with attribute
  31427. * names as keys
  31428. * @param {Object[]|undefined} segmentTimeline
  31429. * List of objects representing the attributes of each S element contained within
  31430. * the SegmentTimeline element
  31431. * @return {Object.<Array>} list of segments
  31432. */
  31433. var segmentsFromList = function segmentsFromList(attributes, segmentTimeline) {
  31434. var duration = attributes.duration,
  31435. _attributes$segmentUr = attributes.segmentUrls,
  31436. segmentUrls = _attributes$segmentUr === void 0 ? [] : _attributes$segmentUr,
  31437. periodStart = attributes.periodStart; // Per spec (5.3.9.2.1) no way to determine segment duration OR
  31438. // if both SegmentTimeline and @duration are defined, it is outside of spec.
  31439. if (!duration && !segmentTimeline || duration && segmentTimeline) {
  31440. throw new Error(errors.SEGMENT_TIME_UNSPECIFIED);
  31441. }
  31442. var segmentUrlMap = segmentUrls.map(function (segmentUrlObject) {
  31443. return SegmentURLToSegmentObject(attributes, segmentUrlObject);
  31444. });
  31445. var segmentTimeInfo;
  31446. if (duration) {
  31447. segmentTimeInfo = parseByDuration(attributes);
  31448. }
  31449. if (segmentTimeline) {
  31450. segmentTimeInfo = parseByTimeline(attributes, segmentTimeline);
  31451. }
  31452. var segments = segmentTimeInfo.map(function (segmentTime, index) {
  31453. if (segmentUrlMap[index]) {
  31454. var segment = segmentUrlMap[index]; // See DASH spec section 5.3.9.2.2
  31455. // - if timescale isn't present on any level, default to 1.
  31456. var timescale = attributes.timescale || 1; // - if presentationTimeOffset isn't present on any level, default to 0
  31457. var presentationTimeOffset = attributes.presentationTimeOffset || 0;
  31458. segment.timeline = segmentTime.timeline;
  31459. segment.duration = segmentTime.duration;
  31460. segment.number = segmentTime.number;
  31461. segment.presentationTime = periodStart + (segmentTime.time - presentationTimeOffset) / timescale;
  31462. return segment;
  31463. } // Since we're mapping we should get rid of any blank segments (in case
  31464. // the given SegmentTimeline is handling for more elements than we have
  31465. // SegmentURLs for).
  31466. }).filter(function (segment) {
  31467. return segment;
  31468. });
  31469. return segments;
  31470. };
  31471. var generateSegments = function generateSegments(_ref) {
  31472. var attributes = _ref.attributes,
  31473. segmentInfo = _ref.segmentInfo;
  31474. var segmentAttributes;
  31475. var segmentsFn;
  31476. if (segmentInfo.template) {
  31477. segmentsFn = segmentsFromTemplate;
  31478. segmentAttributes = merge(attributes, segmentInfo.template);
  31479. } else if (segmentInfo.base) {
  31480. segmentsFn = segmentsFromBase;
  31481. segmentAttributes = merge(attributes, segmentInfo.base);
  31482. } else if (segmentInfo.list) {
  31483. segmentsFn = segmentsFromList;
  31484. segmentAttributes = merge(attributes, segmentInfo.list);
  31485. }
  31486. var segmentsInfo = {
  31487. attributes: attributes
  31488. };
  31489. if (!segmentsFn) {
  31490. return segmentsInfo;
  31491. }
  31492. var segments = segmentsFn(segmentAttributes, segmentInfo.segmentTimeline); // The @duration attribute will be used to determin the playlist's targetDuration which
  31493. // must be in seconds. Since we've generated the segment list, we no longer need
  31494. // @duration to be in @timescale units, so we can convert it here.
  31495. if (segmentAttributes.duration) {
  31496. var _segmentAttributes = segmentAttributes,
  31497. duration = _segmentAttributes.duration,
  31498. _segmentAttributes$ti = _segmentAttributes.timescale,
  31499. timescale = _segmentAttributes$ti === void 0 ? 1 : _segmentAttributes$ti;
  31500. segmentAttributes.duration = duration / timescale;
  31501. } else if (segments.length) {
  31502. // if there is no @duration attribute, use the largest segment duration as
  31503. // as target duration
  31504. segmentAttributes.duration = segments.reduce(function (max, segment) {
  31505. return Math.max(max, Math.ceil(segment.duration));
  31506. }, 0);
  31507. } else {
  31508. segmentAttributes.duration = 0;
  31509. }
  31510. segmentsInfo.attributes = segmentAttributes;
  31511. segmentsInfo.segments = segments; // This is a sidx box without actual segment information
  31512. if (segmentInfo.base && segmentAttributes.indexRange) {
  31513. segmentsInfo.sidx = segments[0];
  31514. segmentsInfo.segments = [];
  31515. }
  31516. return segmentsInfo;
  31517. };
  31518. var toPlaylists = function toPlaylists(representations) {
  31519. return representations.map(generateSegments);
  31520. };
  31521. var findChildren = function findChildren(element, name) {
  31522. return from(element.childNodes).filter(function (_ref) {
  31523. var tagName = _ref.tagName;
  31524. return tagName === name;
  31525. });
  31526. };
  31527. var getContent = function getContent(element) {
  31528. return element.textContent.trim();
  31529. };
  31530. /**
  31531. * Converts the provided string that may contain a division operation to a number.
  31532. *
  31533. * @param {string} value - the provided string value
  31534. *
  31535. * @return {number} the parsed string value
  31536. */
  31537. var parseDivisionValue = function parseDivisionValue(value) {
  31538. return parseFloat(value.split('/').reduce(function (prev, current) {
  31539. return prev / current;
  31540. }));
  31541. };
  31542. var parseDuration = function parseDuration(str) {
  31543. var SECONDS_IN_YEAR = 365 * 24 * 60 * 60;
  31544. var SECONDS_IN_MONTH = 30 * 24 * 60 * 60;
  31545. var SECONDS_IN_DAY = 24 * 60 * 60;
  31546. var SECONDS_IN_HOUR = 60 * 60;
  31547. var SECONDS_IN_MIN = 60; // P10Y10M10DT10H10M10.1S
  31548. var durationRegex = /P(?:(\d*)Y)?(?:(\d*)M)?(?:(\d*)D)?(?:T(?:(\d*)H)?(?:(\d*)M)?(?:([\d.]*)S)?)?/;
  31549. var match = durationRegex.exec(str);
  31550. if (!match) {
  31551. return 0;
  31552. }
  31553. var _match$slice = match.slice(1),
  31554. year = _match$slice[0],
  31555. month = _match$slice[1],
  31556. day = _match$slice[2],
  31557. hour = _match$slice[3],
  31558. minute = _match$slice[4],
  31559. second = _match$slice[5];
  31560. 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);
  31561. };
  31562. var parseDate = function parseDate(str) {
  31563. // Date format without timezone according to ISO 8601
  31564. // YYY-MM-DDThh:mm:ss.ssssss
  31565. 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
  31566. // expressed by ending with 'Z'
  31567. if (dateRegex.test(str)) {
  31568. str += 'Z';
  31569. }
  31570. return Date.parse(str);
  31571. };
  31572. var parsers = {
  31573. /**
  31574. * Specifies the duration of the entire Media Presentation. Format is a duration string
  31575. * as specified in ISO 8601
  31576. *
  31577. * @param {string} value
  31578. * value of attribute as a string
  31579. * @return {number}
  31580. * The duration in seconds
  31581. */
  31582. mediaPresentationDuration: function mediaPresentationDuration(value) {
  31583. return parseDuration(value);
  31584. },
  31585. /**
  31586. * Specifies the Segment availability start time for all Segments referred to in this
  31587. * MPD. For a dynamic manifest, it specifies the anchor for the earliest availability
  31588. * time. Format is a date string as specified in ISO 8601
  31589. *
  31590. * @param {string} value
  31591. * value of attribute as a string
  31592. * @return {number}
  31593. * The date as seconds from unix epoch
  31594. */
  31595. availabilityStartTime: function availabilityStartTime(value) {
  31596. return parseDate(value) / 1000;
  31597. },
  31598. /**
  31599. * Specifies the smallest period between potential changes to the MPD. Format is a
  31600. * duration string as specified in ISO 8601
  31601. *
  31602. * @param {string} value
  31603. * value of attribute as a string
  31604. * @return {number}
  31605. * The duration in seconds
  31606. */
  31607. minimumUpdatePeriod: function minimumUpdatePeriod(value) {
  31608. return parseDuration(value);
  31609. },
  31610. /**
  31611. * Specifies the suggested presentation delay. Format is a
  31612. * duration string as specified in ISO 8601
  31613. *
  31614. * @param {string} value
  31615. * value of attribute as a string
  31616. * @return {number}
  31617. * The duration in seconds
  31618. */
  31619. suggestedPresentationDelay: function suggestedPresentationDelay(value) {
  31620. return parseDuration(value);
  31621. },
  31622. /**
  31623. * specifices the type of mpd. Can be either "static" or "dynamic"
  31624. *
  31625. * @param {string} value
  31626. * value of attribute as a string
  31627. *
  31628. * @return {string}
  31629. * The type as a string
  31630. */
  31631. type: function type(value) {
  31632. return value;
  31633. },
  31634. /**
  31635. * Specifies the duration of the smallest time shifting buffer for any Representation
  31636. * in the MPD. Format is a duration string as specified in ISO 8601
  31637. *
  31638. * @param {string} value
  31639. * value of attribute as a string
  31640. * @return {number}
  31641. * The duration in seconds
  31642. */
  31643. timeShiftBufferDepth: function timeShiftBufferDepth(value) {
  31644. return parseDuration(value);
  31645. },
  31646. /**
  31647. * Specifies the PeriodStart time of the Period relative to the availabilityStarttime.
  31648. * Format is a duration string as specified in ISO 8601
  31649. *
  31650. * @param {string} value
  31651. * value of attribute as a string
  31652. * @return {number}
  31653. * The duration in seconds
  31654. */
  31655. start: function start(value) {
  31656. return parseDuration(value);
  31657. },
  31658. /**
  31659. * Specifies the width of the visual presentation
  31660. *
  31661. * @param {string} value
  31662. * value of attribute as a string
  31663. * @return {number}
  31664. * The parsed width
  31665. */
  31666. width: function width(value) {
  31667. return parseInt(value, 10);
  31668. },
  31669. /**
  31670. * Specifies the height of the visual presentation
  31671. *
  31672. * @param {string} value
  31673. * value of attribute as a string
  31674. * @return {number}
  31675. * The parsed height
  31676. */
  31677. height: function height(value) {
  31678. return parseInt(value, 10);
  31679. },
  31680. /**
  31681. * Specifies the bitrate of the representation
  31682. *
  31683. * @param {string} value
  31684. * value of attribute as a string
  31685. * @return {number}
  31686. * The parsed bandwidth
  31687. */
  31688. bandwidth: function bandwidth(value) {
  31689. return parseInt(value, 10);
  31690. },
  31691. /**
  31692. * Specifies the frame rate of the representation
  31693. *
  31694. * @param {string} value
  31695. * value of attribute as a string
  31696. * @return {number}
  31697. * The parsed frame rate
  31698. */
  31699. frameRate: function frameRate(value) {
  31700. return parseDivisionValue(value);
  31701. },
  31702. /**
  31703. * Specifies the number of the first Media Segment in this Representation in the Period
  31704. *
  31705. * @param {string} value
  31706. * value of attribute as a string
  31707. * @return {number}
  31708. * The parsed number
  31709. */
  31710. startNumber: function startNumber(value) {
  31711. return parseInt(value, 10);
  31712. },
  31713. /**
  31714. * Specifies the timescale in units per seconds
  31715. *
  31716. * @param {string} value
  31717. * value of attribute as a string
  31718. * @return {number}
  31719. * The parsed timescale
  31720. */
  31721. timescale: function timescale(value) {
  31722. return parseInt(value, 10);
  31723. },
  31724. /**
  31725. * Specifies the presentationTimeOffset.
  31726. *
  31727. * @param {string} value
  31728. * value of the attribute as a string
  31729. *
  31730. * @return {number}
  31731. * The parsed presentationTimeOffset
  31732. */
  31733. presentationTimeOffset: function presentationTimeOffset(value) {
  31734. return parseInt(value, 10);
  31735. },
  31736. /**
  31737. * Specifies the constant approximate Segment duration
  31738. * NOTE: The <Period> element also contains an @duration attribute. This duration
  31739. * specifies the duration of the Period. This attribute is currently not
  31740. * supported by the rest of the parser, however we still check for it to prevent
  31741. * errors.
  31742. *
  31743. * @param {string} value
  31744. * value of attribute as a string
  31745. * @return {number}
  31746. * The parsed duration
  31747. */
  31748. duration: function duration(value) {
  31749. var parsedValue = parseInt(value, 10);
  31750. if (isNaN(parsedValue)) {
  31751. return parseDuration(value);
  31752. }
  31753. return parsedValue;
  31754. },
  31755. /**
  31756. * Specifies the Segment duration, in units of the value of the @timescale.
  31757. *
  31758. * @param {string} value
  31759. * value of attribute as a string
  31760. * @return {number}
  31761. * The parsed duration
  31762. */
  31763. d: function d(value) {
  31764. return parseInt(value, 10);
  31765. },
  31766. /**
  31767. * Specifies the MPD start time, in @timescale units, the first Segment in the series
  31768. * starts relative to the beginning of the Period
  31769. *
  31770. * @param {string} value
  31771. * value of attribute as a string
  31772. * @return {number}
  31773. * The parsed time
  31774. */
  31775. t: function t(value) {
  31776. return parseInt(value, 10);
  31777. },
  31778. /**
  31779. * Specifies the repeat count of the number of following contiguous Segments with the
  31780. * same duration expressed by the value of @d
  31781. *
  31782. * @param {string} value
  31783. * value of attribute as a string
  31784. * @return {number}
  31785. * The parsed number
  31786. */
  31787. r: function r(value) {
  31788. return parseInt(value, 10);
  31789. },
  31790. /**
  31791. * Default parser for all other attributes. Acts as a no-op and just returns the value
  31792. * as a string
  31793. *
  31794. * @param {string} value
  31795. * value of attribute as a string
  31796. * @return {string}
  31797. * Unparsed value
  31798. */
  31799. DEFAULT: function DEFAULT(value) {
  31800. return value;
  31801. }
  31802. };
  31803. /**
  31804. * Gets all the attributes and values of the provided node, parses attributes with known
  31805. * types, and returns an object with attribute names mapped to values.
  31806. *
  31807. * @param {Node} el
  31808. * The node to parse attributes from
  31809. * @return {Object}
  31810. * Object with all attributes of el parsed
  31811. */
  31812. var parseAttributes = function parseAttributes(el) {
  31813. if (!(el && el.attributes)) {
  31814. return {};
  31815. }
  31816. return from(el.attributes).reduce(function (a, e) {
  31817. var parseFn = parsers[e.name] || parsers.DEFAULT;
  31818. a[e.name] = parseFn(e.value);
  31819. return a;
  31820. }, {});
  31821. };
  31822. var keySystemsMap = {
  31823. 'urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b': 'org.w3.clearkey',
  31824. 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed': 'com.widevine.alpha',
  31825. 'urn:uuid:9a04f079-9840-4286-ab92-e65be0885f95': 'com.microsoft.playready',
  31826. 'urn:uuid:f239e769-efa3-4850-9c16-a903c6932efb': 'com.adobe.primetime'
  31827. };
  31828. /**
  31829. * Builds a list of urls that is the product of the reference urls and BaseURL values
  31830. *
  31831. * @param {string[]} referenceUrls
  31832. * List of reference urls to resolve to
  31833. * @param {Node[]} baseUrlElements
  31834. * List of BaseURL nodes from the mpd
  31835. * @return {string[]}
  31836. * List of resolved urls
  31837. */
  31838. var buildBaseUrls = function buildBaseUrls(referenceUrls, baseUrlElements) {
  31839. if (!baseUrlElements.length) {
  31840. return referenceUrls;
  31841. }
  31842. return flatten(referenceUrls.map(function (reference) {
  31843. return baseUrlElements.map(function (baseUrlElement) {
  31844. return resolveUrl$1(reference, getContent(baseUrlElement));
  31845. });
  31846. }));
  31847. };
  31848. /**
  31849. * Contains all Segment information for its containing AdaptationSet
  31850. *
  31851. * @typedef {Object} SegmentInformation
  31852. * @property {Object|undefined} template
  31853. * Contains the attributes for the SegmentTemplate node
  31854. * @property {Object[]|undefined} segmentTimeline
  31855. * Contains a list of atrributes for each S node within the SegmentTimeline node
  31856. * @property {Object|undefined} list
  31857. * Contains the attributes for the SegmentList node
  31858. * @property {Object|undefined} base
  31859. * Contains the attributes for the SegmentBase node
  31860. */
  31861. /**
  31862. * Returns all available Segment information contained within the AdaptationSet node
  31863. *
  31864. * @param {Node} adaptationSet
  31865. * The AdaptationSet node to get Segment information from
  31866. * @return {SegmentInformation}
  31867. * The Segment information contained within the provided AdaptationSet
  31868. */
  31869. var getSegmentInformation = function getSegmentInformation(adaptationSet) {
  31870. var segmentTemplate = findChildren(adaptationSet, 'SegmentTemplate')[0];
  31871. var segmentList = findChildren(adaptationSet, 'SegmentList')[0];
  31872. var segmentUrls = segmentList && findChildren(segmentList, 'SegmentURL').map(function (s) {
  31873. return merge({
  31874. tag: 'SegmentURL'
  31875. }, parseAttributes(s));
  31876. });
  31877. var segmentBase = findChildren(adaptationSet, 'SegmentBase')[0];
  31878. var segmentTimelineParentNode = segmentList || segmentTemplate;
  31879. var segmentTimeline = segmentTimelineParentNode && findChildren(segmentTimelineParentNode, 'SegmentTimeline')[0];
  31880. var segmentInitializationParentNode = segmentList || segmentBase || segmentTemplate;
  31881. var segmentInitialization = segmentInitializationParentNode && findChildren(segmentInitializationParentNode, 'Initialization')[0]; // SegmentTemplate is handled slightly differently, since it can have both
  31882. // @initialization and an <Initialization> node. @initialization can be templated,
  31883. // while the node can have a url and range specified. If the <SegmentTemplate> has
  31884. // both @initialization and an <Initialization> subelement we opt to override with
  31885. // the node, as this interaction is not defined in the spec.
  31886. var template = segmentTemplate && parseAttributes(segmentTemplate);
  31887. if (template && segmentInitialization) {
  31888. template.initialization = segmentInitialization && parseAttributes(segmentInitialization);
  31889. } else if (template && template.initialization) {
  31890. // If it is @initialization we convert it to an object since this is the format that
  31891. // later functions will rely on for the initialization segment. This is only valid
  31892. // for <SegmentTemplate>
  31893. template.initialization = {
  31894. sourceURL: template.initialization
  31895. };
  31896. }
  31897. var segmentInfo = {
  31898. template: template,
  31899. segmentTimeline: segmentTimeline && findChildren(segmentTimeline, 'S').map(function (s) {
  31900. return parseAttributes(s);
  31901. }),
  31902. list: segmentList && merge(parseAttributes(segmentList), {
  31903. segmentUrls: segmentUrls,
  31904. initialization: parseAttributes(segmentInitialization)
  31905. }),
  31906. base: segmentBase && merge(parseAttributes(segmentBase), {
  31907. initialization: parseAttributes(segmentInitialization)
  31908. })
  31909. };
  31910. Object.keys(segmentInfo).forEach(function (key) {
  31911. if (!segmentInfo[key]) {
  31912. delete segmentInfo[key];
  31913. }
  31914. });
  31915. return segmentInfo;
  31916. };
  31917. /**
  31918. * Contains Segment information and attributes needed to construct a Playlist object
  31919. * from a Representation
  31920. *
  31921. * @typedef {Object} RepresentationInformation
  31922. * @property {SegmentInformation} segmentInfo
  31923. * Segment information for this Representation
  31924. * @property {Object} attributes
  31925. * Inherited attributes for this Representation
  31926. */
  31927. /**
  31928. * Maps a Representation node to an object containing Segment information and attributes
  31929. *
  31930. * @name inheritBaseUrlsCallback
  31931. * @function
  31932. * @param {Node} representation
  31933. * Representation node from the mpd
  31934. * @return {RepresentationInformation}
  31935. * Representation information needed to construct a Playlist object
  31936. */
  31937. /**
  31938. * Returns a callback for Array.prototype.map for mapping Representation nodes to
  31939. * Segment information and attributes using inherited BaseURL nodes.
  31940. *
  31941. * @param {Object} adaptationSetAttributes
  31942. * Contains attributes inherited by the AdaptationSet
  31943. * @param {string[]} adaptationSetBaseUrls
  31944. * Contains list of resolved base urls inherited by the AdaptationSet
  31945. * @param {SegmentInformation} adaptationSetSegmentInfo
  31946. * Contains Segment information for the AdaptationSet
  31947. * @return {inheritBaseUrlsCallback}
  31948. * Callback map function
  31949. */
  31950. var inheritBaseUrls = function inheritBaseUrls(adaptationSetAttributes, adaptationSetBaseUrls, adaptationSetSegmentInfo) {
  31951. return function (representation) {
  31952. var repBaseUrlElements = findChildren(representation, 'BaseURL');
  31953. var repBaseUrls = buildBaseUrls(adaptationSetBaseUrls, repBaseUrlElements);
  31954. var attributes = merge(adaptationSetAttributes, parseAttributes(representation));
  31955. var representationSegmentInfo = getSegmentInformation(representation);
  31956. return repBaseUrls.map(function (baseUrl) {
  31957. return {
  31958. segmentInfo: merge(adaptationSetSegmentInfo, representationSegmentInfo),
  31959. attributes: merge(attributes, {
  31960. baseUrl: baseUrl
  31961. })
  31962. };
  31963. });
  31964. };
  31965. };
  31966. /**
  31967. * Tranforms a series of content protection nodes to
  31968. * an object containing pssh data by key system
  31969. *
  31970. * @param {Node[]} contentProtectionNodes
  31971. * Content protection nodes
  31972. * @return {Object}
  31973. * Object containing pssh data by key system
  31974. */
  31975. var generateKeySystemInformation = function generateKeySystemInformation(contentProtectionNodes) {
  31976. return contentProtectionNodes.reduce(function (acc, node) {
  31977. 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
  31978. // as a lowercase string it also mentions it should be treated as case-insensitive on input. Since the key system
  31979. // UUIDs in the keySystemsMap are hardcoded as lowercase in the codebase there isn't any reason not to do
  31980. // .toLowerCase() on the input UUID string from the manifest (at least I could not think of one).
  31981. if (attributes.schemeIdUri) {
  31982. attributes.schemeIdUri = attributes.schemeIdUri.toLowerCase();
  31983. }
  31984. var keySystem = keySystemsMap[attributes.schemeIdUri];
  31985. if (keySystem) {
  31986. acc[keySystem] = {
  31987. attributes: attributes
  31988. };
  31989. var psshNode = findChildren(node, 'cenc:pssh')[0];
  31990. if (psshNode) {
  31991. var pssh = getContent(psshNode);
  31992. acc[keySystem].pssh = pssh && decodeB64ToUint8Array(pssh);
  31993. }
  31994. }
  31995. return acc;
  31996. }, {});
  31997. }; // defined in ANSI_SCTE 214-1 2016
  31998. var parseCaptionServiceMetadata = function parseCaptionServiceMetadata(service) {
  31999. // 608 captions
  32000. if (service.schemeIdUri === 'urn:scte:dash:cc:cea-608:2015') {
  32001. var values = typeof service.value !== 'string' ? [] : service.value.split(';');
  32002. return values.map(function (value) {
  32003. var channel;
  32004. var language; // default language to value
  32005. language = value;
  32006. if (/^CC\d=/.test(value)) {
  32007. var _value$split = value.split('=');
  32008. channel = _value$split[0];
  32009. language = _value$split[1];
  32010. } else if (/^CC\d$/.test(value)) {
  32011. channel = value;
  32012. }
  32013. return {
  32014. channel: channel,
  32015. language: language
  32016. };
  32017. });
  32018. } else if (service.schemeIdUri === 'urn:scte:dash:cc:cea-708:2015') {
  32019. var _values = typeof service.value !== 'string' ? [] : service.value.split(';');
  32020. return _values.map(function (value) {
  32021. var flags = {
  32022. // service or channel number 1-63
  32023. 'channel': undefined,
  32024. // language is a 3ALPHA per ISO 639.2/B
  32025. // field is required
  32026. 'language': undefined,
  32027. // BIT 1/0 or ?
  32028. // default value is 1, meaning 16:9 aspect ratio, 0 is 4:3, ? is unknown
  32029. 'aspectRatio': 1,
  32030. // BIT 1/0
  32031. // easy reader flag indicated the text is tailed to the needs of beginning readers
  32032. // default 0, or off
  32033. 'easyReader': 0,
  32034. // BIT 1/0
  32035. // If 3d metadata is present (CEA-708.1) then 1
  32036. // default 0
  32037. '3D': 0
  32038. };
  32039. if (/=/.test(value)) {
  32040. var _value$split2 = value.split('='),
  32041. channel = _value$split2[0],
  32042. _value$split2$ = _value$split2[1],
  32043. opts = _value$split2$ === void 0 ? '' : _value$split2$;
  32044. flags.channel = channel;
  32045. flags.language = value;
  32046. opts.split(',').forEach(function (opt) {
  32047. var _opt$split = opt.split(':'),
  32048. name = _opt$split[0],
  32049. val = _opt$split[1];
  32050. if (name === 'lang') {
  32051. flags.language = val; // er for easyReadery
  32052. } else if (name === 'er') {
  32053. flags.easyReader = Number(val); // war for wide aspect ratio
  32054. } else if (name === 'war') {
  32055. flags.aspectRatio = Number(val);
  32056. } else if (name === '3D') {
  32057. flags['3D'] = Number(val);
  32058. }
  32059. });
  32060. } else {
  32061. flags.language = value;
  32062. }
  32063. if (flags.channel) {
  32064. flags.channel = 'SERVICE' + flags.channel;
  32065. }
  32066. return flags;
  32067. });
  32068. }
  32069. };
  32070. /**
  32071. * Maps an AdaptationSet node to a list of Representation information objects
  32072. *
  32073. * @name toRepresentationsCallback
  32074. * @function
  32075. * @param {Node} adaptationSet
  32076. * AdaptationSet node from the mpd
  32077. * @return {RepresentationInformation[]}
  32078. * List of objects containing Representaion information
  32079. */
  32080. /**
  32081. * Returns a callback for Array.prototype.map for mapping AdaptationSet nodes to a list of
  32082. * Representation information objects
  32083. *
  32084. * @param {Object} periodAttributes
  32085. * Contains attributes inherited by the Period
  32086. * @param {string[]} periodBaseUrls
  32087. * Contains list of resolved base urls inherited by the Period
  32088. * @param {string[]} periodSegmentInfo
  32089. * Contains Segment Information at the period level
  32090. * @return {toRepresentationsCallback}
  32091. * Callback map function
  32092. */
  32093. var toRepresentations = function toRepresentations(periodAttributes, periodBaseUrls, periodSegmentInfo) {
  32094. return function (adaptationSet) {
  32095. var adaptationSetAttributes = parseAttributes(adaptationSet);
  32096. var adaptationSetBaseUrls = buildBaseUrls(periodBaseUrls, findChildren(adaptationSet, 'BaseURL'));
  32097. var role = findChildren(adaptationSet, 'Role')[0];
  32098. var roleAttributes = {
  32099. role: parseAttributes(role)
  32100. };
  32101. var attrs = merge(periodAttributes, adaptationSetAttributes, roleAttributes);
  32102. var accessibility = findChildren(adaptationSet, 'Accessibility')[0];
  32103. var captionServices = parseCaptionServiceMetadata(parseAttributes(accessibility));
  32104. if (captionServices) {
  32105. attrs = merge(attrs, {
  32106. captionServices: captionServices
  32107. });
  32108. }
  32109. var label = findChildren(adaptationSet, 'Label')[0];
  32110. if (label && label.childNodes.length) {
  32111. var labelVal = label.childNodes[0].nodeValue.trim();
  32112. attrs = merge(attrs, {
  32113. label: labelVal
  32114. });
  32115. }
  32116. var contentProtection = generateKeySystemInformation(findChildren(adaptationSet, 'ContentProtection'));
  32117. if (Object.keys(contentProtection).length) {
  32118. attrs = merge(attrs, {
  32119. contentProtection: contentProtection
  32120. });
  32121. }
  32122. var segmentInfo = getSegmentInformation(adaptationSet);
  32123. var representations = findChildren(adaptationSet, 'Representation');
  32124. var adaptationSetSegmentInfo = merge(periodSegmentInfo, segmentInfo);
  32125. return flatten(representations.map(inheritBaseUrls(attrs, adaptationSetBaseUrls, adaptationSetSegmentInfo)));
  32126. };
  32127. };
  32128. /**
  32129. * Contains all period information for mapping nodes onto adaptation sets.
  32130. *
  32131. * @typedef {Object} PeriodInformation
  32132. * @property {Node} period.node
  32133. * Period node from the mpd
  32134. * @property {Object} period.attributes
  32135. * Parsed period attributes from node plus any added
  32136. */
  32137. /**
  32138. * Maps a PeriodInformation object to a list of Representation information objects for all
  32139. * AdaptationSet nodes contained within the Period.
  32140. *
  32141. * @name toAdaptationSetsCallback
  32142. * @function
  32143. * @param {PeriodInformation} period
  32144. * Period object containing necessary period information
  32145. * @param {number} periodStart
  32146. * Start time of the Period within the mpd
  32147. * @return {RepresentationInformation[]}
  32148. * List of objects containing Representaion information
  32149. */
  32150. /**
  32151. * Returns a callback for Array.prototype.map for mapping Period nodes to a list of
  32152. * Representation information objects
  32153. *
  32154. * @param {Object} mpdAttributes
  32155. * Contains attributes inherited by the mpd
  32156. * @param {string[]} mpdBaseUrls
  32157. * Contains list of resolved base urls inherited by the mpd
  32158. * @return {toAdaptationSetsCallback}
  32159. * Callback map function
  32160. */
  32161. var toAdaptationSets = function toAdaptationSets(mpdAttributes, mpdBaseUrls) {
  32162. return function (period, index) {
  32163. var periodBaseUrls = buildBaseUrls(mpdBaseUrls, findChildren(period.node, 'BaseURL'));
  32164. var periodAttributes = merge(mpdAttributes, {
  32165. periodStart: period.attributes.start
  32166. });
  32167. if (typeof period.attributes.duration === 'number') {
  32168. periodAttributes.periodDuration = period.attributes.duration;
  32169. }
  32170. var adaptationSets = findChildren(period.node, 'AdaptationSet');
  32171. var periodSegmentInfo = getSegmentInformation(period.node);
  32172. return flatten(adaptationSets.map(toRepresentations(periodAttributes, periodBaseUrls, periodSegmentInfo)));
  32173. };
  32174. };
  32175. /**
  32176. * Gets Period@start property for a given period.
  32177. *
  32178. * @param {Object} options
  32179. * Options object
  32180. * @param {Object} options.attributes
  32181. * Period attributes
  32182. * @param {Object} [options.priorPeriodAttributes]
  32183. * Prior period attributes (if prior period is available)
  32184. * @param {string} options.mpdType
  32185. * The MPD@type these periods came from
  32186. * @return {number|null}
  32187. * The period start, or null if it's an early available period or error
  32188. */
  32189. var getPeriodStart = function getPeriodStart(_ref) {
  32190. var attributes = _ref.attributes,
  32191. priorPeriodAttributes = _ref.priorPeriodAttributes,
  32192. mpdType = _ref.mpdType; // Summary of period start time calculation from DASH spec section 5.3.2.1
  32193. //
  32194. // A period's start is the first period's start + time elapsed after playing all
  32195. // prior periods to this one. Periods continue one after the other in time (without
  32196. // gaps) until the end of the presentation.
  32197. //
  32198. // The value of Period@start should be:
  32199. // 1. if Period@start is present: value of Period@start
  32200. // 2. if previous period exists and it has @duration: previous Period@start +
  32201. // previous Period@duration
  32202. // 3. if this is first period and MPD@type is 'static': 0
  32203. // 4. in all other cases, consider the period an "early available period" (note: not
  32204. // currently supported)
  32205. // (1)
  32206. if (typeof attributes.start === 'number') {
  32207. return attributes.start;
  32208. } // (2)
  32209. if (priorPeriodAttributes && typeof priorPeriodAttributes.start === 'number' && typeof priorPeriodAttributes.duration === 'number') {
  32210. return priorPeriodAttributes.start + priorPeriodAttributes.duration;
  32211. } // (3)
  32212. if (!priorPeriodAttributes && mpdType === 'static') {
  32213. return 0;
  32214. } // (4)
  32215. // There is currently no logic for calculating the Period@start value if there is
  32216. // no Period@start or prior Period@start and Period@duration available. This is not made
  32217. // explicit by the DASH interop guidelines or the DASH spec, however, since there's
  32218. // nothing about any other resolution strategies, it's implied. Thus, this case should
  32219. // be considered an early available period, or error, and null should suffice for both
  32220. // of those cases.
  32221. return null;
  32222. };
  32223. /**
  32224. * Traverses the mpd xml tree to generate a list of Representation information objects
  32225. * that have inherited attributes from parent nodes
  32226. *
  32227. * @param {Node} mpd
  32228. * The root node of the mpd
  32229. * @param {Object} options
  32230. * Available options for inheritAttributes
  32231. * @param {string} options.manifestUri
  32232. * The uri source of the mpd
  32233. * @param {number} options.NOW
  32234. * Current time per DASH IOP. Default is current time in ms since epoch
  32235. * @param {number} options.clientOffset
  32236. * Client time difference from NOW (in milliseconds)
  32237. * @return {RepresentationInformation[]}
  32238. * List of objects containing Representation information
  32239. */
  32240. var inheritAttributes = function inheritAttributes(mpd, options) {
  32241. if (options === void 0) {
  32242. options = {};
  32243. }
  32244. var _options = options,
  32245. _options$manifestUri = _options.manifestUri,
  32246. manifestUri = _options$manifestUri === void 0 ? '' : _options$manifestUri,
  32247. _options$NOW = _options.NOW,
  32248. NOW = _options$NOW === void 0 ? Date.now() : _options$NOW,
  32249. _options$clientOffset = _options.clientOffset,
  32250. clientOffset = _options$clientOffset === void 0 ? 0 : _options$clientOffset;
  32251. var periodNodes = findChildren(mpd, 'Period');
  32252. if (!periodNodes.length) {
  32253. throw new Error(errors.INVALID_NUMBER_OF_PERIOD);
  32254. }
  32255. var locations = findChildren(mpd, 'Location');
  32256. var mpdAttributes = parseAttributes(mpd);
  32257. var mpdBaseUrls = buildBaseUrls([manifestUri], findChildren(mpd, 'BaseURL')); // See DASH spec section 5.3.1.2, Semantics of MPD element. Default type to 'static'.
  32258. mpdAttributes.type = mpdAttributes.type || 'static';
  32259. mpdAttributes.sourceDuration = mpdAttributes.mediaPresentationDuration || 0;
  32260. mpdAttributes.NOW = NOW;
  32261. mpdAttributes.clientOffset = clientOffset;
  32262. if (locations.length) {
  32263. mpdAttributes.locations = locations.map(getContent);
  32264. }
  32265. var periods = []; // Since toAdaptationSets acts on individual periods right now, the simplest approach to
  32266. // adding properties that require looking at prior periods is to parse attributes and add
  32267. // missing ones before toAdaptationSets is called. If more such properties are added, it
  32268. // may be better to refactor toAdaptationSets.
  32269. periodNodes.forEach(function (node, index) {
  32270. var attributes = parseAttributes(node); // Use the last modified prior period, as it may contain added information necessary
  32271. // for this period.
  32272. var priorPeriod = periods[index - 1];
  32273. attributes.start = getPeriodStart({
  32274. attributes: attributes,
  32275. priorPeriodAttributes: priorPeriod ? priorPeriod.attributes : null,
  32276. mpdType: mpdAttributes.type
  32277. });
  32278. periods.push({
  32279. node: node,
  32280. attributes: attributes
  32281. });
  32282. });
  32283. return {
  32284. locations: mpdAttributes.locations,
  32285. representationInfo: flatten(periods.map(toAdaptationSets(mpdAttributes, mpdBaseUrls)))
  32286. };
  32287. };
  32288. var stringToMpdXml = function stringToMpdXml(manifestString) {
  32289. if (manifestString === '') {
  32290. throw new Error(errors.DASH_EMPTY_MANIFEST);
  32291. }
  32292. var parser = new DOMParser();
  32293. var xml;
  32294. var mpd;
  32295. try {
  32296. xml = parser.parseFromString(manifestString, 'application/xml');
  32297. mpd = xml && xml.documentElement.tagName === 'MPD' ? xml.documentElement : null;
  32298. } catch (e) {// ie 11 throwsw on invalid xml
  32299. }
  32300. if (!mpd || mpd && mpd.getElementsByTagName('parsererror').length > 0) {
  32301. throw new Error(errors.DASH_INVALID_XML);
  32302. }
  32303. return mpd;
  32304. };
  32305. /**
  32306. * Parses the manifest for a UTCTiming node, returning the nodes attributes if found
  32307. *
  32308. * @param {string} mpd
  32309. * XML string of the MPD manifest
  32310. * @return {Object|null}
  32311. * Attributes of UTCTiming node specified in the manifest. Null if none found
  32312. */
  32313. var parseUTCTimingScheme = function parseUTCTimingScheme(mpd) {
  32314. var UTCTimingNode = findChildren(mpd, 'UTCTiming')[0];
  32315. if (!UTCTimingNode) {
  32316. return null;
  32317. }
  32318. var attributes = parseAttributes(UTCTimingNode);
  32319. switch (attributes.schemeIdUri) {
  32320. case 'urn:mpeg:dash:utc:http-head:2014':
  32321. case 'urn:mpeg:dash:utc:http-head:2012':
  32322. attributes.method = 'HEAD';
  32323. break;
  32324. case 'urn:mpeg:dash:utc:http-xsdate:2014':
  32325. case 'urn:mpeg:dash:utc:http-iso:2014':
  32326. case 'urn:mpeg:dash:utc:http-xsdate:2012':
  32327. case 'urn:mpeg:dash:utc:http-iso:2012':
  32328. attributes.method = 'GET';
  32329. break;
  32330. case 'urn:mpeg:dash:utc:direct:2014':
  32331. case 'urn:mpeg:dash:utc:direct:2012':
  32332. attributes.method = 'DIRECT';
  32333. attributes.value = Date.parse(attributes.value);
  32334. break;
  32335. case 'urn:mpeg:dash:utc:http-ntp:2014':
  32336. case 'urn:mpeg:dash:utc:ntp:2014':
  32337. case 'urn:mpeg:dash:utc:sntp:2014':
  32338. default:
  32339. throw new Error(errors.UNSUPPORTED_UTC_TIMING_SCHEME);
  32340. }
  32341. return attributes;
  32342. };
  32343. /*
  32344. * Given a DASH manifest string and options, parses the DASH manifest into an object in the
  32345. * form outputed by m3u8-parser and accepted by videojs/http-streaming.
  32346. *
  32347. * For live DASH manifests, if `previousManifest` is provided in options, then the newly
  32348. * parsed DASH manifest will have its media sequence and discontinuity sequence values
  32349. * updated to reflect its position relative to the prior manifest.
  32350. *
  32351. * @param {string} manifestString - the DASH manifest as a string
  32352. * @param {options} [options] - any options
  32353. *
  32354. * @return {Object} the manifest object
  32355. */
  32356. var parse = function parse(manifestString, options) {
  32357. if (options === void 0) {
  32358. options = {};
  32359. }
  32360. var parsedManifestInfo = inheritAttributes(stringToMpdXml(manifestString), options);
  32361. var playlists = toPlaylists(parsedManifestInfo.representationInfo);
  32362. return toM3u8({
  32363. dashPlaylists: playlists,
  32364. locations: parsedManifestInfo.locations,
  32365. sidxMapping: options.sidxMapping,
  32366. previousManifest: options.previousManifest
  32367. });
  32368. };
  32369. /**
  32370. * Parses the manifest for a UTCTiming node, returning the nodes attributes if found
  32371. *
  32372. * @param {string} manifestString
  32373. * XML string of the MPD manifest
  32374. * @return {Object|null}
  32375. * Attributes of UTCTiming node specified in the manifest. Null if none found
  32376. */
  32377. var parseUTCTiming = function parseUTCTiming(manifestString) {
  32378. return parseUTCTimingScheme(stringToMpdXml(manifestString));
  32379. };
  32380. var MAX_UINT32 = Math.pow(2, 32);
  32381. var getUint64$1 = function getUint64(uint8) {
  32382. var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
  32383. var value;
  32384. if (dv.getBigUint64) {
  32385. value = dv.getBigUint64(0);
  32386. if (value < Number.MAX_SAFE_INTEGER) {
  32387. return Number(value);
  32388. }
  32389. return value;
  32390. }
  32391. return dv.getUint32(0) * MAX_UINT32 + dv.getUint32(4);
  32392. };
  32393. var numbers = {
  32394. getUint64: getUint64$1,
  32395. MAX_UINT32: MAX_UINT32
  32396. };
  32397. var getUint64 = numbers.getUint64;
  32398. var parseSidx = function parseSidx(data) {
  32399. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  32400. result = {
  32401. version: data[0],
  32402. flags: new Uint8Array(data.subarray(1, 4)),
  32403. references: [],
  32404. referenceId: view.getUint32(4),
  32405. timescale: view.getUint32(8)
  32406. },
  32407. i = 12;
  32408. if (result.version === 0) {
  32409. result.earliestPresentationTime = view.getUint32(i);
  32410. result.firstOffset = view.getUint32(i + 4);
  32411. i += 8;
  32412. } else {
  32413. // read 64 bits
  32414. result.earliestPresentationTime = getUint64(data.subarray(i));
  32415. result.firstOffset = getUint64(data.subarray(i + 8));
  32416. i += 16;
  32417. }
  32418. i += 2; // reserved
  32419. var referenceCount = view.getUint16(i);
  32420. i += 2; // start of references
  32421. for (; referenceCount > 0; i += 12, referenceCount--) {
  32422. result.references.push({
  32423. referenceType: (data[i] & 0x80) >>> 7,
  32424. referencedSize: view.getUint32(i) & 0x7FFFFFFF,
  32425. subsegmentDuration: view.getUint32(i + 4),
  32426. startsWithSap: !!(data[i + 8] & 0x80),
  32427. sapType: (data[i + 8] & 0x70) >>> 4,
  32428. sapDeltaTime: view.getUint32(i + 8) & 0x0FFFFFFF
  32429. });
  32430. }
  32431. return result;
  32432. };
  32433. var parseSidx_1 = parseSidx;
  32434. var ID3 = toUint8([0x49, 0x44, 0x33]);
  32435. var getId3Size = function getId3Size(bytes, offset) {
  32436. if (offset === void 0) {
  32437. offset = 0;
  32438. }
  32439. bytes = toUint8(bytes);
  32440. var flags = bytes[offset + 5];
  32441. var returnSize = bytes[offset + 6] << 21 | bytes[offset + 7] << 14 | bytes[offset + 8] << 7 | bytes[offset + 9];
  32442. var footerPresent = (flags & 16) >> 4;
  32443. if (footerPresent) {
  32444. return returnSize + 20;
  32445. }
  32446. return returnSize + 10;
  32447. };
  32448. var getId3Offset = function getId3Offset(bytes, offset) {
  32449. if (offset === void 0) {
  32450. offset = 0;
  32451. }
  32452. bytes = toUint8(bytes);
  32453. if (bytes.length - offset < 10 || !bytesMatch(bytes, ID3, {
  32454. offset: offset
  32455. })) {
  32456. return offset;
  32457. }
  32458. offset += getId3Size(bytes, offset); // recursive check for id3 tags as some files
  32459. // have multiple ID3 tag sections even though
  32460. // they should not.
  32461. return getId3Offset(bytes, offset);
  32462. };
  32463. var normalizePath$1 = function normalizePath(path) {
  32464. if (typeof path === 'string') {
  32465. return stringToBytes(path);
  32466. }
  32467. if (typeof path === 'number') {
  32468. return path;
  32469. }
  32470. return path;
  32471. };
  32472. var normalizePaths$1 = function normalizePaths(paths) {
  32473. if (!Array.isArray(paths)) {
  32474. return [normalizePath$1(paths)];
  32475. }
  32476. return paths.map(function (p) {
  32477. return normalizePath$1(p);
  32478. });
  32479. };
  32480. /**
  32481. * find any number of boxes by name given a path to it in an iso bmff
  32482. * such as mp4.
  32483. *
  32484. * @param {TypedArray} bytes
  32485. * bytes for the iso bmff to search for boxes in
  32486. *
  32487. * @param {Uint8Array[]|string[]|string|Uint8Array} name
  32488. * An array of paths or a single path representing the name
  32489. * of boxes to search through in bytes. Paths may be
  32490. * uint8 (character codes) or strings.
  32491. *
  32492. * @param {boolean} [complete=false]
  32493. * Should we search only for complete boxes on the final path.
  32494. * This is very useful when you do not want to get back partial boxes
  32495. * in the case of streaming files.
  32496. *
  32497. * @return {Uint8Array[]}
  32498. * An array of the end paths that we found.
  32499. */
  32500. var findBox = function findBox(bytes, paths, complete) {
  32501. if (complete === void 0) {
  32502. complete = false;
  32503. }
  32504. paths = normalizePaths$1(paths);
  32505. bytes = toUint8(bytes);
  32506. var results = [];
  32507. if (!paths.length) {
  32508. // short-circuit the search for empty paths
  32509. return results;
  32510. }
  32511. var i = 0;
  32512. while (i < bytes.length) {
  32513. var size = (bytes[i] << 24 | bytes[i + 1] << 16 | bytes[i + 2] << 8 | bytes[i + 3]) >>> 0;
  32514. var type = bytes.subarray(i + 4, i + 8); // invalid box format.
  32515. if (size === 0) {
  32516. break;
  32517. }
  32518. var end = i + size;
  32519. if (end > bytes.length) {
  32520. // this box is bigger than the number of bytes we have
  32521. // and complete is set, we cannot find any more boxes.
  32522. if (complete) {
  32523. break;
  32524. }
  32525. end = bytes.length;
  32526. }
  32527. var data = bytes.subarray(i + 8, end);
  32528. if (bytesMatch(type, paths[0])) {
  32529. if (paths.length === 1) {
  32530. // this is the end of the path and we've found the box we were
  32531. // looking for
  32532. results.push(data);
  32533. } else {
  32534. // recursively search for the next box along the path
  32535. results.push.apply(results, findBox(data, paths.slice(1), complete));
  32536. }
  32537. }
  32538. i = end;
  32539. } // we've finished searching all of bytes
  32540. return results;
  32541. };
  32542. // https://matroska-org.github.io/libebml/specs.html
  32543. // https://www.matroska.org/technical/elements.html
  32544. // https://www.webmproject.org/docs/container/
  32545. var EBML_TAGS = {
  32546. EBML: toUint8([0x1A, 0x45, 0xDF, 0xA3]),
  32547. DocType: toUint8([0x42, 0x82]),
  32548. Segment: toUint8([0x18, 0x53, 0x80, 0x67]),
  32549. SegmentInfo: toUint8([0x15, 0x49, 0xA9, 0x66]),
  32550. Tracks: toUint8([0x16, 0x54, 0xAE, 0x6B]),
  32551. Track: toUint8([0xAE]),
  32552. TrackNumber: toUint8([0xd7]),
  32553. DefaultDuration: toUint8([0x23, 0xe3, 0x83]),
  32554. TrackEntry: toUint8([0xAE]),
  32555. TrackType: toUint8([0x83]),
  32556. FlagDefault: toUint8([0x88]),
  32557. CodecID: toUint8([0x86]),
  32558. CodecPrivate: toUint8([0x63, 0xA2]),
  32559. VideoTrack: toUint8([0xe0]),
  32560. AudioTrack: toUint8([0xe1]),
  32561. // Not used yet, but will be used for live webm/mkv
  32562. // see https://www.matroska.org/technical/basics.html#block-structure
  32563. // see https://www.matroska.org/technical/basics.html#simpleblock-structure
  32564. Cluster: toUint8([0x1F, 0x43, 0xB6, 0x75]),
  32565. Timestamp: toUint8([0xE7]),
  32566. TimestampScale: toUint8([0x2A, 0xD7, 0xB1]),
  32567. BlockGroup: toUint8([0xA0]),
  32568. BlockDuration: toUint8([0x9B]),
  32569. Block: toUint8([0xA1]),
  32570. SimpleBlock: toUint8([0xA3])
  32571. };
  32572. /**
  32573. * This is a simple table to determine the length
  32574. * of things in ebml. The length is one based (starts at 1,
  32575. * rather than zero) and for every zero bit before a one bit
  32576. * we add one to length. We also need this table because in some
  32577. * case we have to xor all the length bits from another value.
  32578. */
  32579. var LENGTH_TABLE = [128, 64, 32, 16, 8, 4, 2, 1];
  32580. var getLength = function getLength(_byte) {
  32581. var len = 1;
  32582. for (var i = 0; i < LENGTH_TABLE.length; i++) {
  32583. if (_byte & LENGTH_TABLE[i]) {
  32584. break;
  32585. }
  32586. len++;
  32587. }
  32588. return len;
  32589. }; // length in ebml is stored in the first 4 to 8 bits
  32590. // of the first byte. 4 for the id length and 8 for the
  32591. // data size length. Length is measured by converting the number to binary
  32592. // then 1 + the number of zeros before a 1 is encountered starting
  32593. // from the left.
  32594. var getvint = function getvint(bytes, offset, removeLength, signed) {
  32595. if (removeLength === void 0) {
  32596. removeLength = true;
  32597. }
  32598. if (signed === void 0) {
  32599. signed = false;
  32600. }
  32601. var length = getLength(bytes[offset]);
  32602. var valueBytes = bytes.subarray(offset, offset + length); // NOTE that we do **not** subarray here because we need to copy these bytes
  32603. // as they will be modified below to remove the dataSizeLen bits and we do not
  32604. // want to modify the original data. normally we could just call slice on
  32605. // uint8array but ie 11 does not support that...
  32606. if (removeLength) {
  32607. valueBytes = Array.prototype.slice.call(bytes, offset, offset + length);
  32608. valueBytes[0] ^= LENGTH_TABLE[length - 1];
  32609. }
  32610. return {
  32611. length: length,
  32612. value: bytesToNumber(valueBytes, {
  32613. signed: signed
  32614. }),
  32615. bytes: valueBytes
  32616. };
  32617. };
  32618. var normalizePath = function normalizePath(path) {
  32619. if (typeof path === 'string') {
  32620. return path.match(/.{1,2}/g).map(function (p) {
  32621. return normalizePath(p);
  32622. });
  32623. }
  32624. if (typeof path === 'number') {
  32625. return numberToBytes(path);
  32626. }
  32627. return path;
  32628. };
  32629. var normalizePaths = function normalizePaths(paths) {
  32630. if (!Array.isArray(paths)) {
  32631. return [normalizePath(paths)];
  32632. }
  32633. return paths.map(function (p) {
  32634. return normalizePath(p);
  32635. });
  32636. };
  32637. var getInfinityDataSize = function getInfinityDataSize(id, bytes, offset) {
  32638. if (offset >= bytes.length) {
  32639. return bytes.length;
  32640. }
  32641. var innerid = getvint(bytes, offset, false);
  32642. if (bytesMatch(id.bytes, innerid.bytes)) {
  32643. return offset;
  32644. }
  32645. var dataHeader = getvint(bytes, offset + innerid.length);
  32646. return getInfinityDataSize(id, bytes, offset + dataHeader.length + dataHeader.value + innerid.length);
  32647. };
  32648. /**
  32649. * Notes on the EBLM format.
  32650. *
  32651. * EBLM uses "vints" tags. Every vint tag contains
  32652. * two parts
  32653. *
  32654. * 1. The length from the first byte. You get this by
  32655. * converting the byte to binary and counting the zeros
  32656. * before a 1. Then you add 1 to that. Examples
  32657. * 00011111 = length 4 because there are 3 zeros before a 1.
  32658. * 00100000 = length 3 because there are 2 zeros before a 1.
  32659. * 00000011 = length 7 because there are 6 zeros before a 1.
  32660. *
  32661. * 2. The bits used for length are removed from the first byte
  32662. * Then all the bytes are merged into a value. NOTE: this
  32663. * is not the case for id ebml tags as there id includes
  32664. * length bits.
  32665. *
  32666. */
  32667. var findEbml = function findEbml(bytes, paths) {
  32668. paths = normalizePaths(paths);
  32669. bytes = toUint8(bytes);
  32670. var results = [];
  32671. if (!paths.length) {
  32672. return results;
  32673. }
  32674. var i = 0;
  32675. while (i < bytes.length) {
  32676. var id = getvint(bytes, i, false);
  32677. var dataHeader = getvint(bytes, i + id.length);
  32678. var dataStart = i + id.length + dataHeader.length; // dataSize is unknown or this is a live stream
  32679. if (dataHeader.value === 0x7f) {
  32680. dataHeader.value = getInfinityDataSize(id, bytes, dataStart);
  32681. if (dataHeader.value !== bytes.length) {
  32682. dataHeader.value -= dataStart;
  32683. }
  32684. }
  32685. var dataEnd = dataStart + dataHeader.value > bytes.length ? bytes.length : dataStart + dataHeader.value;
  32686. var data = bytes.subarray(dataStart, dataEnd);
  32687. if (bytesMatch(paths[0], id.bytes)) {
  32688. if (paths.length === 1) {
  32689. // this is the end of the paths and we've found the tag we were
  32690. // looking for
  32691. results.push(data);
  32692. } else {
  32693. // recursively search for the next tag inside of the data
  32694. // of this one
  32695. results = results.concat(findEbml(data, paths.slice(1)));
  32696. }
  32697. }
  32698. var totalLength = id.length + dataHeader.length + data.length; // move past this tag entirely, we are not looking for it
  32699. i += totalLength;
  32700. }
  32701. return results;
  32702. }; // see https://www.matroska.org/technical/basics.html#block-structure
  32703. var NAL_TYPE_ONE = toUint8([0x00, 0x00, 0x00, 0x01]);
  32704. var NAL_TYPE_TWO = toUint8([0x00, 0x00, 0x01]);
  32705. var EMULATION_PREVENTION = toUint8([0x00, 0x00, 0x03]);
  32706. /**
  32707. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  32708. * Sequence Payload"
  32709. *
  32710. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  32711. * unit
  32712. * @return {Uint8Array} the RBSP without any Emulation
  32713. * Prevention Bytes
  32714. */
  32715. var discardEmulationPreventionBytes = function discardEmulationPreventionBytes(bytes) {
  32716. var positions = [];
  32717. var i = 1; // Find all `Emulation Prevention Bytes`
  32718. while (i < bytes.length - 2) {
  32719. if (bytesMatch(bytes.subarray(i, i + 3), EMULATION_PREVENTION)) {
  32720. positions.push(i + 2);
  32721. i++;
  32722. }
  32723. i++;
  32724. } // If no Emulation Prevention Bytes were found just return the original
  32725. // array
  32726. if (positions.length === 0) {
  32727. return bytes;
  32728. } // Create a new array to hold the NAL unit data
  32729. var newLength = bytes.length - positions.length;
  32730. var newData = new Uint8Array(newLength);
  32731. var sourceIndex = 0;
  32732. for (i = 0; i < newLength; sourceIndex++, i++) {
  32733. if (sourceIndex === positions[0]) {
  32734. // Skip this byte
  32735. sourceIndex++; // Remove this position index
  32736. positions.shift();
  32737. }
  32738. newData[i] = bytes[sourceIndex];
  32739. }
  32740. return newData;
  32741. };
  32742. var findNal = function findNal(bytes, dataType, types, nalLimit) {
  32743. if (nalLimit === void 0) {
  32744. nalLimit = Infinity;
  32745. }
  32746. bytes = toUint8(bytes);
  32747. types = [].concat(types);
  32748. var i = 0;
  32749. var nalStart;
  32750. var nalsFound = 0; // keep searching until:
  32751. // we reach the end of bytes
  32752. // we reach the maximum number of nals they want to seach
  32753. // NOTE: that we disregard nalLimit when we have found the start
  32754. // of the nal we want so that we can find the end of the nal we want.
  32755. while (i < bytes.length && (nalsFound < nalLimit || nalStart)) {
  32756. var nalOffset = void 0;
  32757. if (bytesMatch(bytes.subarray(i), NAL_TYPE_ONE)) {
  32758. nalOffset = 4;
  32759. } else if (bytesMatch(bytes.subarray(i), NAL_TYPE_TWO)) {
  32760. nalOffset = 3;
  32761. } // we are unsynced,
  32762. // find the next nal unit
  32763. if (!nalOffset) {
  32764. i++;
  32765. continue;
  32766. }
  32767. nalsFound++;
  32768. if (nalStart) {
  32769. return discardEmulationPreventionBytes(bytes.subarray(nalStart, i));
  32770. }
  32771. var nalType = void 0;
  32772. if (dataType === 'h264') {
  32773. nalType = bytes[i + nalOffset] & 0x1f;
  32774. } else if (dataType === 'h265') {
  32775. nalType = bytes[i + nalOffset] >> 1 & 0x3f;
  32776. }
  32777. if (types.indexOf(nalType) !== -1) {
  32778. nalStart = i + nalOffset;
  32779. } // nal header is 1 length for h264, and 2 for h265
  32780. i += nalOffset + (dataType === 'h264' ? 1 : 2);
  32781. }
  32782. return bytes.subarray(0, 0);
  32783. };
  32784. var findH264Nal = function findH264Nal(bytes, type, nalLimit) {
  32785. return findNal(bytes, 'h264', type, nalLimit);
  32786. };
  32787. var findH265Nal = function findH265Nal(bytes, type, nalLimit) {
  32788. return findNal(bytes, 'h265', type, nalLimit);
  32789. };
  32790. var CONSTANTS = {
  32791. // "webm" string literal in hex
  32792. 'webm': toUint8([0x77, 0x65, 0x62, 0x6d]),
  32793. // "matroska" string literal in hex
  32794. 'matroska': toUint8([0x6d, 0x61, 0x74, 0x72, 0x6f, 0x73, 0x6b, 0x61]),
  32795. // "fLaC" string literal in hex
  32796. 'flac': toUint8([0x66, 0x4c, 0x61, 0x43]),
  32797. // "OggS" string literal in hex
  32798. 'ogg': toUint8([0x4f, 0x67, 0x67, 0x53]),
  32799. // ac-3 sync byte, also works for ec-3 as that is simply a codec
  32800. // of ac-3
  32801. 'ac3': toUint8([0x0b, 0x77]),
  32802. // "RIFF" string literal in hex used for wav and avi
  32803. 'riff': toUint8([0x52, 0x49, 0x46, 0x46]),
  32804. // "AVI" string literal in hex
  32805. 'avi': toUint8([0x41, 0x56, 0x49]),
  32806. // "WAVE" string literal in hex
  32807. 'wav': toUint8([0x57, 0x41, 0x56, 0x45]),
  32808. // "ftyp3g" string literal in hex
  32809. '3gp': toUint8([0x66, 0x74, 0x79, 0x70, 0x33, 0x67]),
  32810. // "ftyp" string literal in hex
  32811. 'mp4': toUint8([0x66, 0x74, 0x79, 0x70]),
  32812. // "styp" string literal in hex
  32813. 'fmp4': toUint8([0x73, 0x74, 0x79, 0x70]),
  32814. // "ftypqt" string literal in hex
  32815. 'mov': toUint8([0x66, 0x74, 0x79, 0x70, 0x71, 0x74]),
  32816. // moov string literal in hex
  32817. 'moov': toUint8([0x6D, 0x6F, 0x6F, 0x76]),
  32818. // moof string literal in hex
  32819. 'moof': toUint8([0x6D, 0x6F, 0x6F, 0x66])
  32820. };
  32821. var _isLikely = {
  32822. aac: function aac(bytes) {
  32823. var offset = getId3Offset(bytes);
  32824. return bytesMatch(bytes, [0xFF, 0x10], {
  32825. offset: offset,
  32826. mask: [0xFF, 0x16]
  32827. });
  32828. },
  32829. mp3: function mp3(bytes) {
  32830. var offset = getId3Offset(bytes);
  32831. return bytesMatch(bytes, [0xFF, 0x02], {
  32832. offset: offset,
  32833. mask: [0xFF, 0x06]
  32834. });
  32835. },
  32836. webm: function webm(bytes) {
  32837. var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is webm
  32838. return bytesMatch(docType, CONSTANTS.webm);
  32839. },
  32840. mkv: function mkv(bytes) {
  32841. var docType = findEbml(bytes, [EBML_TAGS.EBML, EBML_TAGS.DocType])[0]; // check if DocType EBML tag is matroska
  32842. return bytesMatch(docType, CONSTANTS.matroska);
  32843. },
  32844. mp4: function mp4(bytes) {
  32845. // if this file is another base media file format, it is not mp4
  32846. if (_isLikely['3gp'](bytes) || _isLikely.mov(bytes)) {
  32847. return false;
  32848. } // if this file starts with a ftyp or styp box its mp4
  32849. if (bytesMatch(bytes, CONSTANTS.mp4, {
  32850. offset: 4
  32851. }) || bytesMatch(bytes, CONSTANTS.fmp4, {
  32852. offset: 4
  32853. })) {
  32854. return true;
  32855. } // if this file starts with a moof/moov box its mp4
  32856. if (bytesMatch(bytes, CONSTANTS.moof, {
  32857. offset: 4
  32858. }) || bytesMatch(bytes, CONSTANTS.moov, {
  32859. offset: 4
  32860. })) {
  32861. return true;
  32862. }
  32863. },
  32864. mov: function mov(bytes) {
  32865. return bytesMatch(bytes, CONSTANTS.mov, {
  32866. offset: 4
  32867. });
  32868. },
  32869. '3gp': function gp(bytes) {
  32870. return bytesMatch(bytes, CONSTANTS['3gp'], {
  32871. offset: 4
  32872. });
  32873. },
  32874. ac3: function ac3(bytes) {
  32875. var offset = getId3Offset(bytes);
  32876. return bytesMatch(bytes, CONSTANTS.ac3, {
  32877. offset: offset
  32878. });
  32879. },
  32880. ts: function ts(bytes) {
  32881. if (bytes.length < 189 && bytes.length >= 1) {
  32882. return bytes[0] === 0x47;
  32883. }
  32884. var i = 0; // check the first 376 bytes for two matching sync bytes
  32885. while (i + 188 < bytes.length && i < 188) {
  32886. if (bytes[i] === 0x47 && bytes[i + 188] === 0x47) {
  32887. return true;
  32888. }
  32889. i += 1;
  32890. }
  32891. return false;
  32892. },
  32893. flac: function flac(bytes) {
  32894. var offset = getId3Offset(bytes);
  32895. return bytesMatch(bytes, CONSTANTS.flac, {
  32896. offset: offset
  32897. });
  32898. },
  32899. ogg: function ogg(bytes) {
  32900. return bytesMatch(bytes, CONSTANTS.ogg);
  32901. },
  32902. avi: function avi(bytes) {
  32903. return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.avi, {
  32904. offset: 8
  32905. });
  32906. },
  32907. wav: function wav(bytes) {
  32908. return bytesMatch(bytes, CONSTANTS.riff) && bytesMatch(bytes, CONSTANTS.wav, {
  32909. offset: 8
  32910. });
  32911. },
  32912. 'h264': function h264(bytes) {
  32913. // find seq_parameter_set_rbsp
  32914. return findH264Nal(bytes, 7, 3).length;
  32915. },
  32916. 'h265': function h265(bytes) {
  32917. // find video_parameter_set_rbsp or seq_parameter_set_rbsp
  32918. return findH265Nal(bytes, [32, 33], 3).length;
  32919. }
  32920. }; // get all the isLikely functions
  32921. // but make sure 'ts' is above h264 and h265
  32922. // but below everything else as it is the least specific
  32923. var isLikelyTypes = Object.keys(_isLikely) // remove ts, h264, h265
  32924. .filter(function (t) {
  32925. return t !== 'ts' && t !== 'h264' && t !== 'h265';
  32926. }) // add it back to the bottom
  32927. .concat(['ts', 'h264', 'h265']); // make sure we are dealing with uint8 data.
  32928. isLikelyTypes.forEach(function (type) {
  32929. var isLikelyFn = _isLikely[type];
  32930. _isLikely[type] = function (bytes) {
  32931. return isLikelyFn(toUint8(bytes));
  32932. };
  32933. }); // export after wrapping
  32934. var isLikely = _isLikely; // A useful list of file signatures can be found here
  32935. // https://en.wikipedia.org/wiki/List_of_file_signatures
  32936. var detectContainerForBytes = function detectContainerForBytes(bytes) {
  32937. bytes = toUint8(bytes);
  32938. for (var i = 0; i < isLikelyTypes.length; i++) {
  32939. var type = isLikelyTypes[i];
  32940. if (isLikely[type](bytes)) {
  32941. return type;
  32942. }
  32943. }
  32944. return '';
  32945. }; // fmp4 is not a container
  32946. var isLikelyFmp4MediaSegment = function isLikelyFmp4MediaSegment(bytes) {
  32947. return findBox(bytes, ['moof']).length > 0;
  32948. };
  32949. /**
  32950. * mux.js
  32951. *
  32952. * Copyright (c) Brightcove
  32953. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  32954. */
  32955. var ONE_SECOND_IN_TS = 90000,
  32956. // 90kHz clock
  32957. secondsToVideoTs,
  32958. secondsToAudioTs,
  32959. videoTsToSeconds,
  32960. audioTsToSeconds,
  32961. audioTsToVideoTs,
  32962. videoTsToAudioTs,
  32963. metadataTsToSeconds;
  32964. secondsToVideoTs = function secondsToVideoTs(seconds) {
  32965. return seconds * ONE_SECOND_IN_TS;
  32966. };
  32967. secondsToAudioTs = function secondsToAudioTs(seconds, sampleRate) {
  32968. return seconds * sampleRate;
  32969. };
  32970. videoTsToSeconds = function videoTsToSeconds(timestamp) {
  32971. return timestamp / ONE_SECOND_IN_TS;
  32972. };
  32973. audioTsToSeconds = function audioTsToSeconds(timestamp, sampleRate) {
  32974. return timestamp / sampleRate;
  32975. };
  32976. audioTsToVideoTs = function audioTsToVideoTs(timestamp, sampleRate) {
  32977. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  32978. };
  32979. videoTsToAudioTs = function videoTsToAudioTs(timestamp, sampleRate) {
  32980. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  32981. };
  32982. /**
  32983. * Adjust ID3 tag or caption timing information by the timeline pts values
  32984. * (if keepOriginalTimestamps is false) and convert to seconds
  32985. */
  32986. metadataTsToSeconds = function metadataTsToSeconds(timestamp, timelineStartPts, keepOriginalTimestamps) {
  32987. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  32988. };
  32989. var clock = {
  32990. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS,
  32991. secondsToVideoTs: secondsToVideoTs,
  32992. secondsToAudioTs: secondsToAudioTs,
  32993. videoTsToSeconds: videoTsToSeconds,
  32994. audioTsToSeconds: audioTsToSeconds,
  32995. audioTsToVideoTs: audioTsToVideoTs,
  32996. videoTsToAudioTs: videoTsToAudioTs,
  32997. metadataTsToSeconds: metadataTsToSeconds
  32998. };
  32999. var clock_1 = clock.ONE_SECOND_IN_TS;
  33000. var getPrototypeOf = createCommonjsModule(function (module) {
  33001. function _getPrototypeOf(o) {
  33002. module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
  33003. return o.__proto__ || Object.getPrototypeOf(o);
  33004. };
  33005. return _getPrototypeOf(o);
  33006. }
  33007. module.exports = _getPrototypeOf;
  33008. });
  33009. function _isNativeFunction(fn) {
  33010. return Function.toString.call(fn).indexOf("[native code]") !== -1;
  33011. }
  33012. var isNativeFunction = _isNativeFunction;
  33013. var wrapNativeSuper = createCommonjsModule(function (module) {
  33014. function _wrapNativeSuper(Class) {
  33015. var _cache = typeof Map === "function" ? new Map() : undefined;
  33016. module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) {
  33017. if (Class === null || !isNativeFunction(Class)) return Class;
  33018. if (typeof Class !== "function") {
  33019. throw new TypeError("Super expression must either be null or a function");
  33020. }
  33021. if (typeof _cache !== "undefined") {
  33022. if (_cache.has(Class)) return _cache.get(Class);
  33023. _cache.set(Class, Wrapper);
  33024. }
  33025. function Wrapper() {
  33026. return construct(Class, arguments, getPrototypeOf(this).constructor);
  33027. }
  33028. Wrapper.prototype = Object.create(Class.prototype, {
  33029. constructor: {
  33030. value: Wrapper,
  33031. enumerable: false,
  33032. writable: true,
  33033. configurable: true
  33034. }
  33035. });
  33036. return setPrototypeOf(Wrapper, Class);
  33037. };
  33038. return _wrapNativeSuper(Class);
  33039. }
  33040. module.exports = _wrapNativeSuper;
  33041. });
  33042. /*! @name @videojs/http-streaming @version 2.16.2 @license Apache-2.0 */
  33043. /**
  33044. * @file resolve-url.js - Handling how URLs are resolved and manipulated
  33045. */
  33046. var resolveUrl = resolveUrl$2;
  33047. /**
  33048. * Checks whether xhr request was redirected and returns correct url depending
  33049. * on `handleManifestRedirects` option
  33050. *
  33051. * @api private
  33052. *
  33053. * @param {string} url - an url being requested
  33054. * @param {XMLHttpRequest} req - xhr request result
  33055. *
  33056. * @return {string}
  33057. */
  33058. var resolveManifestRedirect = function resolveManifestRedirect(handleManifestRedirect, url, req) {
  33059. // To understand how the responseURL below is set and generated:
  33060. // - https://fetch.spec.whatwg.org/#concept-response-url
  33061. // - https://fetch.spec.whatwg.org/#atomic-http-redirect-handling
  33062. if (handleManifestRedirect && req && req.responseURL && url !== req.responseURL) {
  33063. return req.responseURL;
  33064. }
  33065. return url;
  33066. };
  33067. var logger = function logger(source) {
  33068. if (videojs.log.debug) {
  33069. return videojs.log.debug.bind(videojs, 'VHS:', source + " >");
  33070. }
  33071. return function () {};
  33072. };
  33073. /**
  33074. * ranges
  33075. *
  33076. * Utilities for working with TimeRanges.
  33077. *
  33078. */
  33079. var TIME_FUDGE_FACTOR = 1 / 30; // Comparisons between time values such as current time and the end of the buffered range
  33080. // can be misleading because of precision differences or when the current media has poorly
  33081. // aligned audio and video, which can cause values to be slightly off from what you would
  33082. // expect. This value is what we consider to be safe to use in such comparisons to account
  33083. // for these scenarios.
  33084. var SAFE_TIME_DELTA = TIME_FUDGE_FACTOR * 3;
  33085. var filterRanges = function filterRanges(timeRanges, predicate) {
  33086. var results = [];
  33087. var i;
  33088. if (timeRanges && timeRanges.length) {
  33089. // Search for ranges that match the predicate
  33090. for (i = 0; i < timeRanges.length; i++) {
  33091. if (predicate(timeRanges.start(i), timeRanges.end(i))) {
  33092. results.push([timeRanges.start(i), timeRanges.end(i)]);
  33093. }
  33094. }
  33095. }
  33096. return videojs.createTimeRanges(results);
  33097. };
  33098. /**
  33099. * Attempts to find the buffered TimeRange that contains the specified
  33100. * time.
  33101. *
  33102. * @param {TimeRanges} buffered - the TimeRanges object to query
  33103. * @param {number} time - the time to filter on.
  33104. * @return {TimeRanges} a new TimeRanges object
  33105. */
  33106. var findRange = function findRange(buffered, time) {
  33107. return filterRanges(buffered, function (start, end) {
  33108. return start - SAFE_TIME_DELTA <= time && end + SAFE_TIME_DELTA >= time;
  33109. });
  33110. };
  33111. /**
  33112. * Returns the TimeRanges that begin later than the specified time.
  33113. *
  33114. * @param {TimeRanges} timeRanges - the TimeRanges object to query
  33115. * @param {number} time - the time to filter on.
  33116. * @return {TimeRanges} a new TimeRanges object.
  33117. */
  33118. var findNextRange = function findNextRange(timeRanges, time) {
  33119. return filterRanges(timeRanges, function (start) {
  33120. return start - TIME_FUDGE_FACTOR >= time;
  33121. });
  33122. };
  33123. /**
  33124. * Returns gaps within a list of TimeRanges
  33125. *
  33126. * @param {TimeRanges} buffered - the TimeRanges object
  33127. * @return {TimeRanges} a TimeRanges object of gaps
  33128. */
  33129. var findGaps = function findGaps(buffered) {
  33130. if (buffered.length < 2) {
  33131. return videojs.createTimeRanges();
  33132. }
  33133. var ranges = [];
  33134. for (var i = 1; i < buffered.length; i++) {
  33135. var start = buffered.end(i - 1);
  33136. var end = buffered.start(i);
  33137. ranges.push([start, end]);
  33138. }
  33139. return videojs.createTimeRanges(ranges);
  33140. };
  33141. /**
  33142. * Calculate the intersection of two TimeRanges
  33143. *
  33144. * @param {TimeRanges} bufferA
  33145. * @param {TimeRanges} bufferB
  33146. * @return {TimeRanges} The interesection of `bufferA` with `bufferB`
  33147. */
  33148. var bufferIntersection = function bufferIntersection(bufferA, bufferB) {
  33149. var start = null;
  33150. var end = null;
  33151. var arity = 0;
  33152. var extents = [];
  33153. var ranges = [];
  33154. if (!bufferA || !bufferA.length || !bufferB || !bufferB.length) {
  33155. return videojs.createTimeRange();
  33156. } // Handle the case where we have both buffers and create an
  33157. // intersection of the two
  33158. var count = bufferA.length; // A) Gather up all start and end times
  33159. while (count--) {
  33160. extents.push({
  33161. time: bufferA.start(count),
  33162. type: 'start'
  33163. });
  33164. extents.push({
  33165. time: bufferA.end(count),
  33166. type: 'end'
  33167. });
  33168. }
  33169. count = bufferB.length;
  33170. while (count--) {
  33171. extents.push({
  33172. time: bufferB.start(count),
  33173. type: 'start'
  33174. });
  33175. extents.push({
  33176. time: bufferB.end(count),
  33177. type: 'end'
  33178. });
  33179. } // B) Sort them by time
  33180. extents.sort(function (a, b) {
  33181. return a.time - b.time;
  33182. }); // C) Go along one by one incrementing arity for start and decrementing
  33183. // arity for ends
  33184. for (count = 0; count < extents.length; count++) {
  33185. if (extents[count].type === 'start') {
  33186. arity++; // D) If arity is ever incremented to 2 we are entering an
  33187. // overlapping range
  33188. if (arity === 2) {
  33189. start = extents[count].time;
  33190. }
  33191. } else if (extents[count].type === 'end') {
  33192. arity--; // E) If arity is ever decremented to 1 we leaving an
  33193. // overlapping range
  33194. if (arity === 1) {
  33195. end = extents[count].time;
  33196. }
  33197. } // F) Record overlapping ranges
  33198. if (start !== null && end !== null) {
  33199. ranges.push([start, end]);
  33200. start = null;
  33201. end = null;
  33202. }
  33203. }
  33204. return videojs.createTimeRanges(ranges);
  33205. };
  33206. /**
  33207. * Gets a human readable string for a TimeRange
  33208. *
  33209. * @param {TimeRange} range
  33210. * @return {string} a human readable string
  33211. */
  33212. var printableRange = function printableRange(range) {
  33213. var strArr = [];
  33214. if (!range || !range.length) {
  33215. return '';
  33216. }
  33217. for (var i = 0; i < range.length; i++) {
  33218. strArr.push(range.start(i) + ' => ' + range.end(i));
  33219. }
  33220. return strArr.join(', ');
  33221. };
  33222. /**
  33223. * Calculates the amount of time left in seconds until the player hits the end of the
  33224. * buffer and causes a rebuffer
  33225. *
  33226. * @param {TimeRange} buffered
  33227. * The state of the buffer
  33228. * @param {Numnber} currentTime
  33229. * The current time of the player
  33230. * @param {number} playbackRate
  33231. * The current playback rate of the player. Defaults to 1.
  33232. * @return {number}
  33233. * Time until the player has to start rebuffering in seconds.
  33234. * @function timeUntilRebuffer
  33235. */
  33236. var timeUntilRebuffer = function timeUntilRebuffer(buffered, currentTime, playbackRate) {
  33237. if (playbackRate === void 0) {
  33238. playbackRate = 1;
  33239. }
  33240. var bufferedEnd = buffered.length ? buffered.end(buffered.length - 1) : 0;
  33241. return (bufferedEnd - currentTime) / playbackRate;
  33242. };
  33243. /**
  33244. * Converts a TimeRanges object into an array representation
  33245. *
  33246. * @param {TimeRanges} timeRanges
  33247. * @return {Array}
  33248. */
  33249. var timeRangesToArray = function timeRangesToArray(timeRanges) {
  33250. var timeRangesList = [];
  33251. for (var i = 0; i < timeRanges.length; i++) {
  33252. timeRangesList.push({
  33253. start: timeRanges.start(i),
  33254. end: timeRanges.end(i)
  33255. });
  33256. }
  33257. return timeRangesList;
  33258. };
  33259. /**
  33260. * Determines if two time range objects are different.
  33261. *
  33262. * @param {TimeRange} a
  33263. * the first time range object to check
  33264. *
  33265. * @param {TimeRange} b
  33266. * the second time range object to check
  33267. *
  33268. * @return {Boolean}
  33269. * Whether the time range objects differ
  33270. */
  33271. var isRangeDifferent = function isRangeDifferent(a, b) {
  33272. // same object
  33273. if (a === b) {
  33274. return false;
  33275. } // one or the other is undefined
  33276. if (!a && b || !b && a) {
  33277. return true;
  33278. } // length is different
  33279. if (a.length !== b.length) {
  33280. return true;
  33281. } // see if any start/end pair is different
  33282. for (var i = 0; i < a.length; i++) {
  33283. if (a.start(i) !== b.start(i) || a.end(i) !== b.end(i)) {
  33284. return true;
  33285. }
  33286. } // if the length and every pair is the same
  33287. // this is the same time range
  33288. return false;
  33289. };
  33290. var lastBufferedEnd = function lastBufferedEnd(a) {
  33291. if (!a || !a.length || !a.end) {
  33292. return;
  33293. }
  33294. return a.end(a.length - 1);
  33295. };
  33296. /**
  33297. * A utility function to add up the amount of time in a timeRange
  33298. * after a specified startTime.
  33299. * ie:[[0, 10], [20, 40], [50, 60]] with a startTime 0
  33300. * would return 40 as there are 40s seconds after 0 in the timeRange
  33301. *
  33302. * @param {TimeRange} range
  33303. * The range to check against
  33304. * @param {number} startTime
  33305. * The time in the time range that you should start counting from
  33306. *
  33307. * @return {number}
  33308. * The number of seconds in the buffer passed the specified time.
  33309. */
  33310. var timeAheadOf = function timeAheadOf(range, startTime) {
  33311. var time = 0;
  33312. if (!range || !range.length) {
  33313. return time;
  33314. }
  33315. for (var i = 0; i < range.length; i++) {
  33316. var start = range.start(i);
  33317. var end = range.end(i); // startTime is after this range entirely
  33318. if (startTime > end) {
  33319. continue;
  33320. } // startTime is within this range
  33321. if (startTime > start && startTime <= end) {
  33322. time += end - startTime;
  33323. continue;
  33324. } // startTime is before this range.
  33325. time += end - start;
  33326. }
  33327. return time;
  33328. };
  33329. /**
  33330. * @file playlist.js
  33331. *
  33332. * Playlist related utilities.
  33333. */
  33334. var createTimeRange = videojs.createTimeRange;
  33335. /**
  33336. * Get the duration of a segment, with special cases for
  33337. * llhls segments that do not have a duration yet.
  33338. *
  33339. * @param {Object} playlist
  33340. * the playlist that the segment belongs to.
  33341. * @param {Object} segment
  33342. * the segment to get a duration for.
  33343. *
  33344. * @return {number}
  33345. * the segment duration
  33346. */
  33347. var segmentDurationWithParts = function segmentDurationWithParts(playlist, segment) {
  33348. // if this isn't a preload segment
  33349. // then we will have a segment duration that is accurate.
  33350. if (!segment.preload) {
  33351. return segment.duration;
  33352. } // otherwise we have to add up parts and preload hints
  33353. // to get an up to date duration.
  33354. var result = 0;
  33355. (segment.parts || []).forEach(function (p) {
  33356. result += p.duration;
  33357. }); // for preload hints we have to use partTargetDuration
  33358. // as they won't even have a duration yet.
  33359. (segment.preloadHints || []).forEach(function (p) {
  33360. if (p.type === 'PART') {
  33361. result += playlist.partTargetDuration;
  33362. }
  33363. });
  33364. return result;
  33365. };
  33366. /**
  33367. * A function to get a combined list of parts and segments with durations
  33368. * and indexes.
  33369. *
  33370. * @param {Playlist} playlist the playlist to get the list for.
  33371. *
  33372. * @return {Array} The part/segment list.
  33373. */
  33374. var getPartsAndSegments = function getPartsAndSegments(playlist) {
  33375. return (playlist.segments || []).reduce(function (acc, segment, si) {
  33376. if (segment.parts) {
  33377. segment.parts.forEach(function (part, pi) {
  33378. acc.push({
  33379. duration: part.duration,
  33380. segmentIndex: si,
  33381. partIndex: pi,
  33382. part: part,
  33383. segment: segment
  33384. });
  33385. });
  33386. } else {
  33387. acc.push({
  33388. duration: segment.duration,
  33389. segmentIndex: si,
  33390. partIndex: null,
  33391. segment: segment,
  33392. part: null
  33393. });
  33394. }
  33395. return acc;
  33396. }, []);
  33397. };
  33398. var getLastParts = function getLastParts(media) {
  33399. var lastSegment = media.segments && media.segments.length && media.segments[media.segments.length - 1];
  33400. return lastSegment && lastSegment.parts || [];
  33401. };
  33402. var getKnownPartCount = function getKnownPartCount(_ref) {
  33403. var preloadSegment = _ref.preloadSegment;
  33404. if (!preloadSegment) {
  33405. return;
  33406. }
  33407. var parts = preloadSegment.parts,
  33408. preloadHints = preloadSegment.preloadHints;
  33409. var partCount = (preloadHints || []).reduce(function (count, hint) {
  33410. return count + (hint.type === 'PART' ? 1 : 0);
  33411. }, 0);
  33412. partCount += parts && parts.length ? parts.length : 0;
  33413. return partCount;
  33414. };
  33415. /**
  33416. * Get the number of seconds to delay from the end of a
  33417. * live playlist.
  33418. *
  33419. * @param {Playlist} master the master playlist
  33420. * @param {Playlist} media the media playlist
  33421. * @return {number} the hold back in seconds.
  33422. */
  33423. var liveEdgeDelay = function liveEdgeDelay(master, media) {
  33424. if (media.endList) {
  33425. return 0;
  33426. } // dash suggestedPresentationDelay trumps everything
  33427. if (master && master.suggestedPresentationDelay) {
  33428. return master.suggestedPresentationDelay;
  33429. }
  33430. var hasParts = getLastParts(media).length > 0; // look for "part" delays from ll-hls first
  33431. if (hasParts && media.serverControl && media.serverControl.partHoldBack) {
  33432. return media.serverControl.partHoldBack;
  33433. } else if (hasParts && media.partTargetDuration) {
  33434. return media.partTargetDuration * 3; // finally look for full segment delays
  33435. } else if (media.serverControl && media.serverControl.holdBack) {
  33436. return media.serverControl.holdBack;
  33437. } else if (media.targetDuration) {
  33438. return media.targetDuration * 3;
  33439. }
  33440. return 0;
  33441. };
  33442. /**
  33443. * walk backward until we find a duration we can use
  33444. * or return a failure
  33445. *
  33446. * @param {Playlist} playlist the playlist to walk through
  33447. * @param {Number} endSequence the mediaSequence to stop walking on
  33448. */
  33449. var backwardDuration = function backwardDuration(playlist, endSequence) {
  33450. var result = 0;
  33451. var i = endSequence - playlist.mediaSequence; // if a start time is available for segment immediately following
  33452. // the interval, use it
  33453. var segment = playlist.segments[i]; // Walk backward until we find the latest segment with timeline
  33454. // information that is earlier than endSequence
  33455. if (segment) {
  33456. if (typeof segment.start !== 'undefined') {
  33457. return {
  33458. result: segment.start,
  33459. precise: true
  33460. };
  33461. }
  33462. if (typeof segment.end !== 'undefined') {
  33463. return {
  33464. result: segment.end - segment.duration,
  33465. precise: true
  33466. };
  33467. }
  33468. }
  33469. while (i--) {
  33470. segment = playlist.segments[i];
  33471. if (typeof segment.end !== 'undefined') {
  33472. return {
  33473. result: result + segment.end,
  33474. precise: true
  33475. };
  33476. }
  33477. result += segmentDurationWithParts(playlist, segment);
  33478. if (typeof segment.start !== 'undefined') {
  33479. return {
  33480. result: result + segment.start,
  33481. precise: true
  33482. };
  33483. }
  33484. }
  33485. return {
  33486. result: result,
  33487. precise: false
  33488. };
  33489. };
  33490. /**
  33491. * walk forward until we find a duration we can use
  33492. * or return a failure
  33493. *
  33494. * @param {Playlist} playlist the playlist to walk through
  33495. * @param {number} endSequence the mediaSequence to stop walking on
  33496. */
  33497. var forwardDuration = function forwardDuration(playlist, endSequence) {
  33498. var result = 0;
  33499. var segment;
  33500. var i = endSequence - playlist.mediaSequence; // Walk forward until we find the earliest segment with timeline
  33501. // information
  33502. for (; i < playlist.segments.length; i++) {
  33503. segment = playlist.segments[i];
  33504. if (typeof segment.start !== 'undefined') {
  33505. return {
  33506. result: segment.start - result,
  33507. precise: true
  33508. };
  33509. }
  33510. result += segmentDurationWithParts(playlist, segment);
  33511. if (typeof segment.end !== 'undefined') {
  33512. return {
  33513. result: segment.end - result,
  33514. precise: true
  33515. };
  33516. }
  33517. } // indicate we didn't find a useful duration estimate
  33518. return {
  33519. result: -1,
  33520. precise: false
  33521. };
  33522. };
  33523. /**
  33524. * Calculate the media duration from the segments associated with a
  33525. * playlist. The duration of a subinterval of the available segments
  33526. * may be calculated by specifying an end index.
  33527. *
  33528. * @param {Object} playlist a media playlist object
  33529. * @param {number=} endSequence an exclusive upper boundary
  33530. * for the playlist. Defaults to playlist length.
  33531. * @param {number} expired the amount of time that has dropped
  33532. * off the front of the playlist in a live scenario
  33533. * @return {number} the duration between the first available segment
  33534. * and end index.
  33535. */
  33536. var intervalDuration = function intervalDuration(playlist, endSequence, expired) {
  33537. if (typeof endSequence === 'undefined') {
  33538. endSequence = playlist.mediaSequence + playlist.segments.length;
  33539. }
  33540. if (endSequence < playlist.mediaSequence) {
  33541. return 0;
  33542. } // do a backward walk to estimate the duration
  33543. var backward = backwardDuration(playlist, endSequence);
  33544. if (backward.precise) {
  33545. // if we were able to base our duration estimate on timing
  33546. // information provided directly from the Media Source, return
  33547. // it
  33548. return backward.result;
  33549. } // walk forward to see if a precise duration estimate can be made
  33550. // that way
  33551. var forward = forwardDuration(playlist, endSequence);
  33552. if (forward.precise) {
  33553. // we found a segment that has been buffered and so it's
  33554. // position is known precisely
  33555. return forward.result;
  33556. } // return the less-precise, playlist-based duration estimate
  33557. return backward.result + expired;
  33558. };
  33559. /**
  33560. * Calculates the duration of a playlist. If a start and end index
  33561. * are specified, the duration will be for the subset of the media
  33562. * timeline between those two indices. The total duration for live
  33563. * playlists is always Infinity.
  33564. *
  33565. * @param {Object} playlist a media playlist object
  33566. * @param {number=} endSequence an exclusive upper
  33567. * boundary for the playlist. Defaults to the playlist media
  33568. * sequence number plus its length.
  33569. * @param {number=} expired the amount of time that has
  33570. * dropped off the front of the playlist in a live scenario
  33571. * @return {number} the duration between the start index and end
  33572. * index.
  33573. */
  33574. var duration = function duration(playlist, endSequence, expired) {
  33575. if (!playlist) {
  33576. return 0;
  33577. }
  33578. if (typeof expired !== 'number') {
  33579. expired = 0;
  33580. } // if a slice of the total duration is not requested, use
  33581. // playlist-level duration indicators when they're present
  33582. if (typeof endSequence === 'undefined') {
  33583. // if present, use the duration specified in the playlist
  33584. if (playlist.totalDuration) {
  33585. return playlist.totalDuration;
  33586. } // duration should be Infinity for live playlists
  33587. if (!playlist.endList) {
  33588. return window.Infinity;
  33589. }
  33590. } // calculate the total duration based on the segment durations
  33591. return intervalDuration(playlist, endSequence, expired);
  33592. };
  33593. /**
  33594. * Calculate the time between two indexes in the current playlist
  33595. * neight the start- nor the end-index need to be within the current
  33596. * playlist in which case, the targetDuration of the playlist is used
  33597. * to approximate the durations of the segments
  33598. *
  33599. * @param {Array} options.durationList list to iterate over for durations.
  33600. * @param {number} options.defaultDuration duration to use for elements before or after the durationList
  33601. * @param {number} options.startIndex partsAndSegments index to start
  33602. * @param {number} options.endIndex partsAndSegments index to end.
  33603. * @return {number} the number of seconds between startIndex and endIndex
  33604. */
  33605. var sumDurations = function sumDurations(_ref2) {
  33606. var defaultDuration = _ref2.defaultDuration,
  33607. durationList = _ref2.durationList,
  33608. startIndex = _ref2.startIndex,
  33609. endIndex = _ref2.endIndex;
  33610. var durations = 0;
  33611. if (startIndex > endIndex) {
  33612. var _ref3 = [endIndex, startIndex];
  33613. startIndex = _ref3[0];
  33614. endIndex = _ref3[1];
  33615. }
  33616. if (startIndex < 0) {
  33617. for (var i = startIndex; i < Math.min(0, endIndex); i++) {
  33618. durations += defaultDuration;
  33619. }
  33620. startIndex = 0;
  33621. }
  33622. for (var _i = startIndex; _i < endIndex; _i++) {
  33623. durations += durationList[_i].duration;
  33624. }
  33625. return durations;
  33626. };
  33627. /**
  33628. * Calculates the playlist end time
  33629. *
  33630. * @param {Object} playlist a media playlist object
  33631. * @param {number=} expired the amount of time that has
  33632. * dropped off the front of the playlist in a live scenario
  33633. * @param {boolean|false} useSafeLiveEnd a boolean value indicating whether or not the
  33634. * playlist end calculation should consider the safe live end
  33635. * (truncate the playlist end by three segments). This is normally
  33636. * used for calculating the end of the playlist's seekable range.
  33637. * This takes into account the value of liveEdgePadding.
  33638. * Setting liveEdgePadding to 0 is equivalent to setting this to false.
  33639. * @param {number} liveEdgePadding a number indicating how far from the end of the playlist we should be in seconds.
  33640. * If this is provided, it is used in the safe live end calculation.
  33641. * Setting useSafeLiveEnd=false or liveEdgePadding=0 are equivalent.
  33642. * Corresponds to suggestedPresentationDelay in DASH manifests.
  33643. * @return {number} the end time of playlist
  33644. * @function playlistEnd
  33645. */
  33646. var playlistEnd = function playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding) {
  33647. if (!playlist || !playlist.segments) {
  33648. return null;
  33649. }
  33650. if (playlist.endList) {
  33651. return duration(playlist);
  33652. }
  33653. if (expired === null) {
  33654. return null;
  33655. }
  33656. expired = expired || 0;
  33657. var lastSegmentEndTime = intervalDuration(playlist, playlist.mediaSequence + playlist.segments.length, expired);
  33658. if (useSafeLiveEnd) {
  33659. liveEdgePadding = typeof liveEdgePadding === 'number' ? liveEdgePadding : liveEdgeDelay(null, playlist);
  33660. lastSegmentEndTime -= liveEdgePadding;
  33661. } // don't return a time less than zero
  33662. return Math.max(0, lastSegmentEndTime);
  33663. };
  33664. /**
  33665. * Calculates the interval of time that is currently seekable in a
  33666. * playlist. The returned time ranges are relative to the earliest
  33667. * moment in the specified playlist that is still available. A full
  33668. * seekable implementation for live streams would need to offset
  33669. * these values by the duration of content that has expired from the
  33670. * stream.
  33671. *
  33672. * @param {Object} playlist a media playlist object
  33673. * dropped off the front of the playlist in a live scenario
  33674. * @param {number=} expired the amount of time that has
  33675. * dropped off the front of the playlist in a live scenario
  33676. * @param {number} liveEdgePadding how far from the end of the playlist we should be in seconds.
  33677. * Corresponds to suggestedPresentationDelay in DASH manifests.
  33678. * @return {TimeRanges} the periods of time that are valid targets
  33679. * for seeking
  33680. */
  33681. var seekable = function seekable(playlist, expired, liveEdgePadding) {
  33682. var useSafeLiveEnd = true;
  33683. var seekableStart = expired || 0;
  33684. var seekableEnd = playlistEnd(playlist, expired, useSafeLiveEnd, liveEdgePadding);
  33685. if (seekableEnd === null) {
  33686. return createTimeRange();
  33687. }
  33688. return createTimeRange(seekableStart, seekableEnd);
  33689. };
  33690. /**
  33691. * Determine the index and estimated starting time of the segment that
  33692. * contains a specified playback position in a media playlist.
  33693. *
  33694. * @param {Object} options.playlist the media playlist to query
  33695. * @param {number} options.currentTime The number of seconds since the earliest
  33696. * possible position to determine the containing segment for
  33697. * @param {number} options.startTime the time when the segment/part starts
  33698. * @param {number} options.startingSegmentIndex the segment index to start looking at.
  33699. * @param {number?} [options.startingPartIndex] the part index to look at within the segment.
  33700. *
  33701. * @return {Object} an object with partIndex, segmentIndex, and startTime.
  33702. */
  33703. var getMediaInfoForTime = function getMediaInfoForTime(_ref4) {
  33704. var playlist = _ref4.playlist,
  33705. currentTime = _ref4.currentTime,
  33706. startingSegmentIndex = _ref4.startingSegmentIndex,
  33707. startingPartIndex = _ref4.startingPartIndex,
  33708. startTime = _ref4.startTime,
  33709. experimentalExactManifestTimings = _ref4.experimentalExactManifestTimings;
  33710. var time = currentTime - startTime;
  33711. var partsAndSegments = getPartsAndSegments(playlist);
  33712. var startIndex = 0;
  33713. for (var i = 0; i < partsAndSegments.length; i++) {
  33714. var partAndSegment = partsAndSegments[i];
  33715. if (startingSegmentIndex !== partAndSegment.segmentIndex) {
  33716. continue;
  33717. } // skip this if part index does not match.
  33718. if (typeof startingPartIndex === 'number' && typeof partAndSegment.partIndex === 'number' && startingPartIndex !== partAndSegment.partIndex) {
  33719. continue;
  33720. }
  33721. startIndex = i;
  33722. break;
  33723. }
  33724. if (time < 0) {
  33725. // Walk backward from startIndex in the playlist, adding durations
  33726. // until we find a segment that contains `time` and return it
  33727. if (startIndex > 0) {
  33728. for (var _i2 = startIndex - 1; _i2 >= 0; _i2--) {
  33729. var _partAndSegment = partsAndSegments[_i2];
  33730. time += _partAndSegment.duration;
  33731. if (experimentalExactManifestTimings) {
  33732. if (time < 0) {
  33733. continue;
  33734. }
  33735. } else if (time + TIME_FUDGE_FACTOR <= 0) {
  33736. continue;
  33737. }
  33738. return {
  33739. partIndex: _partAndSegment.partIndex,
  33740. segmentIndex: _partAndSegment.segmentIndex,
  33741. startTime: startTime - sumDurations({
  33742. defaultDuration: playlist.targetDuration,
  33743. durationList: partsAndSegments,
  33744. startIndex: startIndex,
  33745. endIndex: _i2
  33746. })
  33747. };
  33748. }
  33749. } // We were unable to find a good segment within the playlist
  33750. // so select the first segment
  33751. return {
  33752. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  33753. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  33754. startTime: currentTime
  33755. };
  33756. } // When startIndex is negative, we first walk forward to first segment
  33757. // adding target durations. If we "run out of time" before getting to
  33758. // the first segment, return the first segment
  33759. if (startIndex < 0) {
  33760. for (var _i3 = startIndex; _i3 < 0; _i3++) {
  33761. time -= playlist.targetDuration;
  33762. if (time < 0) {
  33763. return {
  33764. partIndex: partsAndSegments[0] && partsAndSegments[0].partIndex || null,
  33765. segmentIndex: partsAndSegments[0] && partsAndSegments[0].segmentIndex || 0,
  33766. startTime: currentTime
  33767. };
  33768. }
  33769. }
  33770. startIndex = 0;
  33771. } // Walk forward from startIndex in the playlist, subtracting durations
  33772. // until we find a segment that contains `time` and return it
  33773. for (var _i4 = startIndex; _i4 < partsAndSegments.length; _i4++) {
  33774. var _partAndSegment2 = partsAndSegments[_i4];
  33775. time -= _partAndSegment2.duration;
  33776. if (experimentalExactManifestTimings) {
  33777. if (time > 0) {
  33778. continue;
  33779. }
  33780. } else if (time - TIME_FUDGE_FACTOR >= 0) {
  33781. continue;
  33782. }
  33783. return {
  33784. partIndex: _partAndSegment2.partIndex,
  33785. segmentIndex: _partAndSegment2.segmentIndex,
  33786. startTime: startTime + sumDurations({
  33787. defaultDuration: playlist.targetDuration,
  33788. durationList: partsAndSegments,
  33789. startIndex: startIndex,
  33790. endIndex: _i4
  33791. })
  33792. };
  33793. } // We are out of possible candidates so load the last one...
  33794. return {
  33795. segmentIndex: partsAndSegments[partsAndSegments.length - 1].segmentIndex,
  33796. partIndex: partsAndSegments[partsAndSegments.length - 1].partIndex,
  33797. startTime: currentTime
  33798. };
  33799. };
  33800. /**
  33801. * Check whether the playlist is blacklisted or not.
  33802. *
  33803. * @param {Object} playlist the media playlist object
  33804. * @return {boolean} whether the playlist is blacklisted or not
  33805. * @function isBlacklisted
  33806. */
  33807. var isBlacklisted = function isBlacklisted(playlist) {
  33808. return playlist.excludeUntil && playlist.excludeUntil > Date.now();
  33809. };
  33810. /**
  33811. * Check whether the playlist is compatible with current playback configuration or has
  33812. * been blacklisted permanently for being incompatible.
  33813. *
  33814. * @param {Object} playlist the media playlist object
  33815. * @return {boolean} whether the playlist is incompatible or not
  33816. * @function isIncompatible
  33817. */
  33818. var isIncompatible = function isIncompatible(playlist) {
  33819. return playlist.excludeUntil && playlist.excludeUntil === Infinity;
  33820. };
  33821. /**
  33822. * Check whether the playlist is enabled or not.
  33823. *
  33824. * @param {Object} playlist the media playlist object
  33825. * @return {boolean} whether the playlist is enabled or not
  33826. * @function isEnabled
  33827. */
  33828. var isEnabled = function isEnabled(playlist) {
  33829. var blacklisted = isBlacklisted(playlist);
  33830. return !playlist.disabled && !blacklisted;
  33831. };
  33832. /**
  33833. * Check whether the playlist has been manually disabled through the representations api.
  33834. *
  33835. * @param {Object} playlist the media playlist object
  33836. * @return {boolean} whether the playlist is disabled manually or not
  33837. * @function isDisabled
  33838. */
  33839. var isDisabled = function isDisabled(playlist) {
  33840. return playlist.disabled;
  33841. };
  33842. /**
  33843. * Returns whether the current playlist is an AES encrypted HLS stream
  33844. *
  33845. * @return {boolean} true if it's an AES encrypted HLS stream
  33846. */
  33847. var isAes = function isAes(media) {
  33848. for (var i = 0; i < media.segments.length; i++) {
  33849. if (media.segments[i].key) {
  33850. return true;
  33851. }
  33852. }
  33853. return false;
  33854. };
  33855. /**
  33856. * Checks if the playlist has a value for the specified attribute
  33857. *
  33858. * @param {string} attr
  33859. * Attribute to check for
  33860. * @param {Object} playlist
  33861. * The media playlist object
  33862. * @return {boolean}
  33863. * Whether the playlist contains a value for the attribute or not
  33864. * @function hasAttribute
  33865. */
  33866. var hasAttribute = function hasAttribute(attr, playlist) {
  33867. return playlist.attributes && playlist.attributes[attr];
  33868. };
  33869. /**
  33870. * Estimates the time required to complete a segment download from the specified playlist
  33871. *
  33872. * @param {number} segmentDuration
  33873. * Duration of requested segment
  33874. * @param {number} bandwidth
  33875. * Current measured bandwidth of the player
  33876. * @param {Object} playlist
  33877. * The media playlist object
  33878. * @param {number=} bytesReceived
  33879. * Number of bytes already received for the request. Defaults to 0
  33880. * @return {number|NaN}
  33881. * The estimated time to request the segment. NaN if bandwidth information for
  33882. * the given playlist is unavailable
  33883. * @function estimateSegmentRequestTime
  33884. */
  33885. var estimateSegmentRequestTime = function estimateSegmentRequestTime(segmentDuration, bandwidth, playlist, bytesReceived) {
  33886. if (bytesReceived === void 0) {
  33887. bytesReceived = 0;
  33888. }
  33889. if (!hasAttribute('BANDWIDTH', playlist)) {
  33890. return NaN;
  33891. }
  33892. var size = segmentDuration * playlist.attributes.BANDWIDTH;
  33893. return (size - bytesReceived * 8) / bandwidth;
  33894. };
  33895. /*
  33896. * Returns whether the current playlist is the lowest rendition
  33897. *
  33898. * @return {Boolean} true if on lowest rendition
  33899. */
  33900. var isLowestEnabledRendition = function isLowestEnabledRendition(master, media) {
  33901. if (master.playlists.length === 1) {
  33902. return true;
  33903. }
  33904. var currentBandwidth = media.attributes.BANDWIDTH || Number.MAX_VALUE;
  33905. return master.playlists.filter(function (playlist) {
  33906. if (!isEnabled(playlist)) {
  33907. return false;
  33908. }
  33909. return (playlist.attributes.BANDWIDTH || 0) < currentBandwidth;
  33910. }).length === 0;
  33911. };
  33912. var playlistMatch = function playlistMatch(a, b) {
  33913. // both playlits are null
  33914. // or only one playlist is non-null
  33915. // no match
  33916. if (!a && !b || !a && b || a && !b) {
  33917. return false;
  33918. } // playlist objects are the same, match
  33919. if (a === b) {
  33920. return true;
  33921. } // first try to use id as it should be the most
  33922. // accurate
  33923. if (a.id && b.id && a.id === b.id) {
  33924. return true;
  33925. } // next try to use reslovedUri as it should be the
  33926. // second most accurate.
  33927. if (a.resolvedUri && b.resolvedUri && a.resolvedUri === b.resolvedUri) {
  33928. return true;
  33929. } // finally try to use uri as it should be accurate
  33930. // but might miss a few cases for relative uris
  33931. if (a.uri && b.uri && a.uri === b.uri) {
  33932. return true;
  33933. }
  33934. return false;
  33935. };
  33936. var someAudioVariant = function someAudioVariant(master, callback) {
  33937. var AUDIO = master && master.mediaGroups && master.mediaGroups.AUDIO || {};
  33938. var found = false;
  33939. for (var groupName in AUDIO) {
  33940. for (var label in AUDIO[groupName]) {
  33941. found = callback(AUDIO[groupName][label]);
  33942. if (found) {
  33943. break;
  33944. }
  33945. }
  33946. if (found) {
  33947. break;
  33948. }
  33949. }
  33950. return !!found;
  33951. };
  33952. var isAudioOnly = function isAudioOnly(master) {
  33953. // we are audio only if we have no main playlists but do
  33954. // have media group playlists.
  33955. if (!master || !master.playlists || !master.playlists.length) {
  33956. // without audio variants or playlists this
  33957. // is not an audio only master.
  33958. var found = someAudioVariant(master, function (variant) {
  33959. return variant.playlists && variant.playlists.length || variant.uri;
  33960. });
  33961. return found;
  33962. } // if every playlist has only an audio codec it is audio only
  33963. var _loop = function _loop(i) {
  33964. var playlist = master.playlists[i];
  33965. var CODECS = playlist.attributes && playlist.attributes.CODECS; // all codecs are audio, this is an audio playlist.
  33966. if (CODECS && CODECS.split(',').every(function (c) {
  33967. return isAudioCodec(c);
  33968. })) {
  33969. return "continue";
  33970. } // playlist is in an audio group it is audio only
  33971. var found = someAudioVariant(master, function (variant) {
  33972. return playlistMatch(playlist, variant);
  33973. });
  33974. if (found) {
  33975. return "continue";
  33976. } // if we make it here this playlist isn't audio and we
  33977. // are not audio only
  33978. return {
  33979. v: false
  33980. };
  33981. };
  33982. for (var i = 0; i < master.playlists.length; i++) {
  33983. var _ret = _loop(i);
  33984. if (_ret === "continue") continue;
  33985. if (typeof _ret === "object") return _ret.v;
  33986. } // if we make it past every playlist without returning, then
  33987. // this is an audio only playlist.
  33988. return true;
  33989. }; // exports
  33990. var Playlist = {
  33991. liveEdgeDelay: liveEdgeDelay,
  33992. duration: duration,
  33993. seekable: seekable,
  33994. getMediaInfoForTime: getMediaInfoForTime,
  33995. isEnabled: isEnabled,
  33996. isDisabled: isDisabled,
  33997. isBlacklisted: isBlacklisted,
  33998. isIncompatible: isIncompatible,
  33999. playlistEnd: playlistEnd,
  34000. isAes: isAes,
  34001. hasAttribute: hasAttribute,
  34002. estimateSegmentRequestTime: estimateSegmentRequestTime,
  34003. isLowestEnabledRendition: isLowestEnabledRendition,
  34004. isAudioOnly: isAudioOnly,
  34005. playlistMatch: playlistMatch,
  34006. segmentDurationWithParts: segmentDurationWithParts
  34007. };
  34008. var log = videojs.log;
  34009. var createPlaylistID = function createPlaylistID(index, uri) {
  34010. return index + "-" + uri;
  34011. }; // default function for creating a group id
  34012. var groupID = function groupID(type, group, label) {
  34013. return "placeholder-uri-" + type + "-" + group + "-" + label;
  34014. };
  34015. /**
  34016. * Parses a given m3u8 playlist
  34017. *
  34018. * @param {Function} [onwarn]
  34019. * a function to call when the parser triggers a warning event.
  34020. * @param {Function} [oninfo]
  34021. * a function to call when the parser triggers an info event.
  34022. * @param {string} manifestString
  34023. * The downloaded manifest string
  34024. * @param {Object[]} [customTagParsers]
  34025. * An array of custom tag parsers for the m3u8-parser instance
  34026. * @param {Object[]} [customTagMappers]
  34027. * An array of custom tag mappers for the m3u8-parser instance
  34028. * @param {boolean} [experimentalLLHLS=false]
  34029. * Whether to keep ll-hls features in the manifest after parsing.
  34030. * @return {Object}
  34031. * The manifest object
  34032. */
  34033. var parseManifest = function parseManifest(_ref) {
  34034. var onwarn = _ref.onwarn,
  34035. oninfo = _ref.oninfo,
  34036. manifestString = _ref.manifestString,
  34037. _ref$customTagParsers = _ref.customTagParsers,
  34038. customTagParsers = _ref$customTagParsers === void 0 ? [] : _ref$customTagParsers,
  34039. _ref$customTagMappers = _ref.customTagMappers,
  34040. customTagMappers = _ref$customTagMappers === void 0 ? [] : _ref$customTagMappers,
  34041. experimentalLLHLS = _ref.experimentalLLHLS;
  34042. var parser = new Parser();
  34043. if (onwarn) {
  34044. parser.on('warn', onwarn);
  34045. }
  34046. if (oninfo) {
  34047. parser.on('info', oninfo);
  34048. }
  34049. customTagParsers.forEach(function (customParser) {
  34050. return parser.addParser(customParser);
  34051. });
  34052. customTagMappers.forEach(function (mapper) {
  34053. return parser.addTagMapper(mapper);
  34054. });
  34055. parser.push(manifestString);
  34056. parser.end();
  34057. var manifest = parser.manifest; // remove llhls features from the parsed manifest
  34058. // if we don't want llhls support.
  34059. if (!experimentalLLHLS) {
  34060. ['preloadSegment', 'skip', 'serverControl', 'renditionReports', 'partInf', 'partTargetDuration'].forEach(function (k) {
  34061. if (manifest.hasOwnProperty(k)) {
  34062. delete manifest[k];
  34063. }
  34064. });
  34065. if (manifest.segments) {
  34066. manifest.segments.forEach(function (segment) {
  34067. ['parts', 'preloadHints'].forEach(function (k) {
  34068. if (segment.hasOwnProperty(k)) {
  34069. delete segment[k];
  34070. }
  34071. });
  34072. });
  34073. }
  34074. }
  34075. if (!manifest.targetDuration) {
  34076. var targetDuration = 10;
  34077. if (manifest.segments && manifest.segments.length) {
  34078. targetDuration = manifest.segments.reduce(function (acc, s) {
  34079. return Math.max(acc, s.duration);
  34080. }, 0);
  34081. }
  34082. if (onwarn) {
  34083. onwarn("manifest has no targetDuration defaulting to " + targetDuration);
  34084. }
  34085. manifest.targetDuration = targetDuration;
  34086. }
  34087. var parts = getLastParts(manifest);
  34088. if (parts.length && !manifest.partTargetDuration) {
  34089. var partTargetDuration = parts.reduce(function (acc, p) {
  34090. return Math.max(acc, p.duration);
  34091. }, 0);
  34092. if (onwarn) {
  34093. onwarn("manifest has no partTargetDuration defaulting to " + partTargetDuration);
  34094. 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.');
  34095. }
  34096. manifest.partTargetDuration = partTargetDuration;
  34097. }
  34098. return manifest;
  34099. };
  34100. /**
  34101. * Loops through all supported media groups in master and calls the provided
  34102. * callback for each group
  34103. *
  34104. * @param {Object} master
  34105. * The parsed master manifest object
  34106. * @param {Function} callback
  34107. * Callback to call for each media group
  34108. */
  34109. var forEachMediaGroup = function forEachMediaGroup(master, callback) {
  34110. if (!master.mediaGroups) {
  34111. return;
  34112. }
  34113. ['AUDIO', 'SUBTITLES'].forEach(function (mediaType) {
  34114. if (!master.mediaGroups[mediaType]) {
  34115. return;
  34116. }
  34117. for (var groupKey in master.mediaGroups[mediaType]) {
  34118. for (var labelKey in master.mediaGroups[mediaType][groupKey]) {
  34119. var mediaProperties = master.mediaGroups[mediaType][groupKey][labelKey];
  34120. callback(mediaProperties, mediaType, groupKey, labelKey);
  34121. }
  34122. }
  34123. });
  34124. };
  34125. /**
  34126. * Adds properties and attributes to the playlist to keep consistent functionality for
  34127. * playlists throughout VHS.
  34128. *
  34129. * @param {Object} config
  34130. * Arguments object
  34131. * @param {Object} config.playlist
  34132. * The media playlist
  34133. * @param {string} [config.uri]
  34134. * The uri to the media playlist (if media playlist is not from within a master
  34135. * playlist)
  34136. * @param {string} id
  34137. * ID to use for the playlist
  34138. */
  34139. var setupMediaPlaylist = function setupMediaPlaylist(_ref2) {
  34140. var playlist = _ref2.playlist,
  34141. uri = _ref2.uri,
  34142. id = _ref2.id;
  34143. playlist.id = id;
  34144. playlist.playlistErrors_ = 0;
  34145. if (uri) {
  34146. // For media playlists, m3u8-parser does not have access to a URI, as HLS media
  34147. // playlists do not contain their own source URI, but one is needed for consistency in
  34148. // VHS.
  34149. playlist.uri = uri;
  34150. } // For HLS master playlists, even though certain attributes MUST be defined, the
  34151. // stream may still be played without them.
  34152. // For HLS media playlists, m3u8-parser does not attach an attributes object to the
  34153. // manifest.
  34154. //
  34155. // To avoid undefined reference errors through the project, and make the code easier
  34156. // to write/read, add an empty attributes object for these cases.
  34157. playlist.attributes = playlist.attributes || {};
  34158. };
  34159. /**
  34160. * Adds ID, resolvedUri, and attributes properties to each playlist of the master, where
  34161. * necessary. In addition, creates playlist IDs for each playlist and adds playlist ID to
  34162. * playlist references to the playlists array.
  34163. *
  34164. * @param {Object} master
  34165. * The master playlist
  34166. */
  34167. var setupMediaPlaylists = function setupMediaPlaylists(master) {
  34168. var i = master.playlists.length;
  34169. while (i--) {
  34170. var playlist = master.playlists[i];
  34171. setupMediaPlaylist({
  34172. playlist: playlist,
  34173. id: createPlaylistID(i, playlist.uri)
  34174. });
  34175. playlist.resolvedUri = resolveUrl(master.uri, playlist.uri);
  34176. master.playlists[playlist.id] = playlist; // URI reference added for backwards compatibility
  34177. master.playlists[playlist.uri] = playlist; // Although the spec states an #EXT-X-STREAM-INF tag MUST have a BANDWIDTH attribute,
  34178. // the stream can be played without it. Although an attributes property may have been
  34179. // added to the playlist to prevent undefined references, issue a warning to fix the
  34180. // manifest.
  34181. if (!playlist.attributes.BANDWIDTH) {
  34182. log.warn('Invalid playlist STREAM-INF detected. Missing BANDWIDTH attribute.');
  34183. }
  34184. }
  34185. };
  34186. /**
  34187. * Adds resolvedUri properties to each media group.
  34188. *
  34189. * @param {Object} master
  34190. * The master playlist
  34191. */
  34192. var resolveMediaGroupUris = function resolveMediaGroupUris(master) {
  34193. forEachMediaGroup(master, function (properties) {
  34194. if (properties.uri) {
  34195. properties.resolvedUri = resolveUrl(master.uri, properties.uri);
  34196. }
  34197. });
  34198. };
  34199. /**
  34200. * Creates a master playlist wrapper to insert a sole media playlist into.
  34201. *
  34202. * @param {Object} media
  34203. * Media playlist
  34204. * @param {string} uri
  34205. * The media URI
  34206. *
  34207. * @return {Object}
  34208. * Master playlist
  34209. */
  34210. var masterForMedia = function masterForMedia(media, uri) {
  34211. var id = createPlaylistID(0, uri);
  34212. var master = {
  34213. mediaGroups: {
  34214. 'AUDIO': {},
  34215. 'VIDEO': {},
  34216. 'CLOSED-CAPTIONS': {},
  34217. 'SUBTITLES': {}
  34218. },
  34219. uri: window.location.href,
  34220. resolvedUri: window.location.href,
  34221. playlists: [{
  34222. uri: uri,
  34223. id: id,
  34224. resolvedUri: uri,
  34225. // m3u8-parser does not attach an attributes property to media playlists so make
  34226. // sure that the property is attached to avoid undefined reference errors
  34227. attributes: {}
  34228. }]
  34229. }; // set up ID reference
  34230. master.playlists[id] = master.playlists[0]; // URI reference added for backwards compatibility
  34231. master.playlists[uri] = master.playlists[0];
  34232. return master;
  34233. };
  34234. /**
  34235. * Does an in-place update of the master manifest to add updated playlist URI references
  34236. * as well as other properties needed by VHS that aren't included by the parser.
  34237. *
  34238. * @param {Object} master
  34239. * Master manifest object
  34240. * @param {string} uri
  34241. * The source URI
  34242. * @param {function} createGroupID
  34243. * A function to determine how to create the groupID for mediaGroups
  34244. */
  34245. var addPropertiesToMaster = function addPropertiesToMaster(master, uri, createGroupID) {
  34246. if (createGroupID === void 0) {
  34247. createGroupID = groupID;
  34248. }
  34249. master.uri = uri;
  34250. for (var i = 0; i < master.playlists.length; i++) {
  34251. if (!master.playlists[i].uri) {
  34252. // Set up phony URIs for the playlists since playlists are referenced by their URIs
  34253. // throughout VHS, but some formats (e.g., DASH) don't have external URIs
  34254. // TODO: consider adding dummy URIs in mpd-parser
  34255. var phonyUri = "placeholder-uri-" + i;
  34256. master.playlists[i].uri = phonyUri;
  34257. }
  34258. }
  34259. var audioOnlyMaster = isAudioOnly(master);
  34260. forEachMediaGroup(master, function (properties, mediaType, groupKey, labelKey) {
  34261. // add a playlist array under properties
  34262. if (!properties.playlists || !properties.playlists.length) {
  34263. // If the manifest is audio only and this media group does not have a uri, check
  34264. // if the media group is located in the main list of playlists. If it is, don't add
  34265. // placeholder properties as it shouldn't be considered an alternate audio track.
  34266. if (audioOnlyMaster && mediaType === 'AUDIO' && !properties.uri) {
  34267. for (var _i = 0; _i < master.playlists.length; _i++) {
  34268. var p = master.playlists[_i];
  34269. if (p.attributes && p.attributes.AUDIO && p.attributes.AUDIO === groupKey) {
  34270. return;
  34271. }
  34272. }
  34273. }
  34274. properties.playlists = [_extends_1({}, properties)];
  34275. }
  34276. properties.playlists.forEach(function (p, i) {
  34277. var groupId = createGroupID(mediaType, groupKey, labelKey, p);
  34278. var id = createPlaylistID(i, groupId);
  34279. if (p.uri) {
  34280. p.resolvedUri = p.resolvedUri || resolveUrl(master.uri, p.uri);
  34281. } else {
  34282. // DEPRECATED, this has been added to prevent a breaking change.
  34283. // previously we only ever had a single media group playlist, so
  34284. // we mark the first playlist uri without prepending the index as we used to
  34285. // ideally we would do all of the playlists the same way.
  34286. p.uri = i === 0 ? groupId : id; // don't resolve a placeholder uri to an absolute url, just use
  34287. // the placeholder again
  34288. p.resolvedUri = p.uri;
  34289. }
  34290. p.id = p.id || id; // add an empty attributes object, all playlists are
  34291. // expected to have this.
  34292. p.attributes = p.attributes || {}; // setup ID and URI references (URI for backwards compatibility)
  34293. master.playlists[p.id] = p;
  34294. master.playlists[p.uri] = p;
  34295. });
  34296. });
  34297. setupMediaPlaylists(master);
  34298. resolveMediaGroupUris(master);
  34299. };
  34300. var mergeOptions$2 = videojs.mergeOptions,
  34301. EventTarget$1 = videojs.EventTarget;
  34302. var addLLHLSQueryDirectives = function addLLHLSQueryDirectives(uri, media) {
  34303. if (media.endList || !media.serverControl) {
  34304. return uri;
  34305. }
  34306. var parameters = {};
  34307. if (media.serverControl.canBlockReload) {
  34308. var preloadSegment = media.preloadSegment; // next msn is a zero based value, length is not.
  34309. var nextMSN = media.mediaSequence + media.segments.length; // If preload segment has parts then it is likely
  34310. // that we are going to request a part of that preload segment.
  34311. // the logic below is used to determine that.
  34312. if (preloadSegment) {
  34313. var parts = preloadSegment.parts || []; // _HLS_part is a zero based index
  34314. var nextPart = getKnownPartCount(media) - 1; // if nextPart is > -1 and not equal to just the
  34315. // length of parts, then we know we had part preload hints
  34316. // and we need to add the _HLS_part= query
  34317. if (nextPart > -1 && nextPart !== parts.length - 1) {
  34318. // add existing parts to our preload hints
  34319. // eslint-disable-next-line
  34320. parameters._HLS_part = nextPart;
  34321. } // this if statement makes sure that we request the msn
  34322. // of the preload segment if:
  34323. // 1. the preload segment had parts (and was not yet a full segment)
  34324. // but was added to our segments array
  34325. // 2. the preload segment had preload hints for parts that are not in
  34326. // the manifest yet.
  34327. // in all other cases we want the segment after the preload segment
  34328. // which will be given by using media.segments.length because it is 1 based
  34329. // rather than 0 based.
  34330. if (nextPart > -1 || parts.length) {
  34331. nextMSN--;
  34332. }
  34333. } // add _HLS_msn= in front of any _HLS_part query
  34334. // eslint-disable-next-line
  34335. parameters._HLS_msn = nextMSN;
  34336. }
  34337. if (media.serverControl && media.serverControl.canSkipUntil) {
  34338. // add _HLS_skip= infront of all other queries.
  34339. // eslint-disable-next-line
  34340. parameters._HLS_skip = media.serverControl.canSkipDateranges ? 'v2' : 'YES';
  34341. }
  34342. if (Object.keys(parameters).length) {
  34343. var parsedUri = new window.URL(uri);
  34344. ['_HLS_skip', '_HLS_msn', '_HLS_part'].forEach(function (name) {
  34345. if (!parameters.hasOwnProperty(name)) {
  34346. return;
  34347. }
  34348. parsedUri.searchParams.set(name, parameters[name]);
  34349. });
  34350. uri = parsedUri.toString();
  34351. }
  34352. return uri;
  34353. };
  34354. /**
  34355. * Returns a new segment object with properties and
  34356. * the parts array merged.
  34357. *
  34358. * @param {Object} a the old segment
  34359. * @param {Object} b the new segment
  34360. *
  34361. * @return {Object} the merged segment
  34362. */
  34363. var updateSegment = function updateSegment(a, b) {
  34364. if (!a) {
  34365. return b;
  34366. }
  34367. var result = mergeOptions$2(a, b); // if only the old segment has preload hints
  34368. // and the new one does not, remove preload hints.
  34369. if (a.preloadHints && !b.preloadHints) {
  34370. delete result.preloadHints;
  34371. } // if only the old segment has parts
  34372. // then the parts are no longer valid
  34373. if (a.parts && !b.parts) {
  34374. delete result.parts; // if both segments have parts
  34375. // copy part propeties from the old segment
  34376. // to the new one.
  34377. } else if (a.parts && b.parts) {
  34378. for (var i = 0; i < b.parts.length; i++) {
  34379. if (a.parts && a.parts[i]) {
  34380. result.parts[i] = mergeOptions$2(a.parts[i], b.parts[i]);
  34381. }
  34382. }
  34383. } // set skipped to false for segments that have
  34384. // have had information merged from the old segment.
  34385. if (!a.skipped && b.skipped) {
  34386. result.skipped = false;
  34387. } // set preload to false for segments that have
  34388. // had information added in the new segment.
  34389. if (a.preload && !b.preload) {
  34390. result.preload = false;
  34391. }
  34392. return result;
  34393. };
  34394. /**
  34395. * Returns a new array of segments that is the result of merging
  34396. * properties from an older list of segments onto an updated
  34397. * list. No properties on the updated playlist will be ovewritten.
  34398. *
  34399. * @param {Array} original the outdated list of segments
  34400. * @param {Array} update the updated list of segments
  34401. * @param {number=} offset the index of the first update
  34402. * segment in the original segment list. For non-live playlists,
  34403. * this should always be zero and does not need to be
  34404. * specified. For live playlists, it should be the difference
  34405. * between the media sequence numbers in the original and updated
  34406. * playlists.
  34407. * @return {Array} a list of merged segment objects
  34408. */
  34409. var updateSegments = function updateSegments(original, update, offset) {
  34410. var oldSegments = original.slice();
  34411. var newSegments = update.slice();
  34412. offset = offset || 0;
  34413. var result = [];
  34414. var currentMap;
  34415. for (var newIndex = 0; newIndex < newSegments.length; newIndex++) {
  34416. var oldSegment = oldSegments[newIndex + offset];
  34417. var newSegment = newSegments[newIndex];
  34418. if (oldSegment) {
  34419. currentMap = oldSegment.map || currentMap;
  34420. result.push(updateSegment(oldSegment, newSegment));
  34421. } else {
  34422. // carry over map to new segment if it is missing
  34423. if (currentMap && !newSegment.map) {
  34424. newSegment.map = currentMap;
  34425. }
  34426. result.push(newSegment);
  34427. }
  34428. }
  34429. return result;
  34430. };
  34431. var resolveSegmentUris = function resolveSegmentUris(segment, baseUri) {
  34432. // preloadSegment will not have a uri at all
  34433. // as the segment isn't actually in the manifest yet, only parts
  34434. if (!segment.resolvedUri && segment.uri) {
  34435. segment.resolvedUri = resolveUrl(baseUri, segment.uri);
  34436. }
  34437. if (segment.key && !segment.key.resolvedUri) {
  34438. segment.key.resolvedUri = resolveUrl(baseUri, segment.key.uri);
  34439. }
  34440. if (segment.map && !segment.map.resolvedUri) {
  34441. segment.map.resolvedUri = resolveUrl(baseUri, segment.map.uri);
  34442. }
  34443. if (segment.map && segment.map.key && !segment.map.key.resolvedUri) {
  34444. segment.map.key.resolvedUri = resolveUrl(baseUri, segment.map.key.uri);
  34445. }
  34446. if (segment.parts && segment.parts.length) {
  34447. segment.parts.forEach(function (p) {
  34448. if (p.resolvedUri) {
  34449. return;
  34450. }
  34451. p.resolvedUri = resolveUrl(baseUri, p.uri);
  34452. });
  34453. }
  34454. if (segment.preloadHints && segment.preloadHints.length) {
  34455. segment.preloadHints.forEach(function (p) {
  34456. if (p.resolvedUri) {
  34457. return;
  34458. }
  34459. p.resolvedUri = resolveUrl(baseUri, p.uri);
  34460. });
  34461. }
  34462. };
  34463. var getAllSegments = function getAllSegments(media) {
  34464. var segments = media.segments || [];
  34465. var preloadSegment = media.preloadSegment; // a preloadSegment with only preloadHints is not currently
  34466. // a usable segment, only include a preloadSegment that has
  34467. // parts.
  34468. if (preloadSegment && preloadSegment.parts && preloadSegment.parts.length) {
  34469. // if preloadHints has a MAP that means that the
  34470. // init segment is going to change. We cannot use any of the parts
  34471. // from this preload segment.
  34472. if (preloadSegment.preloadHints) {
  34473. for (var i = 0; i < preloadSegment.preloadHints.length; i++) {
  34474. if (preloadSegment.preloadHints[i].type === 'MAP') {
  34475. return segments;
  34476. }
  34477. }
  34478. } // set the duration for our preload segment to target duration.
  34479. preloadSegment.duration = media.targetDuration;
  34480. preloadSegment.preload = true;
  34481. segments.push(preloadSegment);
  34482. }
  34483. return segments;
  34484. }; // consider the playlist unchanged if the playlist object is the same or
  34485. // the number of segments is equal, the media sequence number is unchanged,
  34486. // and this playlist hasn't become the end of the playlist
  34487. var isPlaylistUnchanged = function isPlaylistUnchanged(a, b) {
  34488. 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;
  34489. };
  34490. /**
  34491. * Returns a new master playlist that is the result of merging an
  34492. * updated media playlist into the original version. If the
  34493. * updated media playlist does not match any of the playlist
  34494. * entries in the original master playlist, null is returned.
  34495. *
  34496. * @param {Object} master a parsed master M3U8 object
  34497. * @param {Object} media a parsed media M3U8 object
  34498. * @return {Object} a new object that represents the original
  34499. * master playlist with the updated media playlist merged in, or
  34500. * null if the merge produced no change.
  34501. */
  34502. var updateMaster$1 = function updateMaster(master, newMedia, unchangedCheck) {
  34503. if (unchangedCheck === void 0) {
  34504. unchangedCheck = isPlaylistUnchanged;
  34505. }
  34506. var result = mergeOptions$2(master, {});
  34507. var oldMedia = result.playlists[newMedia.id];
  34508. if (!oldMedia) {
  34509. return null;
  34510. }
  34511. if (unchangedCheck(oldMedia, newMedia)) {
  34512. return null;
  34513. }
  34514. newMedia.segments = getAllSegments(newMedia);
  34515. var mergedPlaylist = mergeOptions$2(oldMedia, newMedia); // always use the new media's preload segment
  34516. if (mergedPlaylist.preloadSegment && !newMedia.preloadSegment) {
  34517. delete mergedPlaylist.preloadSegment;
  34518. } // if the update could overlap existing segment information, merge the two segment lists
  34519. if (oldMedia.segments) {
  34520. if (newMedia.skip) {
  34521. newMedia.segments = newMedia.segments || []; // add back in objects for skipped segments, so that we merge
  34522. // old properties into the new segments
  34523. for (var i = 0; i < newMedia.skip.skippedSegments; i++) {
  34524. newMedia.segments.unshift({
  34525. skipped: true
  34526. });
  34527. }
  34528. }
  34529. mergedPlaylist.segments = updateSegments(oldMedia.segments, newMedia.segments, newMedia.mediaSequence - oldMedia.mediaSequence);
  34530. } // resolve any segment URIs to prevent us from having to do it later
  34531. mergedPlaylist.segments.forEach(function (segment) {
  34532. resolveSegmentUris(segment, mergedPlaylist.resolvedUri);
  34533. }); // TODO Right now in the playlists array there are two references to each playlist, one
  34534. // that is referenced by index, and one by URI. The index reference may no longer be
  34535. // necessary.
  34536. for (var _i = 0; _i < result.playlists.length; _i++) {
  34537. if (result.playlists[_i].id === newMedia.id) {
  34538. result.playlists[_i] = mergedPlaylist;
  34539. }
  34540. }
  34541. result.playlists[newMedia.id] = mergedPlaylist; // URI reference added for backwards compatibility
  34542. result.playlists[newMedia.uri] = mergedPlaylist; // update media group playlist references.
  34543. forEachMediaGroup(master, function (properties, mediaType, groupKey, labelKey) {
  34544. if (!properties.playlists) {
  34545. return;
  34546. }
  34547. for (var _i2 = 0; _i2 < properties.playlists.length; _i2++) {
  34548. if (newMedia.id === properties.playlists[_i2].id) {
  34549. properties.playlists[_i2] = mergedPlaylist;
  34550. }
  34551. }
  34552. });
  34553. return result;
  34554. };
  34555. /**
  34556. * Calculates the time to wait before refreshing a live playlist
  34557. *
  34558. * @param {Object} media
  34559. * The current media
  34560. * @param {boolean} update
  34561. * True if there were any updates from the last refresh, false otherwise
  34562. * @return {number}
  34563. * The time in ms to wait before refreshing the live playlist
  34564. */
  34565. var refreshDelay = function refreshDelay(media, update) {
  34566. var segments = media.segments || [];
  34567. var lastSegment = segments[segments.length - 1];
  34568. var lastPart = lastSegment && lastSegment.parts && lastSegment.parts[lastSegment.parts.length - 1];
  34569. var lastDuration = lastPart && lastPart.duration || lastSegment && lastSegment.duration;
  34570. if (update && lastDuration) {
  34571. return lastDuration * 1000;
  34572. } // if the playlist is unchanged since the last reload or last segment duration
  34573. // cannot be determined, try again after half the target duration
  34574. return (media.partTargetDuration || media.targetDuration || 10) * 500;
  34575. };
  34576. /**
  34577. * Load a playlist from a remote location
  34578. *
  34579. * @class PlaylistLoader
  34580. * @extends Stream
  34581. * @param {string|Object} src url or object of manifest
  34582. * @param {boolean} withCredentials the withCredentials xhr option
  34583. * @class
  34584. */
  34585. var PlaylistLoader = /*#__PURE__*/function (_EventTarget) {
  34586. inheritsLoose(PlaylistLoader, _EventTarget);
  34587. function PlaylistLoader(src, vhs, options) {
  34588. var _this;
  34589. if (options === void 0) {
  34590. options = {};
  34591. }
  34592. _this = _EventTarget.call(this) || this;
  34593. if (!src) {
  34594. throw new Error('A non-empty playlist URL or object is required');
  34595. }
  34596. _this.logger_ = logger('PlaylistLoader');
  34597. var _options = options,
  34598. _options$withCredenti = _options.withCredentials,
  34599. withCredentials = _options$withCredenti === void 0 ? false : _options$withCredenti,
  34600. _options$handleManife = _options.handleManifestRedirects,
  34601. handleManifestRedirects = _options$handleManife === void 0 ? false : _options$handleManife;
  34602. _this.src = src;
  34603. _this.vhs_ = vhs;
  34604. _this.withCredentials = withCredentials;
  34605. _this.handleManifestRedirects = handleManifestRedirects;
  34606. var vhsOptions = vhs.options_;
  34607. _this.customTagParsers = vhsOptions && vhsOptions.customTagParsers || [];
  34608. _this.customTagMappers = vhsOptions && vhsOptions.customTagMappers || [];
  34609. _this.experimentalLLHLS = vhsOptions && vhsOptions.experimentalLLHLS || false; // force experimentalLLHLS for IE 11
  34610. if (videojs.browser.IE_VERSION) {
  34611. _this.experimentalLLHLS = false;
  34612. } // initialize the loader state
  34613. _this.state = 'HAVE_NOTHING'; // live playlist staleness timeout
  34614. _this.handleMediaupdatetimeout_ = _this.handleMediaupdatetimeout_.bind(assertThisInitialized(_this));
  34615. _this.on('mediaupdatetimeout', _this.handleMediaupdatetimeout_);
  34616. return _this;
  34617. }
  34618. var _proto = PlaylistLoader.prototype;
  34619. _proto.handleMediaupdatetimeout_ = function handleMediaupdatetimeout_() {
  34620. var _this2 = this;
  34621. if (this.state !== 'HAVE_METADATA') {
  34622. // only refresh the media playlist if no other activity is going on
  34623. return;
  34624. }
  34625. var media = this.media();
  34626. var uri = resolveUrl(this.master.uri, media.uri);
  34627. if (this.experimentalLLHLS) {
  34628. uri = addLLHLSQueryDirectives(uri, media);
  34629. }
  34630. this.state = 'HAVE_CURRENT_METADATA';
  34631. this.request = this.vhs_.xhr({
  34632. uri: uri,
  34633. withCredentials: this.withCredentials
  34634. }, function (error, req) {
  34635. // disposed
  34636. if (!_this2.request) {
  34637. return;
  34638. }
  34639. if (error) {
  34640. return _this2.playlistRequestError(_this2.request, _this2.media(), 'HAVE_METADATA');
  34641. }
  34642. _this2.haveMetadata({
  34643. playlistString: _this2.request.responseText,
  34644. url: _this2.media().uri,
  34645. id: _this2.media().id
  34646. });
  34647. });
  34648. };
  34649. _proto.playlistRequestError = function playlistRequestError(xhr, playlist, startingState) {
  34650. var uri = playlist.uri,
  34651. id = playlist.id; // any in-flight request is now finished
  34652. this.request = null;
  34653. if (startingState) {
  34654. this.state = startingState;
  34655. }
  34656. this.error = {
  34657. playlist: this.master.playlists[id],
  34658. status: xhr.status,
  34659. message: "HLS playlist request error at URL: " + uri + ".",
  34660. responseText: xhr.responseText,
  34661. code: xhr.status >= 500 ? 4 : 2
  34662. };
  34663. this.trigger('error');
  34664. };
  34665. _proto.parseManifest_ = function parseManifest_(_ref) {
  34666. var _this3 = this;
  34667. var url = _ref.url,
  34668. manifestString = _ref.manifestString;
  34669. return parseManifest({
  34670. onwarn: function onwarn(_ref2) {
  34671. var message = _ref2.message;
  34672. return _this3.logger_("m3u8-parser warn for " + url + ": " + message);
  34673. },
  34674. oninfo: function oninfo(_ref3) {
  34675. var message = _ref3.message;
  34676. return _this3.logger_("m3u8-parser info for " + url + ": " + message);
  34677. },
  34678. manifestString: manifestString,
  34679. customTagParsers: this.customTagParsers,
  34680. customTagMappers: this.customTagMappers,
  34681. experimentalLLHLS: this.experimentalLLHLS
  34682. });
  34683. }
  34684. /**
  34685. * Update the playlist loader's state in response to a new or updated playlist.
  34686. *
  34687. * @param {string} [playlistString]
  34688. * Playlist string (if playlistObject is not provided)
  34689. * @param {Object} [playlistObject]
  34690. * Playlist object (if playlistString is not provided)
  34691. * @param {string} url
  34692. * URL of playlist
  34693. * @param {string} id
  34694. * ID to use for playlist
  34695. */
  34696. ;
  34697. _proto.haveMetadata = function haveMetadata(_ref4) {
  34698. var playlistString = _ref4.playlistString,
  34699. playlistObject = _ref4.playlistObject,
  34700. url = _ref4.url,
  34701. id = _ref4.id; // any in-flight request is now finished
  34702. this.request = null;
  34703. this.state = 'HAVE_METADATA';
  34704. var playlist = playlistObject || this.parseManifest_({
  34705. url: url,
  34706. manifestString: playlistString
  34707. });
  34708. playlist.lastRequest = Date.now();
  34709. setupMediaPlaylist({
  34710. playlist: playlist,
  34711. uri: url,
  34712. id: id
  34713. }); // merge this playlist into the master
  34714. var update = updateMaster$1(this.master, playlist);
  34715. this.targetDuration = playlist.partTargetDuration || playlist.targetDuration;
  34716. this.pendingMedia_ = null;
  34717. if (update) {
  34718. this.master = update;
  34719. this.media_ = this.master.playlists[id];
  34720. } else {
  34721. this.trigger('playlistunchanged');
  34722. }
  34723. this.updateMediaUpdateTimeout_(refreshDelay(this.media(), !!update));
  34724. this.trigger('loadedplaylist');
  34725. }
  34726. /**
  34727. * Abort any outstanding work and clean up.
  34728. */
  34729. ;
  34730. _proto.dispose = function dispose() {
  34731. this.trigger('dispose');
  34732. this.stopRequest();
  34733. window.clearTimeout(this.mediaUpdateTimeout);
  34734. window.clearTimeout(this.finalRenditionTimeout);
  34735. this.off();
  34736. };
  34737. _proto.stopRequest = function stopRequest() {
  34738. if (this.request) {
  34739. var oldRequest = this.request;
  34740. this.request = null;
  34741. oldRequest.onreadystatechange = null;
  34742. oldRequest.abort();
  34743. }
  34744. }
  34745. /**
  34746. * When called without any arguments, returns the currently
  34747. * active media playlist. When called with a single argument,
  34748. * triggers the playlist loader to asynchronously switch to the
  34749. * specified media playlist. Calling this method while the
  34750. * loader is in the HAVE_NOTHING causes an error to be emitted
  34751. * but otherwise has no effect.
  34752. *
  34753. * @param {Object=} playlist the parsed media playlist
  34754. * object to switch to
  34755. * @param {boolean=} shouldDelay whether we should delay the request by half target duration
  34756. *
  34757. * @return {Playlist} the current loaded media
  34758. */
  34759. ;
  34760. _proto.media = function media(playlist, shouldDelay) {
  34761. var _this4 = this; // getter
  34762. if (!playlist) {
  34763. return this.media_;
  34764. } // setter
  34765. if (this.state === 'HAVE_NOTHING') {
  34766. throw new Error('Cannot switch media playlist from ' + this.state);
  34767. } // find the playlist object if the target playlist has been
  34768. // specified by URI
  34769. if (typeof playlist === 'string') {
  34770. if (!this.master.playlists[playlist]) {
  34771. throw new Error('Unknown playlist URI: ' + playlist);
  34772. }
  34773. playlist = this.master.playlists[playlist];
  34774. }
  34775. window.clearTimeout(this.finalRenditionTimeout);
  34776. if (shouldDelay) {
  34777. var delay = (playlist.partTargetDuration || playlist.targetDuration) / 2 * 1000 || 5 * 1000;
  34778. this.finalRenditionTimeout = window.setTimeout(this.media.bind(this, playlist, false), delay);
  34779. return;
  34780. }
  34781. var startingState = this.state;
  34782. var mediaChange = !this.media_ || playlist.id !== this.media_.id;
  34783. var masterPlaylistRef = this.master.playlists[playlist.id]; // switch to fully loaded playlists immediately
  34784. if (masterPlaylistRef && masterPlaylistRef.endList || // handle the case of a playlist object (e.g., if using vhs-json with a resolved
  34785. // media playlist or, for the case of demuxed audio, a resolved audio media group)
  34786. playlist.endList && playlist.segments.length) {
  34787. // abort outstanding playlist requests
  34788. if (this.request) {
  34789. this.request.onreadystatechange = null;
  34790. this.request.abort();
  34791. this.request = null;
  34792. }
  34793. this.state = 'HAVE_METADATA';
  34794. this.media_ = playlist; // trigger media change if the active media has been updated
  34795. if (mediaChange) {
  34796. this.trigger('mediachanging');
  34797. if (startingState === 'HAVE_MASTER') {
  34798. // The initial playlist was a master manifest, and the first media selected was
  34799. // also provided (in the form of a resolved playlist object) as part of the
  34800. // source object (rather than just a URL). Therefore, since the media playlist
  34801. // doesn't need to be requested, loadedmetadata won't trigger as part of the
  34802. // normal flow, and needs an explicit trigger here.
  34803. this.trigger('loadedmetadata');
  34804. } else {
  34805. this.trigger('mediachange');
  34806. }
  34807. }
  34808. return;
  34809. } // We update/set the timeout here so that live playlists
  34810. // that are not a media change will "start" the loader as expected.
  34811. // We expect that this function will start the media update timeout
  34812. // cycle again. This also prevents a playlist switch failure from
  34813. // causing us to stall during live.
  34814. this.updateMediaUpdateTimeout_(refreshDelay(playlist, true)); // switching to the active playlist is a no-op
  34815. if (!mediaChange) {
  34816. return;
  34817. }
  34818. this.state = 'SWITCHING_MEDIA'; // there is already an outstanding playlist request
  34819. if (this.request) {
  34820. if (playlist.resolvedUri === this.request.url) {
  34821. // requesting to switch to the same playlist multiple times
  34822. // has no effect after the first
  34823. return;
  34824. }
  34825. this.request.onreadystatechange = null;
  34826. this.request.abort();
  34827. this.request = null;
  34828. } // request the new playlist
  34829. if (this.media_) {
  34830. this.trigger('mediachanging');
  34831. }
  34832. this.pendingMedia_ = playlist;
  34833. this.request = this.vhs_.xhr({
  34834. uri: playlist.resolvedUri,
  34835. withCredentials: this.withCredentials
  34836. }, function (error, req) {
  34837. // disposed
  34838. if (!_this4.request) {
  34839. return;
  34840. }
  34841. playlist.lastRequest = Date.now();
  34842. playlist.resolvedUri = resolveManifestRedirect(_this4.handleManifestRedirects, playlist.resolvedUri, req);
  34843. if (error) {
  34844. return _this4.playlistRequestError(_this4.request, playlist, startingState);
  34845. }
  34846. _this4.haveMetadata({
  34847. playlistString: req.responseText,
  34848. url: playlist.uri,
  34849. id: playlist.id
  34850. }); // fire loadedmetadata the first time a media playlist is loaded
  34851. if (startingState === 'HAVE_MASTER') {
  34852. _this4.trigger('loadedmetadata');
  34853. } else {
  34854. _this4.trigger('mediachange');
  34855. }
  34856. });
  34857. }
  34858. /**
  34859. * pause loading of the playlist
  34860. */
  34861. ;
  34862. _proto.pause = function pause() {
  34863. if (this.mediaUpdateTimeout) {
  34864. window.clearTimeout(this.mediaUpdateTimeout);
  34865. this.mediaUpdateTimeout = null;
  34866. }
  34867. this.stopRequest();
  34868. if (this.state === 'HAVE_NOTHING') {
  34869. // If we pause the loader before any data has been retrieved, its as if we never
  34870. // started, so reset to an unstarted state.
  34871. this.started = false;
  34872. } // Need to restore state now that no activity is happening
  34873. if (this.state === 'SWITCHING_MEDIA') {
  34874. // if the loader was in the process of switching media, it should either return to
  34875. // HAVE_MASTER or HAVE_METADATA depending on if the loader has loaded a media
  34876. // playlist yet. This is determined by the existence of loader.media_
  34877. if (this.media_) {
  34878. this.state = 'HAVE_METADATA';
  34879. } else {
  34880. this.state = 'HAVE_MASTER';
  34881. }
  34882. } else if (this.state === 'HAVE_CURRENT_METADATA') {
  34883. this.state = 'HAVE_METADATA';
  34884. }
  34885. }
  34886. /**
  34887. * start loading of the playlist
  34888. */
  34889. ;
  34890. _proto.load = function load(shouldDelay) {
  34891. var _this5 = this;
  34892. if (this.mediaUpdateTimeout) {
  34893. window.clearTimeout(this.mediaUpdateTimeout);
  34894. this.mediaUpdateTimeout = null;
  34895. }
  34896. var media = this.media();
  34897. if (shouldDelay) {
  34898. var delay = media ? (media.partTargetDuration || media.targetDuration) / 2 * 1000 : 5 * 1000;
  34899. this.mediaUpdateTimeout = window.setTimeout(function () {
  34900. _this5.mediaUpdateTimeout = null;
  34901. _this5.load();
  34902. }, delay);
  34903. return;
  34904. }
  34905. if (!this.started) {
  34906. this.start();
  34907. return;
  34908. }
  34909. if (media && !media.endList) {
  34910. this.trigger('mediaupdatetimeout');
  34911. } else {
  34912. this.trigger('loadedplaylist');
  34913. }
  34914. };
  34915. _proto.updateMediaUpdateTimeout_ = function updateMediaUpdateTimeout_(delay) {
  34916. var _this6 = this;
  34917. if (this.mediaUpdateTimeout) {
  34918. window.clearTimeout(this.mediaUpdateTimeout);
  34919. this.mediaUpdateTimeout = null;
  34920. } // we only have use mediaupdatetimeout for live playlists.
  34921. if (!this.media() || this.media().endList) {
  34922. return;
  34923. }
  34924. this.mediaUpdateTimeout = window.setTimeout(function () {
  34925. _this6.mediaUpdateTimeout = null;
  34926. _this6.trigger('mediaupdatetimeout');
  34927. _this6.updateMediaUpdateTimeout_(delay);
  34928. }, delay);
  34929. }
  34930. /**
  34931. * start loading of the playlist
  34932. */
  34933. ;
  34934. _proto.start = function start() {
  34935. var _this7 = this;
  34936. this.started = true;
  34937. if (typeof this.src === 'object') {
  34938. // in the case of an entirely constructed manifest object (meaning there's no actual
  34939. // manifest on a server), default the uri to the page's href
  34940. if (!this.src.uri) {
  34941. this.src.uri = window.location.href;
  34942. } // resolvedUri is added on internally after the initial request. Since there's no
  34943. // request for pre-resolved manifests, add on resolvedUri here.
  34944. this.src.resolvedUri = this.src.uri; // Since a manifest object was passed in as the source (instead of a URL), the first
  34945. // request can be skipped (since the top level of the manifest, at a minimum, is
  34946. // already available as a parsed manifest object). However, if the manifest object
  34947. // represents a master playlist, some media playlists may need to be resolved before
  34948. // the starting segment list is available. Therefore, go directly to setup of the
  34949. // initial playlist, and let the normal flow continue from there.
  34950. //
  34951. // Note that the call to setup is asynchronous, as other sections of VHS may assume
  34952. // that the first request is asynchronous.
  34953. setTimeout(function () {
  34954. _this7.setupInitialPlaylist(_this7.src);
  34955. }, 0);
  34956. return;
  34957. } // request the specified URL
  34958. this.request = this.vhs_.xhr({
  34959. uri: this.src,
  34960. withCredentials: this.withCredentials
  34961. }, function (error, req) {
  34962. // disposed
  34963. if (!_this7.request) {
  34964. return;
  34965. } // clear the loader's request reference
  34966. _this7.request = null;
  34967. if (error) {
  34968. _this7.error = {
  34969. status: req.status,
  34970. message: "HLS playlist request error at URL: " + _this7.src + ".",
  34971. responseText: req.responseText,
  34972. // MEDIA_ERR_NETWORK
  34973. code: 2
  34974. };
  34975. if (_this7.state === 'HAVE_NOTHING') {
  34976. _this7.started = false;
  34977. }
  34978. return _this7.trigger('error');
  34979. }
  34980. _this7.src = resolveManifestRedirect(_this7.handleManifestRedirects, _this7.src, req);
  34981. var manifest = _this7.parseManifest_({
  34982. manifestString: req.responseText,
  34983. url: _this7.src
  34984. });
  34985. _this7.setupInitialPlaylist(manifest);
  34986. });
  34987. };
  34988. _proto.srcUri = function srcUri() {
  34989. return typeof this.src === 'string' ? this.src : this.src.uri;
  34990. }
  34991. /**
  34992. * Given a manifest object that's either a master or media playlist, trigger the proper
  34993. * events and set the state of the playlist loader.
  34994. *
  34995. * If the manifest object represents a master playlist, `loadedplaylist` will be
  34996. * triggered to allow listeners to select a playlist. If none is selected, the loader
  34997. * will default to the first one in the playlists array.
  34998. *
  34999. * If the manifest object represents a media playlist, `loadedplaylist` will be
  35000. * triggered followed by `loadedmetadata`, as the only available playlist is loaded.
  35001. *
  35002. * In the case of a media playlist, a master playlist object wrapper with one playlist
  35003. * will be created so that all logic can handle playlists in the same fashion (as an
  35004. * assumed manifest object schema).
  35005. *
  35006. * @param {Object} manifest
  35007. * The parsed manifest object
  35008. */
  35009. ;
  35010. _proto.setupInitialPlaylist = function setupInitialPlaylist(manifest) {
  35011. this.state = 'HAVE_MASTER';
  35012. if (manifest.playlists) {
  35013. this.master = manifest;
  35014. addPropertiesToMaster(this.master, this.srcUri()); // If the initial master playlist has playlists wtih segments already resolved,
  35015. // then resolve URIs in advance, as they are usually done after a playlist request,
  35016. // which may not happen if the playlist is resolved.
  35017. manifest.playlists.forEach(function (playlist) {
  35018. playlist.segments = getAllSegments(playlist);
  35019. playlist.segments.forEach(function (segment) {
  35020. resolveSegmentUris(segment, playlist.resolvedUri);
  35021. });
  35022. });
  35023. this.trigger('loadedplaylist');
  35024. if (!this.request) {
  35025. // no media playlist was specifically selected so start
  35026. // from the first listed one
  35027. this.media(this.master.playlists[0]);
  35028. }
  35029. return;
  35030. } // In order to support media playlists passed in as vhs-json, the case where the uri
  35031. // is not provided as part of the manifest should be considered, and an appropriate
  35032. // default used.
  35033. var uri = this.srcUri() || window.location.href;
  35034. this.master = masterForMedia(manifest, uri);
  35035. this.haveMetadata({
  35036. playlistObject: manifest,
  35037. url: uri,
  35038. id: this.master.playlists[0].id
  35039. });
  35040. this.trigger('loadedmetadata');
  35041. };
  35042. return PlaylistLoader;
  35043. }(EventTarget$1);
  35044. /**
  35045. * @file xhr.js
  35046. */
  35047. var videojsXHR = videojs.xhr,
  35048. mergeOptions$1 = videojs.mergeOptions;
  35049. var callbackWrapper = function callbackWrapper(request, error, response, callback) {
  35050. var reqResponse = request.responseType === 'arraybuffer' ? request.response : request.responseText;
  35051. if (!error && reqResponse) {
  35052. request.responseTime = Date.now();
  35053. request.roundTripTime = request.responseTime - request.requestTime;
  35054. request.bytesReceived = reqResponse.byteLength || reqResponse.length;
  35055. if (!request.bandwidth) {
  35056. request.bandwidth = Math.floor(request.bytesReceived / request.roundTripTime * 8 * 1000);
  35057. }
  35058. }
  35059. if (response.headers) {
  35060. request.responseHeaders = response.headers;
  35061. } // videojs.xhr now uses a specific code on the error
  35062. // object to signal that a request has timed out instead
  35063. // of setting a boolean on the request object
  35064. if (error && error.code === 'ETIMEDOUT') {
  35065. request.timedout = true;
  35066. } // videojs.xhr no longer considers status codes outside of 200 and 0
  35067. // (for file uris) to be errors, but the old XHR did, so emulate that
  35068. // behavior. Status 206 may be used in response to byterange requests.
  35069. if (!error && !request.aborted && response.statusCode !== 200 && response.statusCode !== 206 && response.statusCode !== 0) {
  35070. error = new Error('XHR Failed with a response of: ' + (request && (reqResponse || request.responseText)));
  35071. }
  35072. callback(error, request);
  35073. };
  35074. var xhrFactory = function xhrFactory() {
  35075. var xhr = function XhrFunction(options, callback) {
  35076. // Add a default timeout
  35077. options = mergeOptions$1({
  35078. timeout: 45e3
  35079. }, options); // Allow an optional user-specified function to modify the option
  35080. // object before we construct the xhr request
  35081. var beforeRequest = XhrFunction.beforeRequest || videojs.Vhs.xhr.beforeRequest;
  35082. if (beforeRequest && typeof beforeRequest === 'function') {
  35083. var newOptions = beforeRequest(options);
  35084. if (newOptions) {
  35085. options = newOptions;
  35086. }
  35087. } // Use the standard videojs.xhr() method unless `videojs.Vhs.xhr` has been overriden
  35088. // TODO: switch back to videojs.Vhs.xhr.name === 'XhrFunction' when we drop IE11
  35089. var xhrMethod = videojs.Vhs.xhr.original === true ? videojsXHR : videojs.Vhs.xhr;
  35090. var request = xhrMethod(options, function (error, response) {
  35091. return callbackWrapper(request, error, response, callback);
  35092. });
  35093. var originalAbort = request.abort;
  35094. request.abort = function () {
  35095. request.aborted = true;
  35096. return originalAbort.apply(request, arguments);
  35097. };
  35098. request.uri = options.uri;
  35099. request.requestTime = Date.now();
  35100. return request;
  35101. };
  35102. xhr.original = true;
  35103. return xhr;
  35104. };
  35105. /**
  35106. * Turns segment byterange into a string suitable for use in
  35107. * HTTP Range requests
  35108. *
  35109. * @param {Object} byterange - an object with two values defining the start and end
  35110. * of a byte-range
  35111. */
  35112. var byterangeStr = function byterangeStr(byterange) {
  35113. // `byterangeEnd` is one less than `offset + length` because the HTTP range
  35114. // header uses inclusive ranges
  35115. var byterangeEnd;
  35116. var byterangeStart = byterange.offset;
  35117. if (typeof byterange.offset === 'bigint' || typeof byterange.length === 'bigint') {
  35118. byterangeEnd = window.BigInt(byterange.offset) + window.BigInt(byterange.length) - window.BigInt(1);
  35119. } else {
  35120. byterangeEnd = byterange.offset + byterange.length - 1;
  35121. }
  35122. return 'bytes=' + byterangeStart + '-' + byterangeEnd;
  35123. };
  35124. /**
  35125. * Defines headers for use in the xhr request for a particular segment.
  35126. *
  35127. * @param {Object} segment - a simplified copy of the segmentInfo object
  35128. * from SegmentLoader
  35129. */
  35130. var segmentXhrHeaders = function segmentXhrHeaders(segment) {
  35131. var headers = {};
  35132. if (segment.byterange) {
  35133. headers.Range = byterangeStr(segment.byterange);
  35134. }
  35135. return headers;
  35136. };
  35137. /**
  35138. * @file bin-utils.js
  35139. */
  35140. /**
  35141. * convert a TimeRange to text
  35142. *
  35143. * @param {TimeRange} range the timerange to use for conversion
  35144. * @param {number} i the iterator on the range to convert
  35145. * @return {string} the range in string format
  35146. */
  35147. var textRange = function textRange(range, i) {
  35148. return range.start(i) + '-' + range.end(i);
  35149. };
  35150. /**
  35151. * format a number as hex string
  35152. *
  35153. * @param {number} e The number
  35154. * @param {number} i the iterator
  35155. * @return {string} the hex formatted number as a string
  35156. */
  35157. var formatHexString = function formatHexString(e, i) {
  35158. var value = e.toString(16);
  35159. return '00'.substring(0, 2 - value.length) + value + (i % 2 ? ' ' : '');
  35160. };
  35161. var formatAsciiString = function formatAsciiString(e) {
  35162. if (e >= 0x20 && e < 0x7e) {
  35163. return String.fromCharCode(e);
  35164. }
  35165. return '.';
  35166. };
  35167. /**
  35168. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  35169. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  35170. *
  35171. * @param {Object} message
  35172. * Object of properties and values to send to the web worker
  35173. * @return {Object}
  35174. * Modified message with TypedArray values expanded
  35175. * @function createTransferableMessage
  35176. */
  35177. var createTransferableMessage = function createTransferableMessage(message) {
  35178. var transferable = {};
  35179. Object.keys(message).forEach(function (key) {
  35180. var value = message[key];
  35181. if (isArrayBufferView(value)) {
  35182. transferable[key] = {
  35183. bytes: value.buffer,
  35184. byteOffset: value.byteOffset,
  35185. byteLength: value.byteLength
  35186. };
  35187. } else {
  35188. transferable[key] = value;
  35189. }
  35190. });
  35191. return transferable;
  35192. };
  35193. /**
  35194. * Returns a unique string identifier for a media initialization
  35195. * segment.
  35196. *
  35197. * @param {Object} initSegment
  35198. * the init segment object.
  35199. *
  35200. * @return {string} the generated init segment id
  35201. */
  35202. var initSegmentId = function initSegmentId(initSegment) {
  35203. var byterange = initSegment.byterange || {
  35204. length: Infinity,
  35205. offset: 0
  35206. };
  35207. return [byterange.length, byterange.offset, initSegment.resolvedUri].join(',');
  35208. };
  35209. /**
  35210. * Returns a unique string identifier for a media segment key.
  35211. *
  35212. * @param {Object} key the encryption key
  35213. * @return {string} the unique id for the media segment key.
  35214. */
  35215. var segmentKeyId = function segmentKeyId(key) {
  35216. return key.resolvedUri;
  35217. };
  35218. /**
  35219. * utils to help dump binary data to the console
  35220. *
  35221. * @param {Array|TypedArray} data
  35222. * data to dump to a string
  35223. *
  35224. * @return {string} the data as a hex string.
  35225. */
  35226. var hexDump = function hexDump(data) {
  35227. var bytes = Array.prototype.slice.call(data);
  35228. var step = 16;
  35229. var result = '';
  35230. var hex;
  35231. var ascii;
  35232. for (var j = 0; j < bytes.length / step; j++) {
  35233. hex = bytes.slice(j * step, j * step + step).map(formatHexString).join('');
  35234. ascii = bytes.slice(j * step, j * step + step).map(formatAsciiString).join('');
  35235. result += hex + ' ' + ascii + '\n';
  35236. }
  35237. return result;
  35238. };
  35239. var tagDump = function tagDump(_ref) {
  35240. var bytes = _ref.bytes;
  35241. return hexDump(bytes);
  35242. };
  35243. var textRanges = function textRanges(ranges) {
  35244. var result = '';
  35245. var i;
  35246. for (i = 0; i < ranges.length; i++) {
  35247. result += textRange(ranges, i) + ' ';
  35248. }
  35249. return result;
  35250. };
  35251. var utils = /*#__PURE__*/Object.freeze({
  35252. __proto__: null,
  35253. createTransferableMessage: createTransferableMessage,
  35254. initSegmentId: initSegmentId,
  35255. segmentKeyId: segmentKeyId,
  35256. hexDump: hexDump,
  35257. tagDump: tagDump,
  35258. textRanges: textRanges
  35259. }); // TODO handle fmp4 case where the timing info is accurate and doesn't involve transmux
  35260. // 25% was arbitrarily chosen, and may need to be refined over time.
  35261. var SEGMENT_END_FUDGE_PERCENT = 0.25;
  35262. /**
  35263. * Converts a player time (any time that can be gotten/set from player.currentTime(),
  35264. * e.g., any time within player.seekable().start(0) to player.seekable().end(0)) to a
  35265. * program time (any time referencing the real world (e.g., EXT-X-PROGRAM-DATE-TIME)).
  35266. *
  35267. * The containing segment is required as the EXT-X-PROGRAM-DATE-TIME serves as an "anchor
  35268. * point" (a point where we have a mapping from program time to player time, with player
  35269. * time being the post transmux start of the segment).
  35270. *
  35271. * For more details, see [this doc](../../docs/program-time-from-player-time.md).
  35272. *
  35273. * @param {number} playerTime the player time
  35274. * @param {Object} segment the segment which contains the player time
  35275. * @return {Date} program time
  35276. */
  35277. var playerTimeToProgramTime = function playerTimeToProgramTime(playerTime, segment) {
  35278. if (!segment.dateTimeObject) {
  35279. // Can't convert without an "anchor point" for the program time (i.e., a time that can
  35280. // be used to map the start of a segment with a real world time).
  35281. return null;
  35282. }
  35283. var transmuxerPrependedSeconds = segment.videoTimingInfo.transmuxerPrependedSeconds;
  35284. var transmuxedStart = segment.videoTimingInfo.transmuxedPresentationStart; // get the start of the content from before old content is prepended
  35285. var startOfSegment = transmuxedStart + transmuxerPrependedSeconds;
  35286. var offsetFromSegmentStart = playerTime - startOfSegment;
  35287. return new Date(segment.dateTimeObject.getTime() + offsetFromSegmentStart * 1000);
  35288. };
  35289. var originalSegmentVideoDuration = function originalSegmentVideoDuration(videoTimingInfo) {
  35290. return videoTimingInfo.transmuxedPresentationEnd - videoTimingInfo.transmuxedPresentationStart - videoTimingInfo.transmuxerPrependedSeconds;
  35291. };
  35292. /**
  35293. * Finds a segment that contains the time requested given as an ISO-8601 string. The
  35294. * returned segment might be an estimate or an accurate match.
  35295. *
  35296. * @param {string} programTime The ISO-8601 programTime to find a match for
  35297. * @param {Object} playlist A playlist object to search within
  35298. */
  35299. var findSegmentForProgramTime = function findSegmentForProgramTime(programTime, playlist) {
  35300. // Assumptions:
  35301. // - verifyProgramDateTimeTags has already been run
  35302. // - live streams have been started
  35303. var dateTimeObject;
  35304. try {
  35305. dateTimeObject = new Date(programTime);
  35306. } catch (e) {
  35307. return null;
  35308. }
  35309. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  35310. return null;
  35311. }
  35312. var segment = playlist.segments[0];
  35313. if (dateTimeObject < segment.dateTimeObject) {
  35314. // Requested time is before stream start.
  35315. return null;
  35316. }
  35317. for (var i = 0; i < playlist.segments.length - 1; i++) {
  35318. segment = playlist.segments[i];
  35319. var nextSegmentStart = playlist.segments[i + 1].dateTimeObject;
  35320. if (dateTimeObject < nextSegmentStart) {
  35321. break;
  35322. }
  35323. }
  35324. var lastSegment = playlist.segments[playlist.segments.length - 1];
  35325. var lastSegmentStart = lastSegment.dateTimeObject;
  35326. var lastSegmentDuration = lastSegment.videoTimingInfo ? originalSegmentVideoDuration(lastSegment.videoTimingInfo) : lastSegment.duration + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT;
  35327. var lastSegmentEnd = new Date(lastSegmentStart.getTime() + lastSegmentDuration * 1000);
  35328. if (dateTimeObject > lastSegmentEnd) {
  35329. // Beyond the end of the stream, or our best guess of the end of the stream.
  35330. return null;
  35331. }
  35332. if (dateTimeObject > lastSegmentStart) {
  35333. segment = lastSegment;
  35334. }
  35335. return {
  35336. segment: segment,
  35337. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : Playlist.duration(playlist, playlist.mediaSequence + playlist.segments.indexOf(segment)),
  35338. // Although, given that all segments have accurate date time objects, the segment
  35339. // selected should be accurate, unless the video has been transmuxed at some point
  35340. // (determined by the presence of the videoTimingInfo object), the segment's "player
  35341. // time" (the start time in the player) can't be considered accurate.
  35342. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  35343. };
  35344. };
  35345. /**
  35346. * Finds a segment that contains the given player time(in seconds).
  35347. *
  35348. * @param {number} time The player time to find a match for
  35349. * @param {Object} playlist A playlist object to search within
  35350. */
  35351. var findSegmentForPlayerTime = function findSegmentForPlayerTime(time, playlist) {
  35352. // Assumptions:
  35353. // - there will always be a segment.duration
  35354. // - we can start from zero
  35355. // - segments are in time order
  35356. if (!playlist || !playlist.segments || playlist.segments.length === 0) {
  35357. return null;
  35358. }
  35359. var segmentEnd = 0;
  35360. var segment;
  35361. for (var i = 0; i < playlist.segments.length; i++) {
  35362. segment = playlist.segments[i]; // videoTimingInfo is set after the segment is downloaded and transmuxed, and
  35363. // should contain the most accurate values we have for the segment's player times.
  35364. //
  35365. // Use the accurate transmuxedPresentationEnd value if it is available, otherwise fall
  35366. // back to an estimate based on the manifest derived (inaccurate) segment.duration, to
  35367. // calculate an end value.
  35368. segmentEnd = segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationEnd : segmentEnd + segment.duration;
  35369. if (time <= segmentEnd) {
  35370. break;
  35371. }
  35372. }
  35373. var lastSegment = playlist.segments[playlist.segments.length - 1];
  35374. if (lastSegment.videoTimingInfo && lastSegment.videoTimingInfo.transmuxedPresentationEnd < time) {
  35375. // The time requested is beyond the stream end.
  35376. return null;
  35377. }
  35378. if (time > segmentEnd) {
  35379. // The time is within or beyond the last segment.
  35380. //
  35381. // Check to see if the time is beyond a reasonable guess of the end of the stream.
  35382. if (time > segmentEnd + lastSegment.duration * SEGMENT_END_FUDGE_PERCENT) {
  35383. // Technically, because the duration value is only an estimate, the time may still
  35384. // exist in the last segment, however, there isn't enough information to make even
  35385. // a reasonable estimate.
  35386. return null;
  35387. }
  35388. segment = lastSegment;
  35389. }
  35390. return {
  35391. segment: segment,
  35392. estimatedStart: segment.videoTimingInfo ? segment.videoTimingInfo.transmuxedPresentationStart : segmentEnd - segment.duration,
  35393. // Because videoTimingInfo is only set after transmux, it is the only way to get
  35394. // accurate timing values.
  35395. type: segment.videoTimingInfo ? 'accurate' : 'estimate'
  35396. };
  35397. };
  35398. /**
  35399. * Gives the offset of the comparisonTimestamp from the programTime timestamp in seconds.
  35400. * If the offset returned is positive, the programTime occurs after the
  35401. * comparisonTimestamp.
  35402. * If the offset is negative, the programTime occurs before the comparisonTimestamp.
  35403. *
  35404. * @param {string} comparisonTimeStamp An ISO-8601 timestamp to compare against
  35405. * @param {string} programTime The programTime as an ISO-8601 string
  35406. * @return {number} offset
  35407. */
  35408. var getOffsetFromTimestamp = function getOffsetFromTimestamp(comparisonTimeStamp, programTime) {
  35409. var segmentDateTime;
  35410. var programDateTime;
  35411. try {
  35412. segmentDateTime = new Date(comparisonTimeStamp);
  35413. programDateTime = new Date(programTime);
  35414. } catch (e) {// TODO handle error
  35415. }
  35416. var segmentTimeEpoch = segmentDateTime.getTime();
  35417. var programTimeEpoch = programDateTime.getTime();
  35418. return (programTimeEpoch - segmentTimeEpoch) / 1000;
  35419. };
  35420. /**
  35421. * Checks that all segments in this playlist have programDateTime tags.
  35422. *
  35423. * @param {Object} playlist A playlist object
  35424. */
  35425. var verifyProgramDateTimeTags = function verifyProgramDateTimeTags(playlist) {
  35426. if (!playlist.segments || playlist.segments.length === 0) {
  35427. return false;
  35428. }
  35429. for (var i = 0; i < playlist.segments.length; i++) {
  35430. var segment = playlist.segments[i];
  35431. if (!segment.dateTimeObject) {
  35432. return false;
  35433. }
  35434. }
  35435. return true;
  35436. };
  35437. /**
  35438. * Returns the programTime of the media given a playlist and a playerTime.
  35439. * The playlist must have programDateTime tags for a programDateTime tag to be returned.
  35440. * If the segments containing the time requested have not been buffered yet, an estimate
  35441. * may be returned to the callback.
  35442. *
  35443. * @param {Object} args
  35444. * @param {Object} args.playlist A playlist object to search within
  35445. * @param {number} time A playerTime in seconds
  35446. * @param {Function} callback(err, programTime)
  35447. * @return {string} err.message A detailed error message
  35448. * @return {Object} programTime
  35449. * @return {number} programTime.mediaSeconds The streamTime in seconds
  35450. * @return {string} programTime.programDateTime The programTime as an ISO-8601 String
  35451. */
  35452. var getProgramTime = function getProgramTime(_ref) {
  35453. var playlist = _ref.playlist,
  35454. _ref$time = _ref.time,
  35455. time = _ref$time === void 0 ? undefined : _ref$time,
  35456. callback = _ref.callback;
  35457. if (!callback) {
  35458. throw new Error('getProgramTime: callback must be provided');
  35459. }
  35460. if (!playlist || time === undefined) {
  35461. return callback({
  35462. message: 'getProgramTime: playlist and time must be provided'
  35463. });
  35464. }
  35465. var matchedSegment = findSegmentForPlayerTime(time, playlist);
  35466. if (!matchedSegment) {
  35467. return callback({
  35468. message: 'valid programTime was not found'
  35469. });
  35470. }
  35471. if (matchedSegment.type === 'estimate') {
  35472. return callback({
  35473. message: 'Accurate programTime could not be determined.' + ' Please seek to e.seekTime and try again',
  35474. seekTime: matchedSegment.estimatedStart
  35475. });
  35476. }
  35477. var programTimeObject = {
  35478. mediaSeconds: time
  35479. };
  35480. var programTime = playerTimeToProgramTime(time, matchedSegment.segment);
  35481. if (programTime) {
  35482. programTimeObject.programDateTime = programTime.toISOString();
  35483. }
  35484. return callback(null, programTimeObject);
  35485. };
  35486. /**
  35487. * Seeks in the player to a time that matches the given programTime ISO-8601 string.
  35488. *
  35489. * @param {Object} args
  35490. * @param {string} args.programTime A programTime to seek to as an ISO-8601 String
  35491. * @param {Object} args.playlist A playlist to look within
  35492. * @param {number} args.retryCount The number of times to try for an accurate seek. Default is 2.
  35493. * @param {Function} args.seekTo A method to perform a seek
  35494. * @param {boolean} args.pauseAfterSeek Whether to end in a paused state after seeking. Default is true.
  35495. * @param {Object} args.tech The tech to seek on
  35496. * @param {Function} args.callback(err, newTime) A callback to return the new time to
  35497. * @return {string} err.message A detailed error message
  35498. * @return {number} newTime The exact time that was seeked to in seconds
  35499. */
  35500. var seekToProgramTime = function seekToProgramTime(_ref2) {
  35501. var programTime = _ref2.programTime,
  35502. playlist = _ref2.playlist,
  35503. _ref2$retryCount = _ref2.retryCount,
  35504. retryCount = _ref2$retryCount === void 0 ? 2 : _ref2$retryCount,
  35505. seekTo = _ref2.seekTo,
  35506. _ref2$pauseAfterSeek = _ref2.pauseAfterSeek,
  35507. pauseAfterSeek = _ref2$pauseAfterSeek === void 0 ? true : _ref2$pauseAfterSeek,
  35508. tech = _ref2.tech,
  35509. callback = _ref2.callback;
  35510. if (!callback) {
  35511. throw new Error('seekToProgramTime: callback must be provided');
  35512. }
  35513. if (typeof programTime === 'undefined' || !playlist || !seekTo) {
  35514. return callback({
  35515. message: 'seekToProgramTime: programTime, seekTo and playlist must be provided'
  35516. });
  35517. }
  35518. if (!playlist.endList && !tech.hasStarted_) {
  35519. return callback({
  35520. message: 'player must be playing a live stream to start buffering'
  35521. });
  35522. }
  35523. if (!verifyProgramDateTimeTags(playlist)) {
  35524. return callback({
  35525. message: 'programDateTime tags must be provided in the manifest ' + playlist.resolvedUri
  35526. });
  35527. }
  35528. var matchedSegment = findSegmentForProgramTime(programTime, playlist); // no match
  35529. if (!matchedSegment) {
  35530. return callback({
  35531. message: programTime + " was not found in the stream"
  35532. });
  35533. }
  35534. var segment = matchedSegment.segment;
  35535. var mediaOffset = getOffsetFromTimestamp(segment.dateTimeObject, programTime);
  35536. if (matchedSegment.type === 'estimate') {
  35537. // we've run out of retries
  35538. if (retryCount === 0) {
  35539. return callback({
  35540. message: programTime + " is not buffered yet. Try again"
  35541. });
  35542. }
  35543. seekTo(matchedSegment.estimatedStart + mediaOffset);
  35544. tech.one('seeked', function () {
  35545. seekToProgramTime({
  35546. programTime: programTime,
  35547. playlist: playlist,
  35548. retryCount: retryCount - 1,
  35549. seekTo: seekTo,
  35550. pauseAfterSeek: pauseAfterSeek,
  35551. tech: tech,
  35552. callback: callback
  35553. });
  35554. });
  35555. return;
  35556. } // Since the segment.start value is determined from the buffered end or ending time
  35557. // of the prior segment, the seekToTime doesn't need to account for any transmuxer
  35558. // modifications.
  35559. var seekToTime = segment.start + mediaOffset;
  35560. var seekedCallback = function seekedCallback() {
  35561. return callback(null, tech.currentTime());
  35562. }; // listen for seeked event
  35563. tech.one('seeked', seekedCallback); // pause before seeking as video.js will restore this state
  35564. if (pauseAfterSeek) {
  35565. tech.pause();
  35566. }
  35567. seekTo(seekToTime);
  35568. }; // which will only happen if the request is complete.
  35569. var callbackOnCompleted = function callbackOnCompleted(request, cb) {
  35570. if (request.readyState === 4) {
  35571. return cb();
  35572. }
  35573. return;
  35574. };
  35575. var containerRequest = function containerRequest(uri, xhr, cb) {
  35576. var bytes = [];
  35577. var id3Offset;
  35578. var finished = false;
  35579. var endRequestAndCallback = function endRequestAndCallback(err, req, type, _bytes) {
  35580. req.abort();
  35581. finished = true;
  35582. return cb(err, req, type, _bytes);
  35583. };
  35584. var progressListener = function progressListener(error, request) {
  35585. if (finished) {
  35586. return;
  35587. }
  35588. if (error) {
  35589. return endRequestAndCallback(error, request, '', bytes);
  35590. } // grap the new part of content that was just downloaded
  35591. var newPart = request.responseText.substring(bytes && bytes.byteLength || 0, request.responseText.length); // add that onto bytes
  35592. bytes = concatTypedArrays(bytes, stringToBytes(newPart, true));
  35593. id3Offset = id3Offset || getId3Offset(bytes); // we need at least 10 bytes to determine a type
  35594. // or we need at least two bytes after an id3Offset
  35595. if (bytes.length < 10 || id3Offset && bytes.length < id3Offset + 2) {
  35596. return callbackOnCompleted(request, function () {
  35597. return endRequestAndCallback(error, request, '', bytes);
  35598. });
  35599. }
  35600. var type = detectContainerForBytes(bytes); // if this looks like a ts segment but we don't have enough data
  35601. // to see the second sync byte, wait until we have enough data
  35602. // before declaring it ts
  35603. if (type === 'ts' && bytes.length < 188) {
  35604. return callbackOnCompleted(request, function () {
  35605. return endRequestAndCallback(error, request, '', bytes);
  35606. });
  35607. } // this may be an unsynced ts segment
  35608. // wait for 376 bytes before detecting no container
  35609. if (!type && bytes.length < 376) {
  35610. return callbackOnCompleted(request, function () {
  35611. return endRequestAndCallback(error, request, '', bytes);
  35612. });
  35613. }
  35614. return endRequestAndCallback(null, request, type, bytes);
  35615. };
  35616. var options = {
  35617. uri: uri,
  35618. beforeSend: function beforeSend(request) {
  35619. // this forces the browser to pass the bytes to us unprocessed
  35620. request.overrideMimeType('text/plain; charset=x-user-defined');
  35621. request.addEventListener('progress', function (_ref) {
  35622. _ref.total;
  35623. _ref.loaded;
  35624. return callbackWrapper(request, null, {
  35625. statusCode: request.status
  35626. }, progressListener);
  35627. });
  35628. }
  35629. };
  35630. var request = xhr(options, function (error, response) {
  35631. return callbackWrapper(request, error, response, progressListener);
  35632. });
  35633. return request;
  35634. };
  35635. var EventTarget = videojs.EventTarget,
  35636. mergeOptions = videojs.mergeOptions;
  35637. var dashPlaylistUnchanged = function dashPlaylistUnchanged(a, b) {
  35638. if (!isPlaylistUnchanged(a, b)) {
  35639. return false;
  35640. } // for dash the above check will often return true in scenarios where
  35641. // the playlist actually has changed because mediaSequence isn't a
  35642. // dash thing, and we often set it to 1. So if the playlists have the same amount
  35643. // of segments we return true.
  35644. // So for dash we need to make sure that the underlying segments are different.
  35645. // if sidx changed then the playlists are different.
  35646. if (a.sidx && b.sidx && (a.sidx.offset !== b.sidx.offset || a.sidx.length !== b.sidx.length)) {
  35647. return false;
  35648. } else if (!a.sidx && b.sidx || a.sidx && !b.sidx) {
  35649. return false;
  35650. } // one or the other does not have segments
  35651. // there was a change.
  35652. if (a.segments && !b.segments || !a.segments && b.segments) {
  35653. return false;
  35654. } // neither has segments nothing changed
  35655. if (!a.segments && !b.segments) {
  35656. return true;
  35657. } // check segments themselves
  35658. for (var i = 0; i < a.segments.length; i++) {
  35659. var aSegment = a.segments[i];
  35660. var bSegment = b.segments[i]; // if uris are different between segments there was a change
  35661. if (aSegment.uri !== bSegment.uri) {
  35662. return false;
  35663. } // neither segment has a byterange, there will be no byterange change.
  35664. if (!aSegment.byterange && !bSegment.byterange) {
  35665. continue;
  35666. }
  35667. var aByterange = aSegment.byterange;
  35668. var bByterange = bSegment.byterange; // if byterange only exists on one of the segments, there was a change.
  35669. if (aByterange && !bByterange || !aByterange && bByterange) {
  35670. return false;
  35671. } // if both segments have byterange with different offsets, there was a change.
  35672. if (aByterange.offset !== bByterange.offset || aByterange.length !== bByterange.length) {
  35673. return false;
  35674. }
  35675. } // if everything was the same with segments, this is the same playlist.
  35676. return true;
  35677. };
  35678. /**
  35679. * Use the representation IDs from the mpd object to create groupIDs, the NAME is set to mandatory representation
  35680. * ID in the parser. This allows for continuous playout across periods with the same representation IDs
  35681. * (continuous periods as defined in DASH-IF 3.2.12). This is assumed in the mpd-parser as well. If we want to support
  35682. * periods without continuous playback this function may need modification as well as the parser.
  35683. */
  35684. var dashGroupId = function dashGroupId(type, group, label, playlist) {
  35685. // If the manifest somehow does not have an ID (non-dash compliant), use the label.
  35686. var playlistId = playlist.attributes.NAME || label;
  35687. return "placeholder-uri-" + type + "-" + group + "-" + playlistId;
  35688. };
  35689. /**
  35690. * Parses the master XML string and updates playlist URI references.
  35691. *
  35692. * @param {Object} config
  35693. * Object of arguments
  35694. * @param {string} config.masterXml
  35695. * The mpd XML
  35696. * @param {string} config.srcUrl
  35697. * The mpd URL
  35698. * @param {Date} config.clientOffset
  35699. * A time difference between server and client
  35700. * @param {Object} config.sidxMapping
  35701. * SIDX mappings for moof/mdat URIs and byte ranges
  35702. * @return {Object}
  35703. * The parsed mpd manifest object
  35704. */
  35705. var parseMasterXml = function parseMasterXml(_ref) {
  35706. var masterXml = _ref.masterXml,
  35707. srcUrl = _ref.srcUrl,
  35708. clientOffset = _ref.clientOffset,
  35709. sidxMapping = _ref.sidxMapping,
  35710. previousManifest = _ref.previousManifest;
  35711. var manifest = parse(masterXml, {
  35712. manifestUri: srcUrl,
  35713. clientOffset: clientOffset,
  35714. sidxMapping: sidxMapping,
  35715. previousManifest: previousManifest
  35716. });
  35717. addPropertiesToMaster(manifest, srcUrl, dashGroupId);
  35718. return manifest;
  35719. };
  35720. /**
  35721. * Removes any mediaGroup labels that no longer exist in the newMaster
  35722. *
  35723. * @param {Object} update
  35724. * The previous mpd object being updated
  35725. * @param {Object} newMaster
  35726. * The new mpd object
  35727. */
  35728. var removeOldMediaGroupLabels = function removeOldMediaGroupLabels(update, newMaster) {
  35729. forEachMediaGroup(update, function (properties, type, group, label) {
  35730. if (!(label in newMaster.mediaGroups[type][group])) {
  35731. delete update.mediaGroups[type][group][label];
  35732. }
  35733. });
  35734. };
  35735. /**
  35736. * Returns a new master manifest that is the result of merging an updated master manifest
  35737. * into the original version.
  35738. *
  35739. * @param {Object} oldMaster
  35740. * The old parsed mpd object
  35741. * @param {Object} newMaster
  35742. * The updated parsed mpd object
  35743. * @return {Object}
  35744. * A new object representing the original master manifest with the updated media
  35745. * playlists merged in
  35746. */
  35747. var updateMaster = function updateMaster(oldMaster, newMaster, sidxMapping) {
  35748. var noChanges = true;
  35749. var update = mergeOptions(oldMaster, {
  35750. // These are top level properties that can be updated
  35751. duration: newMaster.duration,
  35752. minimumUpdatePeriod: newMaster.minimumUpdatePeriod,
  35753. timelineStarts: newMaster.timelineStarts
  35754. }); // First update the playlists in playlist list
  35755. for (var i = 0; i < newMaster.playlists.length; i++) {
  35756. var playlist = newMaster.playlists[i];
  35757. if (playlist.sidx) {
  35758. var sidxKey = generateSidxKey(playlist.sidx); // add sidx segments to the playlist if we have all the sidx info already
  35759. if (sidxMapping && sidxMapping[sidxKey] && sidxMapping[sidxKey].sidx) {
  35760. addSidxSegmentsToPlaylist$1(playlist, sidxMapping[sidxKey].sidx, playlist.sidx.resolvedUri);
  35761. }
  35762. }
  35763. var playlistUpdate = updateMaster$1(update, playlist, dashPlaylistUnchanged);
  35764. if (playlistUpdate) {
  35765. update = playlistUpdate;
  35766. noChanges = false;
  35767. }
  35768. } // Then update media group playlists
  35769. forEachMediaGroup(newMaster, function (properties, type, group, label) {
  35770. if (properties.playlists && properties.playlists.length) {
  35771. var id = properties.playlists[0].id;
  35772. var _playlistUpdate = updateMaster$1(update, properties.playlists[0], dashPlaylistUnchanged);
  35773. if (_playlistUpdate) {
  35774. update = _playlistUpdate; // add new mediaGroup label if it doesn't exist and assign the new mediaGroup.
  35775. if (!(label in update.mediaGroups[type][group])) {
  35776. update.mediaGroups[type][group][label] = properties;
  35777. } // update the playlist reference within media groups
  35778. update.mediaGroups[type][group][label].playlists[0] = update.playlists[id];
  35779. noChanges = false;
  35780. }
  35781. }
  35782. }); // remove mediaGroup labels and references that no longer exist in the newMaster
  35783. removeOldMediaGroupLabels(update, newMaster);
  35784. if (newMaster.minimumUpdatePeriod !== oldMaster.minimumUpdatePeriod) {
  35785. noChanges = false;
  35786. }
  35787. if (noChanges) {
  35788. return null;
  35789. }
  35790. return update;
  35791. }; // SIDX should be equivalent if the URI and byteranges of the SIDX match.
  35792. // If the SIDXs have maps, the two maps should match,
  35793. // both `a` and `b` missing SIDXs is considered matching.
  35794. // If `a` or `b` but not both have a map, they aren't matching.
  35795. var equivalentSidx = function equivalentSidx(a, b) {
  35796. var neitherMap = Boolean(!a.map && !b.map);
  35797. var equivalentMap = neitherMap || Boolean(a.map && b.map && a.map.byterange.offset === b.map.byterange.offset && a.map.byterange.length === b.map.byterange.length);
  35798. return equivalentMap && a.uri === b.uri && a.byterange.offset === b.byterange.offset && a.byterange.length === b.byterange.length;
  35799. }; // exported for testing
  35800. var compareSidxEntry = function compareSidxEntry(playlists, oldSidxMapping) {
  35801. var newSidxMapping = {};
  35802. for (var id in playlists) {
  35803. var playlist = playlists[id];
  35804. var currentSidxInfo = playlist.sidx;
  35805. if (currentSidxInfo) {
  35806. var key = generateSidxKey(currentSidxInfo);
  35807. if (!oldSidxMapping[key]) {
  35808. break;
  35809. }
  35810. var savedSidxInfo = oldSidxMapping[key].sidxInfo;
  35811. if (equivalentSidx(savedSidxInfo, currentSidxInfo)) {
  35812. newSidxMapping[key] = oldSidxMapping[key];
  35813. }
  35814. }
  35815. }
  35816. return newSidxMapping;
  35817. };
  35818. /**
  35819. * A function that filters out changed items as they need to be requested separately.
  35820. *
  35821. * The method is exported for testing
  35822. *
  35823. * @param {Object} master the parsed mpd XML returned via mpd-parser
  35824. * @param {Object} oldSidxMapping the SIDX to compare against
  35825. */
  35826. var filterChangedSidxMappings = function filterChangedSidxMappings(master, oldSidxMapping) {
  35827. var videoSidx = compareSidxEntry(master.playlists, oldSidxMapping);
  35828. var mediaGroupSidx = videoSidx;
  35829. forEachMediaGroup(master, function (properties, mediaType, groupKey, labelKey) {
  35830. if (properties.playlists && properties.playlists.length) {
  35831. var playlists = properties.playlists;
  35832. mediaGroupSidx = mergeOptions(mediaGroupSidx, compareSidxEntry(playlists, oldSidxMapping));
  35833. }
  35834. });
  35835. return mediaGroupSidx;
  35836. };
  35837. var DashPlaylistLoader = /*#__PURE__*/function (_EventTarget) {
  35838. inheritsLoose(DashPlaylistLoader, _EventTarget); // DashPlaylistLoader must accept either a src url or a playlist because subsequent
  35839. // playlist loader setups from media groups will expect to be able to pass a playlist
  35840. // (since there aren't external URLs to media playlists with DASH)
  35841. function DashPlaylistLoader(srcUrlOrPlaylist, vhs, options, masterPlaylistLoader) {
  35842. var _this;
  35843. if (options === void 0) {
  35844. options = {};
  35845. }
  35846. _this = _EventTarget.call(this) || this;
  35847. _this.masterPlaylistLoader_ = masterPlaylistLoader || assertThisInitialized(_this);
  35848. if (!masterPlaylistLoader) {
  35849. _this.isMaster_ = true;
  35850. }
  35851. var _options = options,
  35852. _options$withCredenti = _options.withCredentials,
  35853. withCredentials = _options$withCredenti === void 0 ? false : _options$withCredenti,
  35854. _options$handleManife = _options.handleManifestRedirects,
  35855. handleManifestRedirects = _options$handleManife === void 0 ? false : _options$handleManife;
  35856. _this.vhs_ = vhs;
  35857. _this.withCredentials = withCredentials;
  35858. _this.handleManifestRedirects = handleManifestRedirects;
  35859. if (!srcUrlOrPlaylist) {
  35860. throw new Error('A non-empty playlist URL or object is required');
  35861. } // event naming?
  35862. _this.on('minimumUpdatePeriod', function () {
  35863. _this.refreshXml_();
  35864. }); // live playlist staleness timeout
  35865. _this.on('mediaupdatetimeout', function () {
  35866. _this.refreshMedia_(_this.media().id);
  35867. });
  35868. _this.state = 'HAVE_NOTHING';
  35869. _this.loadedPlaylists_ = {};
  35870. _this.logger_ = logger('DashPlaylistLoader'); // initialize the loader state
  35871. // The masterPlaylistLoader will be created with a string
  35872. if (_this.isMaster_) {
  35873. _this.masterPlaylistLoader_.srcUrl = srcUrlOrPlaylist; // TODO: reset sidxMapping between period changes
  35874. // once multi-period is refactored
  35875. _this.masterPlaylistLoader_.sidxMapping_ = {};
  35876. } else {
  35877. _this.childPlaylist_ = srcUrlOrPlaylist;
  35878. }
  35879. return _this;
  35880. }
  35881. var _proto = DashPlaylistLoader.prototype;
  35882. _proto.requestErrored_ = function requestErrored_(err, request, startingState) {
  35883. // disposed
  35884. if (!this.request) {
  35885. return true;
  35886. } // pending request is cleared
  35887. this.request = null;
  35888. if (err) {
  35889. // use the provided error object or create one
  35890. // based on the request/response
  35891. this.error = typeof err === 'object' && !(err instanceof Error) ? err : {
  35892. status: request.status,
  35893. message: 'DASH request error at URL: ' + request.uri,
  35894. response: request.response,
  35895. // MEDIA_ERR_NETWORK
  35896. code: 2
  35897. };
  35898. if (startingState) {
  35899. this.state = startingState;
  35900. }
  35901. this.trigger('error');
  35902. return true;
  35903. }
  35904. }
  35905. /**
  35906. * Verify that the container of the sidx segment can be parsed
  35907. * and if it can, get and parse that segment.
  35908. */
  35909. ;
  35910. _proto.addSidxSegments_ = function addSidxSegments_(playlist, startingState, cb) {
  35911. var _this2 = this;
  35912. var sidxKey = playlist.sidx && generateSidxKey(playlist.sidx); // playlist lacks sidx or sidx segments were added to this playlist already.
  35913. if (!playlist.sidx || !sidxKey || this.masterPlaylistLoader_.sidxMapping_[sidxKey]) {
  35914. // keep this function async
  35915. this.mediaRequest_ = window.setTimeout(function () {
  35916. return cb(false);
  35917. }, 0);
  35918. return;
  35919. } // resolve the segment URL relative to the playlist
  35920. var uri = resolveManifestRedirect(this.handleManifestRedirects, playlist.sidx.resolvedUri);
  35921. var fin = function fin(err, request) {
  35922. if (_this2.requestErrored_(err, request, startingState)) {
  35923. return;
  35924. }
  35925. var sidxMapping = _this2.masterPlaylistLoader_.sidxMapping_;
  35926. var sidx;
  35927. try {
  35928. sidx = parseSidx_1(toUint8(request.response).subarray(8));
  35929. } catch (e) {
  35930. // sidx parsing failed.
  35931. _this2.requestErrored_(e, request, startingState);
  35932. return;
  35933. }
  35934. sidxMapping[sidxKey] = {
  35935. sidxInfo: playlist.sidx,
  35936. sidx: sidx
  35937. };
  35938. addSidxSegmentsToPlaylist$1(playlist, sidx, playlist.sidx.resolvedUri);
  35939. return cb(true);
  35940. };
  35941. this.request = containerRequest(uri, this.vhs_.xhr, function (err, request, container, bytes) {
  35942. if (err) {
  35943. return fin(err, request);
  35944. }
  35945. if (!container || container !== 'mp4') {
  35946. return fin({
  35947. status: request.status,
  35948. message: "Unsupported " + (container || 'unknown') + " container type for sidx segment at URL: " + uri,
  35949. // response is just bytes in this case
  35950. // but we really don't want to return that.
  35951. response: '',
  35952. playlist: playlist,
  35953. internal: true,
  35954. blacklistDuration: Infinity,
  35955. // MEDIA_ERR_NETWORK
  35956. code: 2
  35957. }, request);
  35958. } // if we already downloaded the sidx bytes in the container request, use them
  35959. var _playlist$sidx$bytera = playlist.sidx.byterange,
  35960. offset = _playlist$sidx$bytera.offset,
  35961. length = _playlist$sidx$bytera.length;
  35962. if (bytes.length >= length + offset) {
  35963. return fin(err, {
  35964. response: bytes.subarray(offset, offset + length),
  35965. status: request.status,
  35966. uri: request.uri
  35967. });
  35968. } // otherwise request sidx bytes
  35969. _this2.request = _this2.vhs_.xhr({
  35970. uri: uri,
  35971. responseType: 'arraybuffer',
  35972. headers: segmentXhrHeaders({
  35973. byterange: playlist.sidx.byterange
  35974. })
  35975. }, fin);
  35976. });
  35977. };
  35978. _proto.dispose = function dispose() {
  35979. this.trigger('dispose');
  35980. this.stopRequest();
  35981. this.loadedPlaylists_ = {};
  35982. window.clearTimeout(this.minimumUpdatePeriodTimeout_);
  35983. window.clearTimeout(this.mediaRequest_);
  35984. window.clearTimeout(this.mediaUpdateTimeout);
  35985. this.mediaUpdateTimeout = null;
  35986. this.mediaRequest_ = null;
  35987. this.minimumUpdatePeriodTimeout_ = null;
  35988. if (this.masterPlaylistLoader_.createMupOnMedia_) {
  35989. this.off('loadedmetadata', this.masterPlaylistLoader_.createMupOnMedia_);
  35990. this.masterPlaylistLoader_.createMupOnMedia_ = null;
  35991. }
  35992. this.off();
  35993. };
  35994. _proto.hasPendingRequest = function hasPendingRequest() {
  35995. return this.request || this.mediaRequest_;
  35996. };
  35997. _proto.stopRequest = function stopRequest() {
  35998. if (this.request) {
  35999. var oldRequest = this.request;
  36000. this.request = null;
  36001. oldRequest.onreadystatechange = null;
  36002. oldRequest.abort();
  36003. }
  36004. };
  36005. _proto.media = function media(playlist) {
  36006. var _this3 = this; // getter
  36007. if (!playlist) {
  36008. return this.media_;
  36009. } // setter
  36010. if (this.state === 'HAVE_NOTHING') {
  36011. throw new Error('Cannot switch media playlist from ' + this.state);
  36012. }
  36013. var startingState = this.state; // find the playlist object if the target playlist has been specified by URI
  36014. if (typeof playlist === 'string') {
  36015. if (!this.masterPlaylistLoader_.master.playlists[playlist]) {
  36016. throw new Error('Unknown playlist URI: ' + playlist);
  36017. }
  36018. playlist = this.masterPlaylistLoader_.master.playlists[playlist];
  36019. }
  36020. var mediaChange = !this.media_ || playlist.id !== this.media_.id; // switch to previously loaded playlists immediately
  36021. if (mediaChange && this.loadedPlaylists_[playlist.id] && this.loadedPlaylists_[playlist.id].endList) {
  36022. this.state = 'HAVE_METADATA';
  36023. this.media_ = playlist; // trigger media change if the active media has been updated
  36024. if (mediaChange) {
  36025. this.trigger('mediachanging');
  36026. this.trigger('mediachange');
  36027. }
  36028. return;
  36029. } // switching to the active playlist is a no-op
  36030. if (!mediaChange) {
  36031. return;
  36032. } // switching from an already loaded playlist
  36033. if (this.media_) {
  36034. this.trigger('mediachanging');
  36035. }
  36036. this.addSidxSegments_(playlist, startingState, function (sidxChanged) {
  36037. // everything is ready just continue to haveMetadata
  36038. _this3.haveMetadata({
  36039. startingState: startingState,
  36040. playlist: playlist
  36041. });
  36042. });
  36043. };
  36044. _proto.haveMetadata = function haveMetadata(_ref2) {
  36045. var startingState = _ref2.startingState,
  36046. playlist = _ref2.playlist;
  36047. this.state = 'HAVE_METADATA';
  36048. this.loadedPlaylists_[playlist.id] = playlist;
  36049. this.mediaRequest_ = null; // This will trigger loadedplaylist
  36050. this.refreshMedia_(playlist.id); // fire loadedmetadata the first time a media playlist is loaded
  36051. // to resolve setup of media groups
  36052. if (startingState === 'HAVE_MASTER') {
  36053. this.trigger('loadedmetadata');
  36054. } else {
  36055. // trigger media change if the active media has been updated
  36056. this.trigger('mediachange');
  36057. }
  36058. };
  36059. _proto.pause = function pause() {
  36060. if (this.masterPlaylistLoader_.createMupOnMedia_) {
  36061. this.off('loadedmetadata', this.masterPlaylistLoader_.createMupOnMedia_);
  36062. this.masterPlaylistLoader_.createMupOnMedia_ = null;
  36063. }
  36064. this.stopRequest();
  36065. window.clearTimeout(this.mediaUpdateTimeout);
  36066. this.mediaUpdateTimeout = null;
  36067. if (this.isMaster_) {
  36068. window.clearTimeout(this.masterPlaylistLoader_.minimumUpdatePeriodTimeout_);
  36069. this.masterPlaylistLoader_.minimumUpdatePeriodTimeout_ = null;
  36070. }
  36071. if (this.state === 'HAVE_NOTHING') {
  36072. // If we pause the loader before any data has been retrieved, its as if we never
  36073. // started, so reset to an unstarted state.
  36074. this.started = false;
  36075. }
  36076. };
  36077. _proto.load = function load(isFinalRendition) {
  36078. var _this4 = this;
  36079. window.clearTimeout(this.mediaUpdateTimeout);
  36080. this.mediaUpdateTimeout = null;
  36081. var media = this.media();
  36082. if (isFinalRendition) {
  36083. var delay = media ? media.targetDuration / 2 * 1000 : 5 * 1000;
  36084. this.mediaUpdateTimeout = window.setTimeout(function () {
  36085. return _this4.load();
  36086. }, delay);
  36087. return;
  36088. } // because the playlists are internal to the manifest, load should either load the
  36089. // main manifest, or do nothing but trigger an event
  36090. if (!this.started) {
  36091. this.start();
  36092. return;
  36093. }
  36094. if (media && !media.endList) {
  36095. // Check to see if this is the master loader and the MUP was cleared (this happens
  36096. // when the loader was paused). `media` should be set at this point since one is always
  36097. // set during `start()`.
  36098. if (this.isMaster_ && !this.minimumUpdatePeriodTimeout_) {
  36099. // Trigger minimumUpdatePeriod to refresh the master manifest
  36100. this.trigger('minimumUpdatePeriod'); // Since there was no prior minimumUpdatePeriodTimeout it should be recreated
  36101. this.updateMinimumUpdatePeriodTimeout_();
  36102. }
  36103. this.trigger('mediaupdatetimeout');
  36104. } else {
  36105. this.trigger('loadedplaylist');
  36106. }
  36107. };
  36108. _proto.start = function start() {
  36109. var _this5 = this;
  36110. this.started = true; // We don't need to request the master manifest again
  36111. // Call this asynchronously to match the xhr request behavior below
  36112. if (!this.isMaster_) {
  36113. this.mediaRequest_ = window.setTimeout(function () {
  36114. return _this5.haveMaster_();
  36115. }, 0);
  36116. return;
  36117. }
  36118. this.requestMaster_(function (req, masterChanged) {
  36119. _this5.haveMaster_();
  36120. if (!_this5.hasPendingRequest() && !_this5.media_) {
  36121. _this5.media(_this5.masterPlaylistLoader_.master.playlists[0]);
  36122. }
  36123. });
  36124. };
  36125. _proto.requestMaster_ = function requestMaster_(cb) {
  36126. var _this6 = this;
  36127. this.request = this.vhs_.xhr({
  36128. uri: this.masterPlaylistLoader_.srcUrl,
  36129. withCredentials: this.withCredentials
  36130. }, function (error, req) {
  36131. if (_this6.requestErrored_(error, req)) {
  36132. if (_this6.state === 'HAVE_NOTHING') {
  36133. _this6.started = false;
  36134. }
  36135. return;
  36136. }
  36137. var masterChanged = req.responseText !== _this6.masterPlaylistLoader_.masterXml_;
  36138. _this6.masterPlaylistLoader_.masterXml_ = req.responseText;
  36139. if (req.responseHeaders && req.responseHeaders.date) {
  36140. _this6.masterLoaded_ = Date.parse(req.responseHeaders.date);
  36141. } else {
  36142. _this6.masterLoaded_ = Date.now();
  36143. }
  36144. _this6.masterPlaylistLoader_.srcUrl = resolveManifestRedirect(_this6.handleManifestRedirects, _this6.masterPlaylistLoader_.srcUrl, req);
  36145. if (masterChanged) {
  36146. _this6.handleMaster_();
  36147. _this6.syncClientServerClock_(function () {
  36148. return cb(req, masterChanged);
  36149. });
  36150. return;
  36151. }
  36152. return cb(req, masterChanged);
  36153. });
  36154. }
  36155. /**
  36156. * Parses the master xml for UTCTiming node to sync the client clock to the server
  36157. * clock. If the UTCTiming node requires a HEAD or GET request, that request is made.
  36158. *
  36159. * @param {Function} done
  36160. * Function to call when clock sync has completed
  36161. */
  36162. ;
  36163. _proto.syncClientServerClock_ = function syncClientServerClock_(done) {
  36164. var _this7 = this;
  36165. var utcTiming = parseUTCTiming(this.masterPlaylistLoader_.masterXml_); // No UTCTiming element found in the mpd. Use Date header from mpd request as the
  36166. // server clock
  36167. if (utcTiming === null) {
  36168. this.masterPlaylistLoader_.clientOffset_ = this.masterLoaded_ - Date.now();
  36169. return done();
  36170. }
  36171. if (utcTiming.method === 'DIRECT') {
  36172. this.masterPlaylistLoader_.clientOffset_ = utcTiming.value - Date.now();
  36173. return done();
  36174. }
  36175. this.request = this.vhs_.xhr({
  36176. uri: resolveUrl(this.masterPlaylistLoader_.srcUrl, utcTiming.value),
  36177. method: utcTiming.method,
  36178. withCredentials: this.withCredentials
  36179. }, function (error, req) {
  36180. // disposed
  36181. if (!_this7.request) {
  36182. return;
  36183. }
  36184. if (error) {
  36185. // sync request failed, fall back to using date header from mpd
  36186. // TODO: log warning
  36187. _this7.masterPlaylistLoader_.clientOffset_ = _this7.masterLoaded_ - Date.now();
  36188. return done();
  36189. }
  36190. var serverTime;
  36191. if (utcTiming.method === 'HEAD') {
  36192. if (!req.responseHeaders || !req.responseHeaders.date) {
  36193. // expected date header not preset, fall back to using date header from mpd
  36194. // TODO: log warning
  36195. serverTime = _this7.masterLoaded_;
  36196. } else {
  36197. serverTime = Date.parse(req.responseHeaders.date);
  36198. }
  36199. } else {
  36200. serverTime = Date.parse(req.responseText);
  36201. }
  36202. _this7.masterPlaylistLoader_.clientOffset_ = serverTime - Date.now();
  36203. done();
  36204. });
  36205. };
  36206. _proto.haveMaster_ = function haveMaster_() {
  36207. this.state = 'HAVE_MASTER';
  36208. if (this.isMaster_) {
  36209. // We have the master playlist at this point, so
  36210. // trigger this to allow MasterPlaylistController
  36211. // to make an initial playlist selection
  36212. this.trigger('loadedplaylist');
  36213. } else if (!this.media_) {
  36214. // no media playlist was specifically selected so select
  36215. // the one the child playlist loader was created with
  36216. this.media(this.childPlaylist_);
  36217. }
  36218. };
  36219. _proto.handleMaster_ = function handleMaster_() {
  36220. // clear media request
  36221. this.mediaRequest_ = null;
  36222. var oldMaster = this.masterPlaylistLoader_.master;
  36223. var newMaster = parseMasterXml({
  36224. masterXml: this.masterPlaylistLoader_.masterXml_,
  36225. srcUrl: this.masterPlaylistLoader_.srcUrl,
  36226. clientOffset: this.masterPlaylistLoader_.clientOffset_,
  36227. sidxMapping: this.masterPlaylistLoader_.sidxMapping_,
  36228. previousManifest: oldMaster
  36229. }); // if we have an old master to compare the new master against
  36230. if (oldMaster) {
  36231. newMaster = updateMaster(oldMaster, newMaster, this.masterPlaylistLoader_.sidxMapping_);
  36232. } // only update master if we have a new master
  36233. this.masterPlaylistLoader_.master = newMaster ? newMaster : oldMaster;
  36234. var location = this.masterPlaylistLoader_.master.locations && this.masterPlaylistLoader_.master.locations[0];
  36235. if (location && location !== this.masterPlaylistLoader_.srcUrl) {
  36236. this.masterPlaylistLoader_.srcUrl = location;
  36237. }
  36238. if (!oldMaster || newMaster && newMaster.minimumUpdatePeriod !== oldMaster.minimumUpdatePeriod) {
  36239. this.updateMinimumUpdatePeriodTimeout_();
  36240. }
  36241. return Boolean(newMaster);
  36242. };
  36243. _proto.updateMinimumUpdatePeriodTimeout_ = function updateMinimumUpdatePeriodTimeout_() {
  36244. var mpl = this.masterPlaylistLoader_; // cancel any pending creation of mup on media
  36245. // a new one will be added if needed.
  36246. if (mpl.createMupOnMedia_) {
  36247. mpl.off('loadedmetadata', mpl.createMupOnMedia_);
  36248. mpl.createMupOnMedia_ = null;
  36249. } // clear any pending timeouts
  36250. if (mpl.minimumUpdatePeriodTimeout_) {
  36251. window.clearTimeout(mpl.minimumUpdatePeriodTimeout_);
  36252. mpl.minimumUpdatePeriodTimeout_ = null;
  36253. }
  36254. var mup = mpl.master && mpl.master.minimumUpdatePeriod; // If the minimumUpdatePeriod has a value of 0, that indicates that the current
  36255. // MPD has no future validity, so a new one will need to be acquired when new
  36256. // media segments are to be made available. Thus, we use the target duration
  36257. // in this case
  36258. if (mup === 0) {
  36259. if (mpl.media()) {
  36260. mup = mpl.media().targetDuration * 1000;
  36261. } else {
  36262. mpl.createMupOnMedia_ = mpl.updateMinimumUpdatePeriodTimeout_;
  36263. mpl.one('loadedmetadata', mpl.createMupOnMedia_);
  36264. }
  36265. } // if minimumUpdatePeriod is invalid or <= zero, which
  36266. // can happen when a live video becomes VOD. skip timeout
  36267. // creation.
  36268. if (typeof mup !== 'number' || mup <= 0) {
  36269. if (mup < 0) {
  36270. this.logger_("found invalid minimumUpdatePeriod of " + mup + ", not setting a timeout");
  36271. }
  36272. return;
  36273. }
  36274. this.createMUPTimeout_(mup);
  36275. };
  36276. _proto.createMUPTimeout_ = function createMUPTimeout_(mup) {
  36277. var mpl = this.masterPlaylistLoader_;
  36278. mpl.minimumUpdatePeriodTimeout_ = window.setTimeout(function () {
  36279. mpl.minimumUpdatePeriodTimeout_ = null;
  36280. mpl.trigger('minimumUpdatePeriod');
  36281. mpl.createMUPTimeout_(mup);
  36282. }, mup);
  36283. }
  36284. /**
  36285. * Sends request to refresh the master xml and updates the parsed master manifest
  36286. */
  36287. ;
  36288. _proto.refreshXml_ = function refreshXml_() {
  36289. var _this8 = this;
  36290. this.requestMaster_(function (req, masterChanged) {
  36291. if (!masterChanged) {
  36292. return;
  36293. }
  36294. if (_this8.media_) {
  36295. _this8.media_ = _this8.masterPlaylistLoader_.master.playlists[_this8.media_.id];
  36296. } // This will filter out updated sidx info from the mapping
  36297. _this8.masterPlaylistLoader_.sidxMapping_ = filterChangedSidxMappings(_this8.masterPlaylistLoader_.master, _this8.masterPlaylistLoader_.sidxMapping_);
  36298. _this8.addSidxSegments_(_this8.media(), _this8.state, function (sidxChanged) {
  36299. // TODO: do we need to reload the current playlist?
  36300. _this8.refreshMedia_(_this8.media().id);
  36301. });
  36302. });
  36303. }
  36304. /**
  36305. * Refreshes the media playlist by re-parsing the master xml and updating playlist
  36306. * references. If this is an alternate loader, the updated parsed manifest is retrieved
  36307. * from the master loader.
  36308. */
  36309. ;
  36310. _proto.refreshMedia_ = function refreshMedia_(mediaID) {
  36311. var _this9 = this;
  36312. if (!mediaID) {
  36313. throw new Error('refreshMedia_ must take a media id');
  36314. } // for master we have to reparse the master xml
  36315. // to re-create segments based on current timing values
  36316. // which may change media. We only skip updating master
  36317. // if this is the first time this.media_ is being set.
  36318. // as master was just parsed in that case.
  36319. if (this.media_ && this.isMaster_) {
  36320. this.handleMaster_();
  36321. }
  36322. var playlists = this.masterPlaylistLoader_.master.playlists;
  36323. var mediaChanged = !this.media_ || this.media_ !== playlists[mediaID];
  36324. if (mediaChanged) {
  36325. this.media_ = playlists[mediaID];
  36326. } else {
  36327. this.trigger('playlistunchanged');
  36328. }
  36329. if (!this.mediaUpdateTimeout) {
  36330. var createMediaUpdateTimeout = function createMediaUpdateTimeout() {
  36331. if (_this9.media().endList) {
  36332. return;
  36333. }
  36334. _this9.mediaUpdateTimeout = window.setTimeout(function () {
  36335. _this9.trigger('mediaupdatetimeout');
  36336. createMediaUpdateTimeout();
  36337. }, refreshDelay(_this9.media(), Boolean(mediaChanged)));
  36338. };
  36339. createMediaUpdateTimeout();
  36340. }
  36341. this.trigger('loadedplaylist');
  36342. };
  36343. return DashPlaylistLoader;
  36344. }(EventTarget);
  36345. var Config = {
  36346. GOAL_BUFFER_LENGTH: 30,
  36347. MAX_GOAL_BUFFER_LENGTH: 60,
  36348. BACK_BUFFER_LENGTH: 30,
  36349. GOAL_BUFFER_LENGTH_RATE: 1,
  36350. // 0.5 MB/s
  36351. INITIAL_BANDWIDTH: 4194304,
  36352. // A fudge factor to apply to advertised playlist bitrates to account for
  36353. // temporary flucations in client bandwidth
  36354. BANDWIDTH_VARIANCE: 1.2,
  36355. // How much of the buffer must be filled before we consider upswitching
  36356. BUFFER_LOW_WATER_LINE: 0,
  36357. MAX_BUFFER_LOW_WATER_LINE: 30,
  36358. // TODO: Remove this when experimentalBufferBasedABR is removed
  36359. EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE: 16,
  36360. BUFFER_LOW_WATER_LINE_RATE: 1,
  36361. // If the buffer is greater than the high water line, we won't switch down
  36362. BUFFER_HIGH_WATER_LINE: 30
  36363. };
  36364. var stringToArrayBuffer = function stringToArrayBuffer(string) {
  36365. var view = new Uint8Array(new ArrayBuffer(string.length));
  36366. for (var i = 0; i < string.length; i++) {
  36367. view[i] = string.charCodeAt(i);
  36368. }
  36369. return view.buffer;
  36370. };
  36371. /* global Blob, BlobBuilder, Worker */
  36372. // unify worker interface
  36373. var browserWorkerPolyFill = function browserWorkerPolyFill(workerObj) {
  36374. // node only supports on/off
  36375. workerObj.on = workerObj.addEventListener;
  36376. workerObj.off = workerObj.removeEventListener;
  36377. return workerObj;
  36378. };
  36379. var createObjectURL = function createObjectURL(str) {
  36380. try {
  36381. return URL.createObjectURL(new Blob([str], {
  36382. type: 'application/javascript'
  36383. }));
  36384. } catch (e) {
  36385. var blob = new BlobBuilder();
  36386. blob.append(str);
  36387. return URL.createObjectURL(blob.getBlob());
  36388. }
  36389. };
  36390. var factory = function factory(code) {
  36391. return function () {
  36392. var objectUrl = createObjectURL(code);
  36393. var worker = browserWorkerPolyFill(new Worker(objectUrl));
  36394. worker.objURL = objectUrl;
  36395. var terminate = worker.terminate;
  36396. worker.on = worker.addEventListener;
  36397. worker.off = worker.removeEventListener;
  36398. worker.terminate = function () {
  36399. URL.revokeObjectURL(objectUrl);
  36400. return terminate.call(this);
  36401. };
  36402. return worker;
  36403. };
  36404. };
  36405. var transform = function transform(code) {
  36406. return "var browserWorkerPolyFill = " + browserWorkerPolyFill.toString() + ";\n" + 'browserWorkerPolyFill(self);\n' + code;
  36407. };
  36408. var getWorkerString = function getWorkerString(fn) {
  36409. return fn.toString().replace(/^function.+?{/, '').slice(0, -1);
  36410. };
  36411. /* rollup-plugin-worker-factory start for worker!/Users/ddashkevich/projects/http-streaming/src/transmuxer-worker.js */
  36412. var workerCode$1 = transform(getWorkerString(function () {
  36413. /**
  36414. * mux.js
  36415. *
  36416. * Copyright (c) Brightcove
  36417. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  36418. *
  36419. * A lightweight readable stream implemention that handles event dispatching.
  36420. * Objects that inherit from streams should call init in their constructors.
  36421. */
  36422. var Stream = function Stream() {
  36423. this.init = function () {
  36424. var listeners = {};
  36425. /**
  36426. * Add a listener for a specified event type.
  36427. * @param type {string} the event name
  36428. * @param listener {function} the callback to be invoked when an event of
  36429. * the specified type occurs
  36430. */
  36431. this.on = function (type, listener) {
  36432. if (!listeners[type]) {
  36433. listeners[type] = [];
  36434. }
  36435. listeners[type] = listeners[type].concat(listener);
  36436. };
  36437. /**
  36438. * Remove a listener for a specified event type.
  36439. * @param type {string} the event name
  36440. * @param listener {function} a function previously registered for this
  36441. * type of event through `on`
  36442. */
  36443. this.off = function (type, listener) {
  36444. var index;
  36445. if (!listeners[type]) {
  36446. return false;
  36447. }
  36448. index = listeners[type].indexOf(listener);
  36449. listeners[type] = listeners[type].slice();
  36450. listeners[type].splice(index, 1);
  36451. return index > -1;
  36452. };
  36453. /**
  36454. * Trigger an event of the specified type on this stream. Any additional
  36455. * arguments to this function are passed as parameters to event listeners.
  36456. * @param type {string} the event name
  36457. */
  36458. this.trigger = function (type) {
  36459. var callbacks, i, length, args;
  36460. callbacks = listeners[type];
  36461. if (!callbacks) {
  36462. return;
  36463. } // Slicing the arguments on every invocation of this method
  36464. // can add a significant amount of overhead. Avoid the
  36465. // intermediate object creation for the common case of a
  36466. // single callback argument
  36467. if (arguments.length === 2) {
  36468. length = callbacks.length;
  36469. for (i = 0; i < length; ++i) {
  36470. callbacks[i].call(this, arguments[1]);
  36471. }
  36472. } else {
  36473. args = [];
  36474. i = arguments.length;
  36475. for (i = 1; i < arguments.length; ++i) {
  36476. args.push(arguments[i]);
  36477. }
  36478. length = callbacks.length;
  36479. for (i = 0; i < length; ++i) {
  36480. callbacks[i].apply(this, args);
  36481. }
  36482. }
  36483. };
  36484. /**
  36485. * Destroys the stream and cleans up.
  36486. */
  36487. this.dispose = function () {
  36488. listeners = {};
  36489. };
  36490. };
  36491. };
  36492. /**
  36493. * Forwards all `data` events on this stream to the destination stream. The
  36494. * destination stream should provide a method `push` to receive the data
  36495. * events as they arrive.
  36496. * @param destination {stream} the stream that will receive all `data` events
  36497. * @param autoFlush {boolean} if false, we will not call `flush` on the destination
  36498. * when the current stream emits a 'done' event
  36499. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  36500. */
  36501. Stream.prototype.pipe = function (destination) {
  36502. this.on('data', function (data) {
  36503. destination.push(data);
  36504. });
  36505. this.on('done', function (flushSource) {
  36506. destination.flush(flushSource);
  36507. });
  36508. this.on('partialdone', function (flushSource) {
  36509. destination.partialFlush(flushSource);
  36510. });
  36511. this.on('endedtimeline', function (flushSource) {
  36512. destination.endTimeline(flushSource);
  36513. });
  36514. this.on('reset', function (flushSource) {
  36515. destination.reset(flushSource);
  36516. });
  36517. return destination;
  36518. }; // Default stream functions that are expected to be overridden to perform
  36519. // actual work. These are provided by the prototype as a sort of no-op
  36520. // implementation so that we don't have to check for their existence in the
  36521. // `pipe` function above.
  36522. Stream.prototype.push = function (data) {
  36523. this.trigger('data', data);
  36524. };
  36525. Stream.prototype.flush = function (flushSource) {
  36526. this.trigger('done', flushSource);
  36527. };
  36528. Stream.prototype.partialFlush = function (flushSource) {
  36529. this.trigger('partialdone', flushSource);
  36530. };
  36531. Stream.prototype.endTimeline = function (flushSource) {
  36532. this.trigger('endedtimeline', flushSource);
  36533. };
  36534. Stream.prototype.reset = function (flushSource) {
  36535. this.trigger('reset', flushSource);
  36536. };
  36537. var stream = Stream;
  36538. var MAX_UINT32$1 = Math.pow(2, 32);
  36539. var getUint64$2 = function getUint64(uint8) {
  36540. var dv = new DataView(uint8.buffer, uint8.byteOffset, uint8.byteLength);
  36541. var value;
  36542. if (dv.getBigUint64) {
  36543. value = dv.getBigUint64(0);
  36544. if (value < Number.MAX_SAFE_INTEGER) {
  36545. return Number(value);
  36546. }
  36547. return value;
  36548. }
  36549. return dv.getUint32(0) * MAX_UINT32$1 + dv.getUint32(4);
  36550. };
  36551. var numbers = {
  36552. getUint64: getUint64$2,
  36553. MAX_UINT32: MAX_UINT32$1
  36554. };
  36555. var MAX_UINT32 = numbers.MAX_UINT32;
  36556. 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
  36557. (function () {
  36558. var i;
  36559. types = {
  36560. avc1: [],
  36561. // codingname
  36562. avcC: [],
  36563. btrt: [],
  36564. dinf: [],
  36565. dref: [],
  36566. esds: [],
  36567. ftyp: [],
  36568. hdlr: [],
  36569. mdat: [],
  36570. mdhd: [],
  36571. mdia: [],
  36572. mfhd: [],
  36573. minf: [],
  36574. moof: [],
  36575. moov: [],
  36576. mp4a: [],
  36577. // codingname
  36578. mvex: [],
  36579. mvhd: [],
  36580. pasp: [],
  36581. sdtp: [],
  36582. smhd: [],
  36583. stbl: [],
  36584. stco: [],
  36585. stsc: [],
  36586. stsd: [],
  36587. stsz: [],
  36588. stts: [],
  36589. styp: [],
  36590. tfdt: [],
  36591. tfhd: [],
  36592. traf: [],
  36593. trak: [],
  36594. trun: [],
  36595. trex: [],
  36596. tkhd: [],
  36597. vmhd: []
  36598. }; // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
  36599. // don't throw an error
  36600. if (typeof Uint8Array === 'undefined') {
  36601. return;
  36602. }
  36603. for (i in types) {
  36604. if (types.hasOwnProperty(i)) {
  36605. types[i] = [i.charCodeAt(0), i.charCodeAt(1), i.charCodeAt(2), i.charCodeAt(3)];
  36606. }
  36607. }
  36608. MAJOR_BRAND = new Uint8Array(['i'.charCodeAt(0), 's'.charCodeAt(0), 'o'.charCodeAt(0), 'm'.charCodeAt(0)]);
  36609. AVC1_BRAND = new Uint8Array(['a'.charCodeAt(0), 'v'.charCodeAt(0), 'c'.charCodeAt(0), '1'.charCodeAt(0)]);
  36610. MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
  36611. VIDEO_HDLR = new Uint8Array([0x00, // version 0
  36612. 0x00, 0x00, 0x00, // flags
  36613. 0x00, 0x00, 0x00, 0x00, // pre_defined
  36614. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  36615. 0x00, 0x00, 0x00, 0x00, // reserved
  36616. 0x00, 0x00, 0x00, 0x00, // reserved
  36617. 0x00, 0x00, 0x00, 0x00, // reserved
  36618. 0x56, 0x69, 0x64, 0x65, 0x6f, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  36619. ]);
  36620. AUDIO_HDLR = new Uint8Array([0x00, // version 0
  36621. 0x00, 0x00, 0x00, // flags
  36622. 0x00, 0x00, 0x00, 0x00, // pre_defined
  36623. 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
  36624. 0x00, 0x00, 0x00, 0x00, // reserved
  36625. 0x00, 0x00, 0x00, 0x00, // reserved
  36626. 0x00, 0x00, 0x00, 0x00, // reserved
  36627. 0x53, 0x6f, 0x75, 0x6e, 0x64, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  36628. ]);
  36629. HDLR_TYPES = {
  36630. video: VIDEO_HDLR,
  36631. audio: AUDIO_HDLR
  36632. };
  36633. DREF = new Uint8Array([0x00, // version 0
  36634. 0x00, 0x00, 0x00, // flags
  36635. 0x00, 0x00, 0x00, 0x01, // entry_count
  36636. 0x00, 0x00, 0x00, 0x0c, // entry_size
  36637. 0x75, 0x72, 0x6c, 0x20, // 'url' type
  36638. 0x00, // version 0
  36639. 0x00, 0x00, 0x01 // entry_flags
  36640. ]);
  36641. SMHD = new Uint8Array([0x00, // version
  36642. 0x00, 0x00, 0x00, // flags
  36643. 0x00, 0x00, // balance, 0 means centered
  36644. 0x00, 0x00 // reserved
  36645. ]);
  36646. STCO = new Uint8Array([0x00, // version
  36647. 0x00, 0x00, 0x00, // flags
  36648. 0x00, 0x00, 0x00, 0x00 // entry_count
  36649. ]);
  36650. STSC = STCO;
  36651. STSZ = new Uint8Array([0x00, // version
  36652. 0x00, 0x00, 0x00, // flags
  36653. 0x00, 0x00, 0x00, 0x00, // sample_size
  36654. 0x00, 0x00, 0x00, 0x00 // sample_count
  36655. ]);
  36656. STTS = STCO;
  36657. VMHD = new Uint8Array([0x00, // version
  36658. 0x00, 0x00, 0x01, // flags
  36659. 0x00, 0x00, // graphicsmode
  36660. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // opcolor
  36661. ]);
  36662. })();
  36663. box = function box(type) {
  36664. var payload = [],
  36665. size = 0,
  36666. i,
  36667. result,
  36668. view;
  36669. for (i = 1; i < arguments.length; i++) {
  36670. payload.push(arguments[i]);
  36671. }
  36672. i = payload.length; // calculate the total size we need to allocate
  36673. while (i--) {
  36674. size += payload[i].byteLength;
  36675. }
  36676. result = new Uint8Array(size + 8);
  36677. view = new DataView(result.buffer, result.byteOffset, result.byteLength);
  36678. view.setUint32(0, result.byteLength);
  36679. result.set(type, 4); // copy the payload into the result
  36680. for (i = 0, size = 8; i < payload.length; i++) {
  36681. result.set(payload[i], size);
  36682. size += payload[i].byteLength;
  36683. }
  36684. return result;
  36685. };
  36686. dinf = function dinf() {
  36687. return box(types.dinf, box(types.dref, DREF));
  36688. };
  36689. esds = function esds(track) {
  36690. return box(types.esds, new Uint8Array([0x00, // version
  36691. 0x00, 0x00, 0x00, // flags
  36692. // ES_Descriptor
  36693. 0x03, // tag, ES_DescrTag
  36694. 0x19, // length
  36695. 0x00, 0x00, // ES_ID
  36696. 0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority
  36697. // DecoderConfigDescriptor
  36698. 0x04, // tag, DecoderConfigDescrTag
  36699. 0x11, // length
  36700. 0x40, // object type
  36701. 0x15, // streamType
  36702. 0x00, 0x06, 0x00, // bufferSizeDB
  36703. 0x00, 0x00, 0xda, 0xc0, // maxBitrate
  36704. 0x00, 0x00, 0xda, 0xc0, // avgBitrate
  36705. // DecoderSpecificInfo
  36706. 0x05, // tag, DecoderSpecificInfoTag
  36707. 0x02, // length
  36708. // ISO/IEC 14496-3, AudioSpecificConfig
  36709. // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
  36710. track.audioobjecttype << 3 | track.samplingfrequencyindex >>> 1, track.samplingfrequencyindex << 7 | track.channelcount << 3, 0x06, 0x01, 0x02 // GASpecificConfig
  36711. ]));
  36712. };
  36713. ftyp = function ftyp() {
  36714. return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
  36715. };
  36716. hdlr = function hdlr(type) {
  36717. return box(types.hdlr, HDLR_TYPES[type]);
  36718. };
  36719. mdat = function mdat(data) {
  36720. return box(types.mdat, data);
  36721. };
  36722. mdhd = function mdhd(track) {
  36723. var result = new Uint8Array([0x00, // version 0
  36724. 0x00, 0x00, 0x00, // flags
  36725. 0x00, 0x00, 0x00, 0x02, // creation_time
  36726. 0x00, 0x00, 0x00, 0x03, // modification_time
  36727. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  36728. track.duration >>> 24 & 0xFF, track.duration >>> 16 & 0xFF, track.duration >>> 8 & 0xFF, track.duration & 0xFF, // duration
  36729. 0x55, 0xc4, // 'und' language (undetermined)
  36730. 0x00, 0x00]); // Use the sample rate from the track metadata, when it is
  36731. // defined. The sample rate can be parsed out of an ADTS header, for
  36732. // instance.
  36733. if (track.samplerate) {
  36734. result[12] = track.samplerate >>> 24 & 0xFF;
  36735. result[13] = track.samplerate >>> 16 & 0xFF;
  36736. result[14] = track.samplerate >>> 8 & 0xFF;
  36737. result[15] = track.samplerate & 0xFF;
  36738. }
  36739. return box(types.mdhd, result);
  36740. };
  36741. mdia = function mdia(track) {
  36742. return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
  36743. };
  36744. mfhd = function mfhd(sequenceNumber) {
  36745. return box(types.mfhd, new Uint8Array([0x00, 0x00, 0x00, 0x00, // flags
  36746. (sequenceNumber & 0xFF000000) >> 24, (sequenceNumber & 0xFF0000) >> 16, (sequenceNumber & 0xFF00) >> 8, sequenceNumber & 0xFF // sequence_number
  36747. ]));
  36748. };
  36749. minf = function minf(track) {
  36750. return box(types.minf, track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD), dinf(), stbl(track));
  36751. };
  36752. moof = function moof(sequenceNumber, tracks) {
  36753. var trackFragments = [],
  36754. i = tracks.length; // build traf boxes for each track fragment
  36755. while (i--) {
  36756. trackFragments[i] = traf(tracks[i]);
  36757. }
  36758. return box.apply(null, [types.moof, mfhd(sequenceNumber)].concat(trackFragments));
  36759. };
  36760. /**
  36761. * Returns a movie box.
  36762. * @param tracks {array} the tracks associated with this movie
  36763. * @see ISO/IEC 14496-12:2012(E), section 8.2.1
  36764. */
  36765. moov = function moov(tracks) {
  36766. var i = tracks.length,
  36767. boxes = [];
  36768. while (i--) {
  36769. boxes[i] = trak(tracks[i]);
  36770. }
  36771. return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
  36772. };
  36773. mvex = function mvex(tracks) {
  36774. var i = tracks.length,
  36775. boxes = [];
  36776. while (i--) {
  36777. boxes[i] = trex(tracks[i]);
  36778. }
  36779. return box.apply(null, [types.mvex].concat(boxes));
  36780. };
  36781. mvhd = function mvhd(duration) {
  36782. var bytes = new Uint8Array([0x00, // version 0
  36783. 0x00, 0x00, 0x00, // flags
  36784. 0x00, 0x00, 0x00, 0x01, // creation_time
  36785. 0x00, 0x00, 0x00, 0x02, // modification_time
  36786. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  36787. (duration & 0xFF000000) >> 24, (duration & 0xFF0000) >> 16, (duration & 0xFF00) >> 8, duration & 0xFF, // duration
  36788. 0x00, 0x01, 0x00, 0x00, // 1.0 rate
  36789. 0x01, 0x00, // 1.0 volume
  36790. 0x00, 0x00, // reserved
  36791. 0x00, 0x00, 0x00, 0x00, // reserved
  36792. 0x00, 0x00, 0x00, 0x00, // reserved
  36793. 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
  36794. 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
  36795. 0xff, 0xff, 0xff, 0xff // next_track_ID
  36796. ]);
  36797. return box(types.mvhd, bytes);
  36798. };
  36799. sdtp = function sdtp(track) {
  36800. var samples = track.samples || [],
  36801. bytes = new Uint8Array(4 + samples.length),
  36802. flags,
  36803. i; // leave the full box header (4 bytes) all zero
  36804. // write the sample table
  36805. for (i = 0; i < samples.length; i++) {
  36806. flags = samples[i].flags;
  36807. bytes[i + 4] = flags.dependsOn << 4 | flags.isDependedOn << 2 | flags.hasRedundancy;
  36808. }
  36809. return box(types.sdtp, bytes);
  36810. };
  36811. stbl = function stbl(track) {
  36812. return box(types.stbl, stsd(track), box(types.stts, STTS), box(types.stsc, STSC), box(types.stsz, STSZ), box(types.stco, STCO));
  36813. };
  36814. (function () {
  36815. var videoSample, audioSample;
  36816. stsd = function stsd(track) {
  36817. return box(types.stsd, new Uint8Array([0x00, // version 0
  36818. 0x00, 0x00, 0x00, // flags
  36819. 0x00, 0x00, 0x00, 0x01]), track.type === 'video' ? videoSample(track) : audioSample(track));
  36820. };
  36821. videoSample = function videoSample(track) {
  36822. var sps = track.sps || [],
  36823. pps = track.pps || [],
  36824. sequenceParameterSets = [],
  36825. pictureParameterSets = [],
  36826. i,
  36827. avc1Box; // assemble the SPSs
  36828. for (i = 0; i < sps.length; i++) {
  36829. sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
  36830. sequenceParameterSets.push(sps[i].byteLength & 0xFF); // sequenceParameterSetLength
  36831. sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
  36832. } // assemble the PPSs
  36833. for (i = 0; i < pps.length; i++) {
  36834. pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
  36835. pictureParameterSets.push(pps[i].byteLength & 0xFF);
  36836. pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
  36837. }
  36838. avc1Box = [types.avc1, new Uint8Array([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  36839. 0x00, 0x01, // data_reference_index
  36840. 0x00, 0x00, // pre_defined
  36841. 0x00, 0x00, // reserved
  36842. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // pre_defined
  36843. (track.width & 0xff00) >> 8, track.width & 0xff, // width
  36844. (track.height & 0xff00) >> 8, track.height & 0xff, // height
  36845. 0x00, 0x48, 0x00, 0x00, // horizresolution
  36846. 0x00, 0x48, 0x00, 0x00, // vertresolution
  36847. 0x00, 0x00, 0x00, 0x00, // reserved
  36848. 0x00, 0x01, // frame_count
  36849. 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
  36850. 0x00, 0x18, // depth = 24
  36851. 0x11, 0x11 // pre_defined = -1
  36852. ]), box(types.avcC, new Uint8Array([0x01, // configurationVersion
  36853. track.profileIdc, // AVCProfileIndication
  36854. track.profileCompatibility, // profile_compatibility
  36855. track.levelIdc, // AVCLevelIndication
  36856. 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
  36857. ].concat([sps.length], // numOfSequenceParameterSets
  36858. sequenceParameterSets, // "SPS"
  36859. [pps.length], // numOfPictureParameterSets
  36860. pictureParameterSets // "PPS"
  36861. ))), box(types.btrt, new Uint8Array([0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
  36862. 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
  36863. 0x00, 0x2d, 0xc6, 0xc0 // avgBitrate
  36864. ]))];
  36865. if (track.sarRatio) {
  36866. var hSpacing = track.sarRatio[0],
  36867. vSpacing = track.sarRatio[1];
  36868. 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])));
  36869. }
  36870. return box.apply(null, avc1Box);
  36871. };
  36872. audioSample = function audioSample(track) {
  36873. return box(types.mp4a, new Uint8Array([// SampleEntry, ISO/IEC 14496-12
  36874. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  36875. 0x00, 0x01, // data_reference_index
  36876. // AudioSampleEntry, ISO/IEC 14496-12
  36877. 0x00, 0x00, 0x00, 0x00, // reserved
  36878. 0x00, 0x00, 0x00, 0x00, // reserved
  36879. (track.channelcount & 0xff00) >> 8, track.channelcount & 0xff, // channelcount
  36880. (track.samplesize & 0xff00) >> 8, track.samplesize & 0xff, // samplesize
  36881. 0x00, 0x00, // pre_defined
  36882. 0x00, 0x00, // reserved
  36883. (track.samplerate & 0xff00) >> 8, track.samplerate & 0xff, 0x00, 0x00 // samplerate, 16.16
  36884. // MP4AudioSampleEntry, ISO/IEC 14496-14
  36885. ]), esds(track));
  36886. };
  36887. })();
  36888. tkhd = function tkhd(track) {
  36889. var result = new Uint8Array([0x00, // version 0
  36890. 0x00, 0x00, 0x07, // flags
  36891. 0x00, 0x00, 0x00, 0x00, // creation_time
  36892. 0x00, 0x00, 0x00, 0x00, // modification_time
  36893. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  36894. 0x00, 0x00, 0x00, 0x00, // reserved
  36895. (track.duration & 0xFF000000) >> 24, (track.duration & 0xFF0000) >> 16, (track.duration & 0xFF00) >> 8, track.duration & 0xFF, // duration
  36896. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // reserved
  36897. 0x00, 0x00, // layer
  36898. 0x00, 0x00, // alternate_group
  36899. 0x01, 0x00, // non-audio track volume
  36900. 0x00, 0x00, // reserved
  36901. 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
  36902. (track.width & 0xFF00) >> 8, track.width & 0xFF, 0x00, 0x00, // width
  36903. (track.height & 0xFF00) >> 8, track.height & 0xFF, 0x00, 0x00 // height
  36904. ]);
  36905. return box(types.tkhd, result);
  36906. };
  36907. /**
  36908. * Generate a track fragment (traf) box. A traf box collects metadata
  36909. * about tracks in a movie fragment (moof) box.
  36910. */
  36911. traf = function traf(track) {
  36912. var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable, dataOffset, upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
  36913. trackFragmentHeader = box(types.tfhd, new Uint8Array([0x00, // version 0
  36914. 0x00, 0x00, 0x3a, // flags
  36915. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  36916. 0x00, 0x00, 0x00, 0x01, // sample_description_index
  36917. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  36918. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  36919. 0x00, 0x00, 0x00, 0x00 // default_sample_flags
  36920. ]));
  36921. upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / MAX_UINT32);
  36922. lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % MAX_UINT32);
  36923. trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([0x01, // version 1
  36924. 0x00, 0x00, 0x00, // flags
  36925. // baseMediaDecodeTime
  36926. 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
  36927. // the containing moof to the first payload byte of the associated
  36928. // mdat
  36929. dataOffset = 32 + // tfhd
  36930. 20 + // tfdt
  36931. 8 + // traf header
  36932. 16 + // mfhd
  36933. 8 + // moof header
  36934. 8; // mdat header
  36935. // audio tracks require less metadata
  36936. if (track.type === 'audio') {
  36937. trackFragmentRun = trun$1(track, dataOffset);
  36938. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun);
  36939. } // video tracks should contain an independent and disposable samples
  36940. // box (sdtp)
  36941. // generate one and adjust offsets to match
  36942. sampleDependencyTable = sdtp(track);
  36943. trackFragmentRun = trun$1(track, sampleDependencyTable.length + dataOffset);
  36944. return box(types.traf, trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun, sampleDependencyTable);
  36945. };
  36946. /**
  36947. * Generate a track box.
  36948. * @param track {object} a track definition
  36949. * @return {Uint8Array} the track box
  36950. */
  36951. trak = function trak(track) {
  36952. track.duration = track.duration || 0xffffffff;
  36953. return box(types.trak, tkhd(track), mdia(track));
  36954. };
  36955. trex = function trex(track) {
  36956. var result = new Uint8Array([0x00, // version 0
  36957. 0x00, 0x00, 0x00, // flags
  36958. (track.id & 0xFF000000) >> 24, (track.id & 0xFF0000) >> 16, (track.id & 0xFF00) >> 8, track.id & 0xFF, // track_ID
  36959. 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  36960. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  36961. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  36962. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  36963. ]); // the last two bytes of default_sample_flags is the sample
  36964. // degradation priority, a hint about the importance of this sample
  36965. // relative to others. Lower the degradation priority for all sample
  36966. // types other than video.
  36967. if (track.type !== 'video') {
  36968. result[result.length - 1] = 0x00;
  36969. }
  36970. return box(types.trex, result);
  36971. };
  36972. (function () {
  36973. var audioTrun, videoTrun, trunHeader; // This method assumes all samples are uniform. That is, if a
  36974. // duration is present for the first sample, it will be present for
  36975. // all subsequent samples.
  36976. // see ISO/IEC 14496-12:2012, Section 8.8.8.1
  36977. trunHeader = function trunHeader(samples, offset) {
  36978. var durationPresent = 0,
  36979. sizePresent = 0,
  36980. flagsPresent = 0,
  36981. compositionTimeOffset = 0; // trun flag constants
  36982. if (samples.length) {
  36983. if (samples[0].duration !== undefined) {
  36984. durationPresent = 0x1;
  36985. }
  36986. if (samples[0].size !== undefined) {
  36987. sizePresent = 0x2;
  36988. }
  36989. if (samples[0].flags !== undefined) {
  36990. flagsPresent = 0x4;
  36991. }
  36992. if (samples[0].compositionTimeOffset !== undefined) {
  36993. compositionTimeOffset = 0x8;
  36994. }
  36995. }
  36996. return [0x00, // version 0
  36997. 0x00, durationPresent | sizePresent | flagsPresent | compositionTimeOffset, 0x01, // flags
  36998. (samples.length & 0xFF000000) >>> 24, (samples.length & 0xFF0000) >>> 16, (samples.length & 0xFF00) >>> 8, samples.length & 0xFF, // sample_count
  36999. (offset & 0xFF000000) >>> 24, (offset & 0xFF0000) >>> 16, (offset & 0xFF00) >>> 8, offset & 0xFF // data_offset
  37000. ];
  37001. };
  37002. videoTrun = function videoTrun(track, offset) {
  37003. var bytesOffest, bytes, header, samples, sample, i;
  37004. samples = track.samples || [];
  37005. offset += 8 + 12 + 16 * samples.length;
  37006. header = trunHeader(samples, offset);
  37007. bytes = new Uint8Array(header.length + samples.length * 16);
  37008. bytes.set(header);
  37009. bytesOffest = header.length;
  37010. for (i = 0; i < samples.length; i++) {
  37011. sample = samples[i];
  37012. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  37013. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  37014. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  37015. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  37016. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  37017. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  37018. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  37019. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  37020. bytes[bytesOffest++] = sample.flags.isLeading << 2 | sample.flags.dependsOn;
  37021. bytes[bytesOffest++] = sample.flags.isDependedOn << 6 | sample.flags.hasRedundancy << 4 | sample.flags.paddingValue << 1 | sample.flags.isNonSyncSample;
  37022. bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;
  37023. bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags
  37024. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;
  37025. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;
  37026. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;
  37027. bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset
  37028. }
  37029. return box(types.trun, bytes);
  37030. };
  37031. audioTrun = function audioTrun(track, offset) {
  37032. var bytes, bytesOffest, header, samples, sample, i;
  37033. samples = track.samples || [];
  37034. offset += 8 + 12 + 8 * samples.length;
  37035. header = trunHeader(samples, offset);
  37036. bytes = new Uint8Array(header.length + samples.length * 8);
  37037. bytes.set(header);
  37038. bytesOffest = header.length;
  37039. for (i = 0; i < samples.length; i++) {
  37040. sample = samples[i];
  37041. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  37042. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  37043. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  37044. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  37045. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  37046. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  37047. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  37048. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  37049. }
  37050. return box(types.trun, bytes);
  37051. };
  37052. trun$1 = function trun(track, offset) {
  37053. if (track.type === 'audio') {
  37054. return audioTrun(track, offset);
  37055. }
  37056. return videoTrun(track, offset);
  37057. };
  37058. })();
  37059. var mp4Generator = {
  37060. ftyp: ftyp,
  37061. mdat: mdat,
  37062. moof: moof,
  37063. moov: moov,
  37064. initSegment: function initSegment(tracks) {
  37065. var fileType = ftyp(),
  37066. movie = moov(tracks),
  37067. result;
  37068. result = new Uint8Array(fileType.byteLength + movie.byteLength);
  37069. result.set(fileType);
  37070. result.set(movie, fileType.byteLength);
  37071. return result;
  37072. }
  37073. };
  37074. /**
  37075. * mux.js
  37076. *
  37077. * Copyright (c) Brightcove
  37078. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  37079. */
  37080. // Convert an array of nal units into an array of frames with each frame being
  37081. // composed of the nal units that make up that frame
  37082. // Also keep track of cummulative data about the frame from the nal units such
  37083. // as the frame duration, starting pts, etc.
  37084. var groupNalsIntoFrames = function groupNalsIntoFrames(nalUnits) {
  37085. var i,
  37086. currentNal,
  37087. currentFrame = [],
  37088. frames = []; // TODO added for LHLS, make sure this is OK
  37089. frames.byteLength = 0;
  37090. frames.nalCount = 0;
  37091. frames.duration = 0;
  37092. currentFrame.byteLength = 0;
  37093. for (i = 0; i < nalUnits.length; i++) {
  37094. currentNal = nalUnits[i]; // Split on 'aud'-type nal units
  37095. if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
  37096. // Since the very first nal unit is expected to be an AUD
  37097. // only push to the frames array when currentFrame is not empty
  37098. if (currentFrame.length) {
  37099. currentFrame.duration = currentNal.dts - currentFrame.dts; // TODO added for LHLS, make sure this is OK
  37100. frames.byteLength += currentFrame.byteLength;
  37101. frames.nalCount += currentFrame.length;
  37102. frames.duration += currentFrame.duration;
  37103. frames.push(currentFrame);
  37104. }
  37105. currentFrame = [currentNal];
  37106. currentFrame.byteLength = currentNal.data.byteLength;
  37107. currentFrame.pts = currentNal.pts;
  37108. currentFrame.dts = currentNal.dts;
  37109. } else {
  37110. // Specifically flag key frames for ease of use later
  37111. if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
  37112. currentFrame.keyFrame = true;
  37113. }
  37114. currentFrame.duration = currentNal.dts - currentFrame.dts;
  37115. currentFrame.byteLength += currentNal.data.byteLength;
  37116. currentFrame.push(currentNal);
  37117. }
  37118. } // For the last frame, use the duration of the previous frame if we
  37119. // have nothing better to go on
  37120. if (frames.length && (!currentFrame.duration || currentFrame.duration <= 0)) {
  37121. currentFrame.duration = frames[frames.length - 1].duration;
  37122. } // Push the final frame
  37123. // TODO added for LHLS, make sure this is OK
  37124. frames.byteLength += currentFrame.byteLength;
  37125. frames.nalCount += currentFrame.length;
  37126. frames.duration += currentFrame.duration;
  37127. frames.push(currentFrame);
  37128. return frames;
  37129. }; // Convert an array of frames into an array of Gop with each Gop being composed
  37130. // of the frames that make up that Gop
  37131. // Also keep track of cummulative data about the Gop from the frames such as the
  37132. // Gop duration, starting pts, etc.
  37133. var groupFramesIntoGops = function groupFramesIntoGops(frames) {
  37134. var i,
  37135. currentFrame,
  37136. currentGop = [],
  37137. gops = []; // We must pre-set some of the values on the Gop since we
  37138. // keep running totals of these values
  37139. currentGop.byteLength = 0;
  37140. currentGop.nalCount = 0;
  37141. currentGop.duration = 0;
  37142. currentGop.pts = frames[0].pts;
  37143. currentGop.dts = frames[0].dts; // store some metadata about all the Gops
  37144. gops.byteLength = 0;
  37145. gops.nalCount = 0;
  37146. gops.duration = 0;
  37147. gops.pts = frames[0].pts;
  37148. gops.dts = frames[0].dts;
  37149. for (i = 0; i < frames.length; i++) {
  37150. currentFrame = frames[i];
  37151. if (currentFrame.keyFrame) {
  37152. // Since the very first frame is expected to be an keyframe
  37153. // only push to the gops array when currentGop is not empty
  37154. if (currentGop.length) {
  37155. gops.push(currentGop);
  37156. gops.byteLength += currentGop.byteLength;
  37157. gops.nalCount += currentGop.nalCount;
  37158. gops.duration += currentGop.duration;
  37159. }
  37160. currentGop = [currentFrame];
  37161. currentGop.nalCount = currentFrame.length;
  37162. currentGop.byteLength = currentFrame.byteLength;
  37163. currentGop.pts = currentFrame.pts;
  37164. currentGop.dts = currentFrame.dts;
  37165. currentGop.duration = currentFrame.duration;
  37166. } else {
  37167. currentGop.duration += currentFrame.duration;
  37168. currentGop.nalCount += currentFrame.length;
  37169. currentGop.byteLength += currentFrame.byteLength;
  37170. currentGop.push(currentFrame);
  37171. }
  37172. }
  37173. if (gops.length && currentGop.duration <= 0) {
  37174. currentGop.duration = gops[gops.length - 1].duration;
  37175. }
  37176. gops.byteLength += currentGop.byteLength;
  37177. gops.nalCount += currentGop.nalCount;
  37178. gops.duration += currentGop.duration; // push the final Gop
  37179. gops.push(currentGop);
  37180. return gops;
  37181. };
  37182. /*
  37183. * Search for the first keyframe in the GOPs and throw away all frames
  37184. * until that keyframe. Then extend the duration of the pulled keyframe
  37185. * and pull the PTS and DTS of the keyframe so that it covers the time
  37186. * range of the frames that were disposed.
  37187. *
  37188. * @param {Array} gops video GOPs
  37189. * @returns {Array} modified video GOPs
  37190. */
  37191. var extendFirstKeyFrame = function extendFirstKeyFrame(gops) {
  37192. var currentGop;
  37193. if (!gops[0][0].keyFrame && gops.length > 1) {
  37194. // Remove the first GOP
  37195. currentGop = gops.shift();
  37196. gops.byteLength -= currentGop.byteLength;
  37197. gops.nalCount -= currentGop.nalCount; // Extend the first frame of what is now the
  37198. // first gop to cover the time period of the
  37199. // frames we just removed
  37200. gops[0][0].dts = currentGop.dts;
  37201. gops[0][0].pts = currentGop.pts;
  37202. gops[0][0].duration += currentGop.duration;
  37203. }
  37204. return gops;
  37205. };
  37206. /**
  37207. * Default sample object
  37208. * see ISO/IEC 14496-12:2012, section 8.6.4.3
  37209. */
  37210. var createDefaultSample = function createDefaultSample() {
  37211. return {
  37212. size: 0,
  37213. flags: {
  37214. isLeading: 0,
  37215. dependsOn: 1,
  37216. isDependedOn: 0,
  37217. hasRedundancy: 0,
  37218. degradationPriority: 0,
  37219. isNonSyncSample: 1
  37220. }
  37221. };
  37222. };
  37223. /*
  37224. * Collates information from a video frame into an object for eventual
  37225. * entry into an MP4 sample table.
  37226. *
  37227. * @param {Object} frame the video frame
  37228. * @param {Number} dataOffset the byte offset to position the sample
  37229. * @return {Object} object containing sample table info for a frame
  37230. */
  37231. var sampleForFrame = function sampleForFrame(frame, dataOffset) {
  37232. var sample = createDefaultSample();
  37233. sample.dataOffset = dataOffset;
  37234. sample.compositionTimeOffset = frame.pts - frame.dts;
  37235. sample.duration = frame.duration;
  37236. sample.size = 4 * frame.length; // Space for nal unit size
  37237. sample.size += frame.byteLength;
  37238. if (frame.keyFrame) {
  37239. sample.flags.dependsOn = 2;
  37240. sample.flags.isNonSyncSample = 0;
  37241. }
  37242. return sample;
  37243. }; // generate the track's sample table from an array of gops
  37244. var generateSampleTable$1 = function generateSampleTable(gops, baseDataOffset) {
  37245. var h,
  37246. i,
  37247. sample,
  37248. currentGop,
  37249. currentFrame,
  37250. dataOffset = baseDataOffset || 0,
  37251. samples = [];
  37252. for (h = 0; h < gops.length; h++) {
  37253. currentGop = gops[h];
  37254. for (i = 0; i < currentGop.length; i++) {
  37255. currentFrame = currentGop[i];
  37256. sample = sampleForFrame(currentFrame, dataOffset);
  37257. dataOffset += sample.size;
  37258. samples.push(sample);
  37259. }
  37260. }
  37261. return samples;
  37262. }; // generate the track's raw mdat data from an array of gops
  37263. var concatenateNalData = function concatenateNalData(gops) {
  37264. var h,
  37265. i,
  37266. j,
  37267. currentGop,
  37268. currentFrame,
  37269. currentNal,
  37270. dataOffset = 0,
  37271. nalsByteLength = gops.byteLength,
  37272. numberOfNals = gops.nalCount,
  37273. totalByteLength = nalsByteLength + 4 * numberOfNals,
  37274. data = new Uint8Array(totalByteLength),
  37275. view = new DataView(data.buffer); // For each Gop..
  37276. for (h = 0; h < gops.length; h++) {
  37277. currentGop = gops[h]; // For each Frame..
  37278. for (i = 0; i < currentGop.length; i++) {
  37279. currentFrame = currentGop[i]; // For each NAL..
  37280. for (j = 0; j < currentFrame.length; j++) {
  37281. currentNal = currentFrame[j];
  37282. view.setUint32(dataOffset, currentNal.data.byteLength);
  37283. dataOffset += 4;
  37284. data.set(currentNal.data, dataOffset);
  37285. dataOffset += currentNal.data.byteLength;
  37286. }
  37287. }
  37288. }
  37289. return data;
  37290. }; // generate the track's sample table from a frame
  37291. var generateSampleTableForFrame = function generateSampleTableForFrame(frame, baseDataOffset) {
  37292. var sample,
  37293. dataOffset = baseDataOffset || 0,
  37294. samples = [];
  37295. sample = sampleForFrame(frame, dataOffset);
  37296. samples.push(sample);
  37297. return samples;
  37298. }; // generate the track's raw mdat data from a frame
  37299. var concatenateNalDataForFrame = function concatenateNalDataForFrame(frame) {
  37300. var i,
  37301. currentNal,
  37302. dataOffset = 0,
  37303. nalsByteLength = frame.byteLength,
  37304. numberOfNals = frame.length,
  37305. totalByteLength = nalsByteLength + 4 * numberOfNals,
  37306. data = new Uint8Array(totalByteLength),
  37307. view = new DataView(data.buffer); // For each NAL..
  37308. for (i = 0; i < frame.length; i++) {
  37309. currentNal = frame[i];
  37310. view.setUint32(dataOffset, currentNal.data.byteLength);
  37311. dataOffset += 4;
  37312. data.set(currentNal.data, dataOffset);
  37313. dataOffset += currentNal.data.byteLength;
  37314. }
  37315. return data;
  37316. };
  37317. var frameUtils = {
  37318. groupNalsIntoFrames: groupNalsIntoFrames,
  37319. groupFramesIntoGops: groupFramesIntoGops,
  37320. extendFirstKeyFrame: extendFirstKeyFrame,
  37321. generateSampleTable: generateSampleTable$1,
  37322. concatenateNalData: concatenateNalData,
  37323. generateSampleTableForFrame: generateSampleTableForFrame,
  37324. concatenateNalDataForFrame: concatenateNalDataForFrame
  37325. };
  37326. /**
  37327. * mux.js
  37328. *
  37329. * Copyright (c) Brightcove
  37330. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  37331. */
  37332. var highPrefix = [33, 16, 5, 32, 164, 27];
  37333. var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
  37334. var zeroFill = function zeroFill(count) {
  37335. var a = [];
  37336. while (count--) {
  37337. a.push(0);
  37338. }
  37339. return a;
  37340. };
  37341. var makeTable = function makeTable(metaTable) {
  37342. return Object.keys(metaTable).reduce(function (obj, key) {
  37343. obj[key] = new Uint8Array(metaTable[key].reduce(function (arr, part) {
  37344. return arr.concat(part);
  37345. }, []));
  37346. return obj;
  37347. }, {});
  37348. };
  37349. var silence;
  37350. var silence_1 = function silence_1() {
  37351. if (!silence) {
  37352. // Frames-of-silence to use for filling in missing AAC frames
  37353. var coneOfSilence = {
  37354. 96000: [highPrefix, [227, 64], zeroFill(154), [56]],
  37355. 88200: [highPrefix, [231], zeroFill(170), [56]],
  37356. 64000: [highPrefix, [248, 192], zeroFill(240), [56]],
  37357. 48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
  37358. 44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
  37359. 32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
  37360. 24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
  37361. 16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
  37362. 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]],
  37363. 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]],
  37364. 8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
  37365. };
  37366. silence = makeTable(coneOfSilence);
  37367. }
  37368. return silence;
  37369. };
  37370. /**
  37371. * mux.js
  37372. *
  37373. * Copyright (c) Brightcove
  37374. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  37375. */
  37376. var ONE_SECOND_IN_TS$4 = 90000,
  37377. // 90kHz clock
  37378. secondsToVideoTs,
  37379. secondsToAudioTs,
  37380. videoTsToSeconds,
  37381. audioTsToSeconds,
  37382. audioTsToVideoTs,
  37383. videoTsToAudioTs,
  37384. metadataTsToSeconds;
  37385. secondsToVideoTs = function secondsToVideoTs(seconds) {
  37386. return seconds * ONE_SECOND_IN_TS$4;
  37387. };
  37388. secondsToAudioTs = function secondsToAudioTs(seconds, sampleRate) {
  37389. return seconds * sampleRate;
  37390. };
  37391. videoTsToSeconds = function videoTsToSeconds(timestamp) {
  37392. return timestamp / ONE_SECOND_IN_TS$4;
  37393. };
  37394. audioTsToSeconds = function audioTsToSeconds(timestamp, sampleRate) {
  37395. return timestamp / sampleRate;
  37396. };
  37397. audioTsToVideoTs = function audioTsToVideoTs(timestamp, sampleRate) {
  37398. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  37399. };
  37400. videoTsToAudioTs = function videoTsToAudioTs(timestamp, sampleRate) {
  37401. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  37402. };
  37403. /**
  37404. * Adjust ID3 tag or caption timing information by the timeline pts values
  37405. * (if keepOriginalTimestamps is false) and convert to seconds
  37406. */
  37407. metadataTsToSeconds = function metadataTsToSeconds(timestamp, timelineStartPts, keepOriginalTimestamps) {
  37408. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  37409. };
  37410. var clock = {
  37411. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS$4,
  37412. secondsToVideoTs: secondsToVideoTs,
  37413. secondsToAudioTs: secondsToAudioTs,
  37414. videoTsToSeconds: videoTsToSeconds,
  37415. audioTsToSeconds: audioTsToSeconds,
  37416. audioTsToVideoTs: audioTsToVideoTs,
  37417. videoTsToAudioTs: videoTsToAudioTs,
  37418. metadataTsToSeconds: metadataTsToSeconds
  37419. };
  37420. /**
  37421. * mux.js
  37422. *
  37423. * Copyright (c) Brightcove
  37424. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  37425. */
  37426. /**
  37427. * Sum the `byteLength` properties of the data in each AAC frame
  37428. */
  37429. var sumFrameByteLengths = function sumFrameByteLengths(array) {
  37430. var i,
  37431. currentObj,
  37432. sum = 0; // sum the byteLength's all each nal unit in the frame
  37433. for (i = 0; i < array.length; i++) {
  37434. currentObj = array[i];
  37435. sum += currentObj.data.byteLength;
  37436. }
  37437. return sum;
  37438. }; // Possibly pad (prefix) the audio track with silence if appending this track
  37439. // would lead to the introduction of a gap in the audio buffer
  37440. var prefixWithSilence = function prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime) {
  37441. var baseMediaDecodeTimeTs,
  37442. frameDuration = 0,
  37443. audioGapDuration = 0,
  37444. audioFillFrameCount = 0,
  37445. audioFillDuration = 0,
  37446. silentFrame,
  37447. i,
  37448. firstFrame;
  37449. if (!frames.length) {
  37450. return;
  37451. }
  37452. baseMediaDecodeTimeTs = clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate); // determine frame clock duration based on sample rate, round up to avoid overfills
  37453. frameDuration = Math.ceil(clock.ONE_SECOND_IN_TS / (track.samplerate / 1024));
  37454. if (audioAppendStartTs && videoBaseMediaDecodeTime) {
  37455. // insert the shortest possible amount (audio gap or audio to video gap)
  37456. audioGapDuration = baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime); // number of full frames in the audio gap
  37457. audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
  37458. audioFillDuration = audioFillFrameCount * frameDuration;
  37459. } // don't attempt to fill gaps smaller than a single frame or larger
  37460. // than a half second
  37461. if (audioFillFrameCount < 1 || audioFillDuration > clock.ONE_SECOND_IN_TS / 2) {
  37462. return;
  37463. }
  37464. silentFrame = silence_1()[track.samplerate];
  37465. if (!silentFrame) {
  37466. // we don't have a silent frame pregenerated for the sample rate, so use a frame
  37467. // from the content instead
  37468. silentFrame = frames[0].data;
  37469. }
  37470. for (i = 0; i < audioFillFrameCount; i++) {
  37471. firstFrame = frames[0];
  37472. frames.splice(0, 0, {
  37473. data: silentFrame,
  37474. dts: firstFrame.dts - frameDuration,
  37475. pts: firstFrame.pts - frameDuration
  37476. });
  37477. }
  37478. track.baseMediaDecodeTime -= Math.floor(clock.videoTsToAudioTs(audioFillDuration, track.samplerate));
  37479. return audioFillDuration;
  37480. }; // If the audio segment extends before the earliest allowed dts
  37481. // value, remove AAC frames until starts at or after the earliest
  37482. // allowed DTS so that we don't end up with a negative baseMedia-
  37483. // DecodeTime for the audio track
  37484. var trimAdtsFramesByEarliestDts = function trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts) {
  37485. if (track.minSegmentDts >= earliestAllowedDts) {
  37486. return adtsFrames;
  37487. } // We will need to recalculate the earliest segment Dts
  37488. track.minSegmentDts = Infinity;
  37489. return adtsFrames.filter(function (currentFrame) {
  37490. // If this is an allowed frame, keep it and record it's Dts
  37491. if (currentFrame.dts >= earliestAllowedDts) {
  37492. track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
  37493. track.minSegmentPts = track.minSegmentDts;
  37494. return true;
  37495. } // Otherwise, discard it
  37496. return false;
  37497. });
  37498. }; // generate the track's raw mdat data from an array of frames
  37499. var generateSampleTable = function generateSampleTable(frames) {
  37500. var i,
  37501. currentFrame,
  37502. samples = [];
  37503. for (i = 0; i < frames.length; i++) {
  37504. currentFrame = frames[i];
  37505. samples.push({
  37506. size: currentFrame.data.byteLength,
  37507. duration: 1024 // For AAC audio, all samples contain 1024 samples
  37508. });
  37509. }
  37510. return samples;
  37511. }; // generate the track's sample table from an array of frames
  37512. var concatenateFrameData = function concatenateFrameData(frames) {
  37513. var i,
  37514. currentFrame,
  37515. dataOffset = 0,
  37516. data = new Uint8Array(sumFrameByteLengths(frames));
  37517. for (i = 0; i < frames.length; i++) {
  37518. currentFrame = frames[i];
  37519. data.set(currentFrame.data, dataOffset);
  37520. dataOffset += currentFrame.data.byteLength;
  37521. }
  37522. return data;
  37523. };
  37524. var audioFrameUtils = {
  37525. prefixWithSilence: prefixWithSilence,
  37526. trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
  37527. generateSampleTable: generateSampleTable,
  37528. concatenateFrameData: concatenateFrameData
  37529. };
  37530. /**
  37531. * mux.js
  37532. *
  37533. * Copyright (c) Brightcove
  37534. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  37535. */
  37536. var ONE_SECOND_IN_TS$3 = clock.ONE_SECOND_IN_TS;
  37537. /**
  37538. * Store information about the start and end of the track and the
  37539. * duration for each frame/sample we process in order to calculate
  37540. * the baseMediaDecodeTime
  37541. */
  37542. var collectDtsInfo = function collectDtsInfo(track, data) {
  37543. if (typeof data.pts === 'number') {
  37544. if (track.timelineStartInfo.pts === undefined) {
  37545. track.timelineStartInfo.pts = data.pts;
  37546. }
  37547. if (track.minSegmentPts === undefined) {
  37548. track.minSegmentPts = data.pts;
  37549. } else {
  37550. track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
  37551. }
  37552. if (track.maxSegmentPts === undefined) {
  37553. track.maxSegmentPts = data.pts;
  37554. } else {
  37555. track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
  37556. }
  37557. }
  37558. if (typeof data.dts === 'number') {
  37559. if (track.timelineStartInfo.dts === undefined) {
  37560. track.timelineStartInfo.dts = data.dts;
  37561. }
  37562. if (track.minSegmentDts === undefined) {
  37563. track.minSegmentDts = data.dts;
  37564. } else {
  37565. track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
  37566. }
  37567. if (track.maxSegmentDts === undefined) {
  37568. track.maxSegmentDts = data.dts;
  37569. } else {
  37570. track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
  37571. }
  37572. }
  37573. };
  37574. /**
  37575. * Clear values used to calculate the baseMediaDecodeTime between
  37576. * tracks
  37577. */
  37578. var clearDtsInfo = function clearDtsInfo(track) {
  37579. delete track.minSegmentDts;
  37580. delete track.maxSegmentDts;
  37581. delete track.minSegmentPts;
  37582. delete track.maxSegmentPts;
  37583. };
  37584. /**
  37585. * Calculate the track's baseMediaDecodeTime based on the earliest
  37586. * DTS the transmuxer has ever seen and the minimum DTS for the
  37587. * current track
  37588. * @param track {object} track metadata configuration
  37589. * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
  37590. * in the source; false to adjust the first segment to start at 0.
  37591. */
  37592. var calculateTrackBaseMediaDecodeTime = function calculateTrackBaseMediaDecodeTime(track, keepOriginalTimestamps) {
  37593. var baseMediaDecodeTime,
  37594. scale,
  37595. minSegmentDts = track.minSegmentDts; // Optionally adjust the time so the first segment starts at zero.
  37596. if (!keepOriginalTimestamps) {
  37597. minSegmentDts -= track.timelineStartInfo.dts;
  37598. } // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
  37599. // we want the start of the first segment to be placed
  37600. baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime; // Add to that the distance this segment is from the very first
  37601. baseMediaDecodeTime += minSegmentDts; // baseMediaDecodeTime must not become negative
  37602. baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
  37603. if (track.type === 'audio') {
  37604. // Audio has a different clock equal to the sampling_rate so we need to
  37605. // scale the PTS values into the clock rate of the track
  37606. scale = track.samplerate / ONE_SECOND_IN_TS$3;
  37607. baseMediaDecodeTime *= scale;
  37608. baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
  37609. }
  37610. return baseMediaDecodeTime;
  37611. };
  37612. var trackDecodeInfo = {
  37613. clearDtsInfo: clearDtsInfo,
  37614. calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
  37615. collectDtsInfo: collectDtsInfo
  37616. };
  37617. /**
  37618. * mux.js
  37619. *
  37620. * Copyright (c) Brightcove
  37621. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  37622. *
  37623. * Reads in-band caption information from a video elementary
  37624. * stream. Captions must follow the CEA-708 standard for injection
  37625. * into an MPEG-2 transport streams.
  37626. * @see https://en.wikipedia.org/wiki/CEA-708
  37627. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  37628. */
  37629. // payload type field to indicate how they are to be
  37630. // interpreted. CEAS-708 caption content is always transmitted with
  37631. // payload type 0x04.
  37632. var USER_DATA_REGISTERED_ITU_T_T35 = 4,
  37633. RBSP_TRAILING_BITS = 128;
  37634. /**
  37635. * Parse a supplemental enhancement information (SEI) NAL unit.
  37636. * Stops parsing once a message of type ITU T T35 has been found.
  37637. *
  37638. * @param bytes {Uint8Array} the bytes of a SEI NAL unit
  37639. * @return {object} the parsed SEI payload
  37640. * @see Rec. ITU-T H.264, 7.3.2.3.1
  37641. */
  37642. var parseSei = function parseSei(bytes) {
  37643. var i = 0,
  37644. result = {
  37645. payloadType: -1,
  37646. payloadSize: 0
  37647. },
  37648. payloadType = 0,
  37649. payloadSize = 0; // go through the sei_rbsp parsing each each individual sei_message
  37650. while (i < bytes.byteLength) {
  37651. // stop once we have hit the end of the sei_rbsp
  37652. if (bytes[i] === RBSP_TRAILING_BITS) {
  37653. break;
  37654. } // Parse payload type
  37655. while (bytes[i] === 0xFF) {
  37656. payloadType += 255;
  37657. i++;
  37658. }
  37659. payloadType += bytes[i++]; // Parse payload size
  37660. while (bytes[i] === 0xFF) {
  37661. payloadSize += 255;
  37662. i++;
  37663. }
  37664. payloadSize += bytes[i++]; // this sei_message is a 608/708 caption so save it and break
  37665. // there can only ever be one caption message in a frame's sei
  37666. if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
  37667. var userIdentifier = String.fromCharCode(bytes[i + 3], bytes[i + 4], bytes[i + 5], bytes[i + 6]);
  37668. if (userIdentifier === 'GA94') {
  37669. result.payloadType = payloadType;
  37670. result.payloadSize = payloadSize;
  37671. result.payload = bytes.subarray(i, i + payloadSize);
  37672. break;
  37673. } else {
  37674. result.payload = void 0;
  37675. }
  37676. } // skip the payload and parse the next message
  37677. i += payloadSize;
  37678. payloadType = 0;
  37679. payloadSize = 0;
  37680. }
  37681. return result;
  37682. }; // see ANSI/SCTE 128-1 (2013), section 8.1
  37683. var parseUserData = function parseUserData(sei) {
  37684. // itu_t_t35_contry_code must be 181 (United States) for
  37685. // captions
  37686. if (sei.payload[0] !== 181) {
  37687. return null;
  37688. } // itu_t_t35_provider_code should be 49 (ATSC) for captions
  37689. if ((sei.payload[1] << 8 | sei.payload[2]) !== 49) {
  37690. return null;
  37691. } // the user_identifier should be "GA94" to indicate ATSC1 data
  37692. if (String.fromCharCode(sei.payload[3], sei.payload[4], sei.payload[5], sei.payload[6]) !== 'GA94') {
  37693. return null;
  37694. } // finally, user_data_type_code should be 0x03 for caption data
  37695. if (sei.payload[7] !== 0x03) {
  37696. return null;
  37697. } // return the user_data_type_structure and strip the trailing
  37698. // marker bits
  37699. return sei.payload.subarray(8, sei.payload.length - 1);
  37700. }; // see CEA-708-D, section 4.4
  37701. var parseCaptionPackets = function parseCaptionPackets(pts, userData) {
  37702. var results = [],
  37703. i,
  37704. count,
  37705. offset,
  37706. data; // if this is just filler, return immediately
  37707. if (!(userData[0] & 0x40)) {
  37708. return results;
  37709. } // parse out the cc_data_1 and cc_data_2 fields
  37710. count = userData[0] & 0x1f;
  37711. for (i = 0; i < count; i++) {
  37712. offset = i * 3;
  37713. data = {
  37714. type: userData[offset + 2] & 0x03,
  37715. pts: pts
  37716. }; // capture cc data when cc_valid is 1
  37717. if (userData[offset + 2] & 0x04) {
  37718. data.ccData = userData[offset + 3] << 8 | userData[offset + 4];
  37719. results.push(data);
  37720. }
  37721. }
  37722. return results;
  37723. };
  37724. var discardEmulationPreventionBytes$1 = function discardEmulationPreventionBytes(data) {
  37725. var length = data.byteLength,
  37726. emulationPreventionBytesPositions = [],
  37727. i = 1,
  37728. newLength,
  37729. newData; // Find all `Emulation Prevention Bytes`
  37730. while (i < length - 2) {
  37731. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  37732. emulationPreventionBytesPositions.push(i + 2);
  37733. i += 2;
  37734. } else {
  37735. i++;
  37736. }
  37737. } // If no Emulation Prevention Bytes were found just return the original
  37738. // array
  37739. if (emulationPreventionBytesPositions.length === 0) {
  37740. return data;
  37741. } // Create a new array to hold the NAL unit data
  37742. newLength = length - emulationPreventionBytesPositions.length;
  37743. newData = new Uint8Array(newLength);
  37744. var sourceIndex = 0;
  37745. for (i = 0; i < newLength; sourceIndex++, i++) {
  37746. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  37747. // Skip this byte
  37748. sourceIndex++; // Remove this position index
  37749. emulationPreventionBytesPositions.shift();
  37750. }
  37751. newData[i] = data[sourceIndex];
  37752. }
  37753. return newData;
  37754. }; // exports
  37755. var captionPacketParser = {
  37756. parseSei: parseSei,
  37757. parseUserData: parseUserData,
  37758. parseCaptionPackets: parseCaptionPackets,
  37759. discardEmulationPreventionBytes: discardEmulationPreventionBytes$1,
  37760. USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
  37761. }; // Link To Transport
  37762. // -----------------
  37763. var CaptionStream$1 = function CaptionStream(options) {
  37764. options = options || {};
  37765. CaptionStream.prototype.init.call(this); // parse708captions flag, default to true
  37766. this.parse708captions_ = typeof options.parse708captions === 'boolean' ? options.parse708captions : true;
  37767. this.captionPackets_ = [];
  37768. this.ccStreams_ = [new Cea608Stream(0, 0), // eslint-disable-line no-use-before-define
  37769. new Cea608Stream(0, 1), // eslint-disable-line no-use-before-define
  37770. new Cea608Stream(1, 0), // eslint-disable-line no-use-before-define
  37771. new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
  37772. ];
  37773. if (this.parse708captions_) {
  37774. this.cc708Stream_ = new Cea708Stream({
  37775. captionServices: options.captionServices
  37776. }); // eslint-disable-line no-use-before-define
  37777. }
  37778. this.reset(); // forward data and done events from CCs to this CaptionStream
  37779. this.ccStreams_.forEach(function (cc) {
  37780. cc.on('data', this.trigger.bind(this, 'data'));
  37781. cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
  37782. cc.on('done', this.trigger.bind(this, 'done'));
  37783. }, this);
  37784. if (this.parse708captions_) {
  37785. this.cc708Stream_.on('data', this.trigger.bind(this, 'data'));
  37786. this.cc708Stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));
  37787. this.cc708Stream_.on('done', this.trigger.bind(this, 'done'));
  37788. }
  37789. };
  37790. CaptionStream$1.prototype = new stream();
  37791. CaptionStream$1.prototype.push = function (event) {
  37792. var sei, userData, newCaptionPackets; // only examine SEI NALs
  37793. if (event.nalUnitType !== 'sei_rbsp') {
  37794. return;
  37795. } // parse the sei
  37796. sei = captionPacketParser.parseSei(event.escapedRBSP); // no payload data, skip
  37797. if (!sei.payload) {
  37798. return;
  37799. } // ignore everything but user_data_registered_itu_t_t35
  37800. if (sei.payloadType !== captionPacketParser.USER_DATA_REGISTERED_ITU_T_T35) {
  37801. return;
  37802. } // parse out the user data payload
  37803. userData = captionPacketParser.parseUserData(sei); // ignore unrecognized userData
  37804. if (!userData) {
  37805. return;
  37806. } // Sometimes, the same segment # will be downloaded twice. To stop the
  37807. // caption data from being processed twice, we track the latest dts we've
  37808. // received and ignore everything with a dts before that. However, since
  37809. // data for a specific dts can be split across packets on either side of
  37810. // a segment boundary, we need to make sure we *don't* ignore the packets
  37811. // from the *next* segment that have dts === this.latestDts_. By constantly
  37812. // tracking the number of packets received with dts === this.latestDts_, we
  37813. // know how many should be ignored once we start receiving duplicates.
  37814. if (event.dts < this.latestDts_) {
  37815. // We've started getting older data, so set the flag.
  37816. this.ignoreNextEqualDts_ = true;
  37817. return;
  37818. } else if (event.dts === this.latestDts_ && this.ignoreNextEqualDts_) {
  37819. this.numSameDts_--;
  37820. if (!this.numSameDts_) {
  37821. // We've received the last duplicate packet, time to start processing again
  37822. this.ignoreNextEqualDts_ = false;
  37823. }
  37824. return;
  37825. } // parse out CC data packets and save them for later
  37826. newCaptionPackets = captionPacketParser.parseCaptionPackets(event.pts, userData);
  37827. this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
  37828. if (this.latestDts_ !== event.dts) {
  37829. this.numSameDts_ = 0;
  37830. }
  37831. this.numSameDts_++;
  37832. this.latestDts_ = event.dts;
  37833. };
  37834. CaptionStream$1.prototype.flushCCStreams = function (flushType) {
  37835. this.ccStreams_.forEach(function (cc) {
  37836. return flushType === 'flush' ? cc.flush() : cc.partialFlush();
  37837. }, this);
  37838. };
  37839. CaptionStream$1.prototype.flushStream = function (flushType) {
  37840. // make sure we actually parsed captions before proceeding
  37841. if (!this.captionPackets_.length) {
  37842. this.flushCCStreams(flushType);
  37843. return;
  37844. } // In Chrome, the Array#sort function is not stable so add a
  37845. // presortIndex that we can use to ensure we get a stable-sort
  37846. this.captionPackets_.forEach(function (elem, idx) {
  37847. elem.presortIndex = idx;
  37848. }); // sort caption byte-pairs based on their PTS values
  37849. this.captionPackets_.sort(function (a, b) {
  37850. if (a.pts === b.pts) {
  37851. return a.presortIndex - b.presortIndex;
  37852. }
  37853. return a.pts - b.pts;
  37854. });
  37855. this.captionPackets_.forEach(function (packet) {
  37856. if (packet.type < 2) {
  37857. // Dispatch packet to the right Cea608Stream
  37858. this.dispatchCea608Packet(packet);
  37859. } else {
  37860. // Dispatch packet to the Cea708Stream
  37861. this.dispatchCea708Packet(packet);
  37862. }
  37863. }, this);
  37864. this.captionPackets_.length = 0;
  37865. this.flushCCStreams(flushType);
  37866. };
  37867. CaptionStream$1.prototype.flush = function () {
  37868. return this.flushStream('flush');
  37869. }; // Only called if handling partial data
  37870. CaptionStream$1.prototype.partialFlush = function () {
  37871. return this.flushStream('partialFlush');
  37872. };
  37873. CaptionStream$1.prototype.reset = function () {
  37874. this.latestDts_ = null;
  37875. this.ignoreNextEqualDts_ = false;
  37876. this.numSameDts_ = 0;
  37877. this.activeCea608Channel_ = [null, null];
  37878. this.ccStreams_.forEach(function (ccStream) {
  37879. ccStream.reset();
  37880. });
  37881. }; // From the CEA-608 spec:
  37882. /*
  37883. * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
  37884. * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
  37885. * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
  37886. * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
  37887. * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
  37888. * to switch to captioning or Text.
  37889. */
  37890. // With that in mind, we ignore any data between an XDS control code and a
  37891. // subsequent closed-captioning control code.
  37892. CaptionStream$1.prototype.dispatchCea608Packet = function (packet) {
  37893. // NOTE: packet.type is the CEA608 field
  37894. if (this.setsTextOrXDSActive(packet)) {
  37895. this.activeCea608Channel_[packet.type] = null;
  37896. } else if (this.setsChannel1Active(packet)) {
  37897. this.activeCea608Channel_[packet.type] = 0;
  37898. } else if (this.setsChannel2Active(packet)) {
  37899. this.activeCea608Channel_[packet.type] = 1;
  37900. }
  37901. if (this.activeCea608Channel_[packet.type] === null) {
  37902. // If we haven't received anything to set the active channel, or the
  37903. // packets are Text/XDS data, discard the data; we don't want jumbled
  37904. // captions
  37905. return;
  37906. }
  37907. this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
  37908. };
  37909. CaptionStream$1.prototype.setsChannel1Active = function (packet) {
  37910. return (packet.ccData & 0x7800) === 0x1000;
  37911. };
  37912. CaptionStream$1.prototype.setsChannel2Active = function (packet) {
  37913. return (packet.ccData & 0x7800) === 0x1800;
  37914. };
  37915. CaptionStream$1.prototype.setsTextOrXDSActive = function (packet) {
  37916. return (packet.ccData & 0x7100) === 0x0100 || (packet.ccData & 0x78fe) === 0x102a || (packet.ccData & 0x78fe) === 0x182a;
  37917. };
  37918. CaptionStream$1.prototype.dispatchCea708Packet = function (packet) {
  37919. if (this.parse708captions_) {
  37920. this.cc708Stream_.push(packet);
  37921. }
  37922. }; // ----------------------
  37923. // Session to Application
  37924. // ----------------------
  37925. // This hash maps special and extended character codes to their
  37926. // proper Unicode equivalent. The first one-byte key is just a
  37927. // non-standard character code. The two-byte keys that follow are
  37928. // the extended CEA708 character codes, along with the preceding
  37929. // 0x10 extended character byte to distinguish these codes from
  37930. // non-extended character codes. Every CEA708 character code that
  37931. // is not in this object maps directly to a standard unicode
  37932. // character code.
  37933. // The transparent space and non-breaking transparent space are
  37934. // technically not fully supported since there is no code to
  37935. // make them transparent, so they have normal non-transparent
  37936. // stand-ins.
  37937. // The special closed caption (CC) character isn't a standard
  37938. // unicode character, so a fairly similar unicode character was
  37939. // chosen in it's place.
  37940. var CHARACTER_TRANSLATION_708 = {
  37941. 0x7f: 0x266a,
  37942. // ♪
  37943. 0x1020: 0x20,
  37944. // Transparent Space
  37945. 0x1021: 0xa0,
  37946. // Nob-breaking Transparent Space
  37947. 0x1025: 0x2026,
  37948. // …
  37949. 0x102a: 0x0160,
  37950. // Š
  37951. 0x102c: 0x0152,
  37952. // Œ
  37953. 0x1030: 0x2588,
  37954. // █
  37955. 0x1031: 0x2018,
  37956. // ‘
  37957. 0x1032: 0x2019,
  37958. // ’
  37959. 0x1033: 0x201c,
  37960. // “
  37961. 0x1034: 0x201d,
  37962. // ”
  37963. 0x1035: 0x2022,
  37964. // •
  37965. 0x1039: 0x2122,
  37966. // ™
  37967. 0x103a: 0x0161,
  37968. // š
  37969. 0x103c: 0x0153,
  37970. // œ
  37971. 0x103d: 0x2120,
  37972. // ℠
  37973. 0x103f: 0x0178,
  37974. // Ÿ
  37975. 0x1076: 0x215b,
  37976. // ⅛
  37977. 0x1077: 0x215c,
  37978. // ⅜
  37979. 0x1078: 0x215d,
  37980. // ⅝
  37981. 0x1079: 0x215e,
  37982. // ⅞
  37983. 0x107a: 0x23d0,
  37984. // ⏐
  37985. 0x107b: 0x23a4,
  37986. // ⎤
  37987. 0x107c: 0x23a3,
  37988. // ⎣
  37989. 0x107d: 0x23af,
  37990. // ⎯
  37991. 0x107e: 0x23a6,
  37992. // ⎦
  37993. 0x107f: 0x23a1,
  37994. // ⎡
  37995. 0x10a0: 0x3138 // ㄸ (CC char)
  37996. };
  37997. var get708CharFromCode = function get708CharFromCode(code) {
  37998. var newCode = CHARACTER_TRANSLATION_708[code] || code;
  37999. if (code & 0x1000 && code === newCode) {
  38000. // Invalid extended code
  38001. return '';
  38002. }
  38003. return String.fromCharCode(newCode);
  38004. };
  38005. var within708TextBlock = function within708TextBlock(b) {
  38006. return 0x20 <= b && b <= 0x7f || 0xa0 <= b && b <= 0xff;
  38007. };
  38008. var Cea708Window = function Cea708Window(windowNum) {
  38009. this.windowNum = windowNum;
  38010. this.reset();
  38011. };
  38012. Cea708Window.prototype.reset = function () {
  38013. this.clearText();
  38014. this.pendingNewLine = false;
  38015. this.winAttr = {};
  38016. this.penAttr = {};
  38017. this.penLoc = {};
  38018. this.penColor = {}; // These default values are arbitrary,
  38019. // defineWindow will usually override them
  38020. this.visible = 0;
  38021. this.rowLock = 0;
  38022. this.columnLock = 0;
  38023. this.priority = 0;
  38024. this.relativePositioning = 0;
  38025. this.anchorVertical = 0;
  38026. this.anchorHorizontal = 0;
  38027. this.anchorPoint = 0;
  38028. this.rowCount = 1;
  38029. this.virtualRowCount = this.rowCount + 1;
  38030. this.columnCount = 41;
  38031. this.windowStyle = 0;
  38032. this.penStyle = 0;
  38033. };
  38034. Cea708Window.prototype.getText = function () {
  38035. return this.rows.join('\n');
  38036. };
  38037. Cea708Window.prototype.clearText = function () {
  38038. this.rows = [''];
  38039. this.rowIdx = 0;
  38040. };
  38041. Cea708Window.prototype.newLine = function (pts) {
  38042. if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === 'function') {
  38043. this.beforeRowOverflow(pts);
  38044. }
  38045. if (this.rows.length > 0) {
  38046. this.rows.push('');
  38047. this.rowIdx++;
  38048. } // Show all virtual rows since there's no visible scrolling
  38049. while (this.rows.length > this.virtualRowCount) {
  38050. this.rows.shift();
  38051. this.rowIdx--;
  38052. }
  38053. };
  38054. Cea708Window.prototype.isEmpty = function () {
  38055. if (this.rows.length === 0) {
  38056. return true;
  38057. } else if (this.rows.length === 1) {
  38058. return this.rows[0] === '';
  38059. }
  38060. return false;
  38061. };
  38062. Cea708Window.prototype.addText = function (text) {
  38063. this.rows[this.rowIdx] += text;
  38064. };
  38065. Cea708Window.prototype.backspace = function () {
  38066. if (!this.isEmpty()) {
  38067. var row = this.rows[this.rowIdx];
  38068. this.rows[this.rowIdx] = row.substr(0, row.length - 1);
  38069. }
  38070. };
  38071. var Cea708Service = function Cea708Service(serviceNum, encoding, stream) {
  38072. this.serviceNum = serviceNum;
  38073. this.text = '';
  38074. this.currentWindow = new Cea708Window(-1);
  38075. this.windows = [];
  38076. this.stream = stream; // Try to setup a TextDecoder if an `encoding` value was provided
  38077. if (typeof encoding === 'string') {
  38078. this.createTextDecoder(encoding);
  38079. }
  38080. };
  38081. /**
  38082. * Initialize service windows
  38083. * Must be run before service use
  38084. *
  38085. * @param {Integer} pts PTS value
  38086. * @param {Function} beforeRowOverflow Function to execute before row overflow of a window
  38087. */
  38088. Cea708Service.prototype.init = function (pts, beforeRowOverflow) {
  38089. this.startPts = pts;
  38090. for (var win = 0; win < 8; win++) {
  38091. this.windows[win] = new Cea708Window(win);
  38092. if (typeof beforeRowOverflow === 'function') {
  38093. this.windows[win].beforeRowOverflow = beforeRowOverflow;
  38094. }
  38095. }
  38096. };
  38097. /**
  38098. * Set current window of service to be affected by commands
  38099. *
  38100. * @param {Integer} windowNum Window number
  38101. */
  38102. Cea708Service.prototype.setCurrentWindow = function (windowNum) {
  38103. this.currentWindow = this.windows[windowNum];
  38104. };
  38105. /**
  38106. * Try to create a TextDecoder if it is natively supported
  38107. */
  38108. Cea708Service.prototype.createTextDecoder = function (encoding) {
  38109. if (typeof TextDecoder === 'undefined') {
  38110. this.stream.trigger('log', {
  38111. level: 'warn',
  38112. message: 'The `encoding` option is unsupported without TextDecoder support'
  38113. });
  38114. } else {
  38115. try {
  38116. this.textDecoder_ = new TextDecoder(encoding);
  38117. } catch (error) {
  38118. this.stream.trigger('log', {
  38119. level: 'warn',
  38120. message: 'TextDecoder could not be created with ' + encoding + ' encoding. ' + error
  38121. });
  38122. }
  38123. }
  38124. };
  38125. var Cea708Stream = function Cea708Stream(options) {
  38126. options = options || {};
  38127. Cea708Stream.prototype.init.call(this);
  38128. var self = this;
  38129. var captionServices = options.captionServices || {};
  38130. var captionServiceEncodings = {};
  38131. var serviceProps; // Get service encodings from captionServices option block
  38132. Object.keys(captionServices).forEach(function (serviceName) {
  38133. serviceProps = captionServices[serviceName];
  38134. if (/^SERVICE/.test(serviceName)) {
  38135. captionServiceEncodings[serviceName] = serviceProps.encoding;
  38136. }
  38137. });
  38138. this.serviceEncodings = captionServiceEncodings;
  38139. this.current708Packet = null;
  38140. this.services = {};
  38141. this.push = function (packet) {
  38142. if (packet.type === 3) {
  38143. // 708 packet start
  38144. self.new708Packet();
  38145. self.add708Bytes(packet);
  38146. } else {
  38147. if (self.current708Packet === null) {
  38148. // This should only happen at the start of a file if there's no packet start.
  38149. self.new708Packet();
  38150. }
  38151. self.add708Bytes(packet);
  38152. }
  38153. };
  38154. };
  38155. Cea708Stream.prototype = new stream();
  38156. /**
  38157. * Push current 708 packet, create new 708 packet.
  38158. */
  38159. Cea708Stream.prototype.new708Packet = function () {
  38160. if (this.current708Packet !== null) {
  38161. this.push708Packet();
  38162. }
  38163. this.current708Packet = {
  38164. data: [],
  38165. ptsVals: []
  38166. };
  38167. };
  38168. /**
  38169. * Add pts and both bytes from packet into current 708 packet.
  38170. */
  38171. Cea708Stream.prototype.add708Bytes = function (packet) {
  38172. var data = packet.ccData;
  38173. var byte0 = data >>> 8;
  38174. var byte1 = data & 0xff; // I would just keep a list of packets instead of bytes, but it isn't clear in the spec
  38175. // that service blocks will always line up with byte pairs.
  38176. this.current708Packet.ptsVals.push(packet.pts);
  38177. this.current708Packet.data.push(byte0);
  38178. this.current708Packet.data.push(byte1);
  38179. };
  38180. /**
  38181. * Parse completed 708 packet into service blocks and push each service block.
  38182. */
  38183. Cea708Stream.prototype.push708Packet = function () {
  38184. var packet708 = this.current708Packet;
  38185. var packetData = packet708.data;
  38186. var serviceNum = null;
  38187. var blockSize = null;
  38188. var i = 0;
  38189. var b = packetData[i++];
  38190. packet708.seq = b >> 6;
  38191. packet708.sizeCode = b & 0x3f; // 0b00111111;
  38192. for (; i < packetData.length; i++) {
  38193. b = packetData[i++];
  38194. serviceNum = b >> 5;
  38195. blockSize = b & 0x1f; // 0b00011111
  38196. if (serviceNum === 7 && blockSize > 0) {
  38197. // Extended service num
  38198. b = packetData[i++];
  38199. serviceNum = b;
  38200. }
  38201. this.pushServiceBlock(serviceNum, i, blockSize);
  38202. if (blockSize > 0) {
  38203. i += blockSize - 1;
  38204. }
  38205. }
  38206. };
  38207. /**
  38208. * Parse service block, execute commands, read text.
  38209. *
  38210. * Note: While many of these commands serve important purposes,
  38211. * many others just parse out the parameters or attributes, but
  38212. * nothing is done with them because this is not a full and complete
  38213. * implementation of the entire 708 spec.
  38214. *
  38215. * @param {Integer} serviceNum Service number
  38216. * @param {Integer} start Start index of the 708 packet data
  38217. * @param {Integer} size Block size
  38218. */
  38219. Cea708Stream.prototype.pushServiceBlock = function (serviceNum, start, size) {
  38220. var b;
  38221. var i = start;
  38222. var packetData = this.current708Packet.data;
  38223. var service = this.services[serviceNum];
  38224. if (!service) {
  38225. service = this.initService(serviceNum, i);
  38226. }
  38227. for (; i < start + size && i < packetData.length; i++) {
  38228. b = packetData[i];
  38229. if (within708TextBlock(b)) {
  38230. i = this.handleText(i, service);
  38231. } else if (b === 0x18) {
  38232. i = this.multiByteCharacter(i, service);
  38233. } else if (b === 0x10) {
  38234. i = this.extendedCommands(i, service);
  38235. } else if (0x80 <= b && b <= 0x87) {
  38236. i = this.setCurrentWindow(i, service);
  38237. } else if (0x98 <= b && b <= 0x9f) {
  38238. i = this.defineWindow(i, service);
  38239. } else if (b === 0x88) {
  38240. i = this.clearWindows(i, service);
  38241. } else if (b === 0x8c) {
  38242. i = this.deleteWindows(i, service);
  38243. } else if (b === 0x89) {
  38244. i = this.displayWindows(i, service);
  38245. } else if (b === 0x8a) {
  38246. i = this.hideWindows(i, service);
  38247. } else if (b === 0x8b) {
  38248. i = this.toggleWindows(i, service);
  38249. } else if (b === 0x97) {
  38250. i = this.setWindowAttributes(i, service);
  38251. } else if (b === 0x90) {
  38252. i = this.setPenAttributes(i, service);
  38253. } else if (b === 0x91) {
  38254. i = this.setPenColor(i, service);
  38255. } else if (b === 0x92) {
  38256. i = this.setPenLocation(i, service);
  38257. } else if (b === 0x8f) {
  38258. service = this.reset(i, service);
  38259. } else if (b === 0x08) {
  38260. // BS: Backspace
  38261. service.currentWindow.backspace();
  38262. } else if (b === 0x0c) {
  38263. // FF: Form feed
  38264. service.currentWindow.clearText();
  38265. } else if (b === 0x0d) {
  38266. // CR: Carriage return
  38267. service.currentWindow.pendingNewLine = true;
  38268. } else if (b === 0x0e) {
  38269. // HCR: Horizontal carriage return
  38270. service.currentWindow.clearText();
  38271. } else if (b === 0x8d) {
  38272. // DLY: Delay, nothing to do
  38273. i++;
  38274. } else ;
  38275. }
  38276. };
  38277. /**
  38278. * Execute an extended command
  38279. *
  38280. * @param {Integer} i Current index in the 708 packet
  38281. * @param {Service} service The service object to be affected
  38282. * @return {Integer} New index after parsing
  38283. */
  38284. Cea708Stream.prototype.extendedCommands = function (i, service) {
  38285. var packetData = this.current708Packet.data;
  38286. var b = packetData[++i];
  38287. if (within708TextBlock(b)) {
  38288. i = this.handleText(i, service, {
  38289. isExtended: true
  38290. });
  38291. }
  38292. return i;
  38293. };
  38294. /**
  38295. * Get PTS value of a given byte index
  38296. *
  38297. * @param {Integer} byteIndex Index of the byte
  38298. * @return {Integer} PTS
  38299. */
  38300. Cea708Stream.prototype.getPts = function (byteIndex) {
  38301. // There's 1 pts value per 2 bytes
  38302. return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];
  38303. };
  38304. /**
  38305. * Initializes a service
  38306. *
  38307. * @param {Integer} serviceNum Service number
  38308. * @return {Service} Initialized service object
  38309. */
  38310. Cea708Stream.prototype.initService = function (serviceNum, i) {
  38311. var serviceName = 'SERVICE' + serviceNum;
  38312. var self = this;
  38313. var serviceName;
  38314. var encoding;
  38315. if (serviceName in this.serviceEncodings) {
  38316. encoding = this.serviceEncodings[serviceName];
  38317. }
  38318. this.services[serviceNum] = new Cea708Service(serviceNum, encoding, self);
  38319. this.services[serviceNum].init(this.getPts(i), function (pts) {
  38320. self.flushDisplayed(pts, self.services[serviceNum]);
  38321. });
  38322. return this.services[serviceNum];
  38323. };
  38324. /**
  38325. * Execute text writing to current window
  38326. *
  38327. * @param {Integer} i Current index in the 708 packet
  38328. * @param {Service} service The service object to be affected
  38329. * @return {Integer} New index after parsing
  38330. */
  38331. Cea708Stream.prototype.handleText = function (i, service, options) {
  38332. var isExtended = options && options.isExtended;
  38333. var isMultiByte = options && options.isMultiByte;
  38334. var packetData = this.current708Packet.data;
  38335. var extended = isExtended ? 0x1000 : 0x0000;
  38336. var currentByte = packetData[i];
  38337. var nextByte = packetData[i + 1];
  38338. var win = service.currentWindow;
  38339. var _char;
  38340. var charCodeArray; // Use the TextDecoder if one was created for this service
  38341. if (service.textDecoder_ && !isExtended) {
  38342. if (isMultiByte) {
  38343. charCodeArray = [currentByte, nextByte];
  38344. i++;
  38345. } else {
  38346. charCodeArray = [currentByte];
  38347. }
  38348. _char = service.textDecoder_.decode(new Uint8Array(charCodeArray));
  38349. } else {
  38350. _char = get708CharFromCode(extended | currentByte);
  38351. }
  38352. if (win.pendingNewLine && !win.isEmpty()) {
  38353. win.newLine(this.getPts(i));
  38354. }
  38355. win.pendingNewLine = false;
  38356. win.addText(_char);
  38357. return i;
  38358. };
  38359. /**
  38360. * Handle decoding of multibyte character
  38361. *
  38362. * @param {Integer} i Current index in the 708 packet
  38363. * @param {Service} service The service object to be affected
  38364. * @return {Integer} New index after parsing
  38365. */
  38366. Cea708Stream.prototype.multiByteCharacter = function (i, service) {
  38367. var packetData = this.current708Packet.data;
  38368. var firstByte = packetData[i + 1];
  38369. var secondByte = packetData[i + 2];
  38370. if (within708TextBlock(firstByte) && within708TextBlock(secondByte)) {
  38371. i = this.handleText(++i, service, {
  38372. isMultiByte: true
  38373. });
  38374. }
  38375. return i;
  38376. };
  38377. /**
  38378. * Parse and execute the CW# command.
  38379. *
  38380. * Set the current window.
  38381. *
  38382. * @param {Integer} i Current index in the 708 packet
  38383. * @param {Service} service The service object to be affected
  38384. * @return {Integer} New index after parsing
  38385. */
  38386. Cea708Stream.prototype.setCurrentWindow = function (i, service) {
  38387. var packetData = this.current708Packet.data;
  38388. var b = packetData[i];
  38389. var windowNum = b & 0x07;
  38390. service.setCurrentWindow(windowNum);
  38391. return i;
  38392. };
  38393. /**
  38394. * Parse and execute the DF# command.
  38395. *
  38396. * Define a window and set it as the current window.
  38397. *
  38398. * @param {Integer} i Current index in the 708 packet
  38399. * @param {Service} service The service object to be affected
  38400. * @return {Integer} New index after parsing
  38401. */
  38402. Cea708Stream.prototype.defineWindow = function (i, service) {
  38403. var packetData = this.current708Packet.data;
  38404. var b = packetData[i];
  38405. var windowNum = b & 0x07;
  38406. service.setCurrentWindow(windowNum);
  38407. var win = service.currentWindow;
  38408. b = packetData[++i];
  38409. win.visible = (b & 0x20) >> 5; // v
  38410. win.rowLock = (b & 0x10) >> 4; // rl
  38411. win.columnLock = (b & 0x08) >> 3; // cl
  38412. win.priority = b & 0x07; // p
  38413. b = packetData[++i];
  38414. win.relativePositioning = (b & 0x80) >> 7; // rp
  38415. win.anchorVertical = b & 0x7f; // av
  38416. b = packetData[++i];
  38417. win.anchorHorizontal = b; // ah
  38418. b = packetData[++i];
  38419. win.anchorPoint = (b & 0xf0) >> 4; // ap
  38420. win.rowCount = b & 0x0f; // rc
  38421. b = packetData[++i];
  38422. win.columnCount = b & 0x3f; // cc
  38423. b = packetData[++i];
  38424. win.windowStyle = (b & 0x38) >> 3; // ws
  38425. win.penStyle = b & 0x07; // ps
  38426. // The spec says there are (rowCount+1) "virtual rows"
  38427. win.virtualRowCount = win.rowCount + 1;
  38428. return i;
  38429. };
  38430. /**
  38431. * Parse and execute the SWA command.
  38432. *
  38433. * Set attributes of the current window.
  38434. *
  38435. * @param {Integer} i Current index in the 708 packet
  38436. * @param {Service} service The service object to be affected
  38437. * @return {Integer} New index after parsing
  38438. */
  38439. Cea708Stream.prototype.setWindowAttributes = function (i, service) {
  38440. var packetData = this.current708Packet.data;
  38441. var b = packetData[i];
  38442. var winAttr = service.currentWindow.winAttr;
  38443. b = packetData[++i];
  38444. winAttr.fillOpacity = (b & 0xc0) >> 6; // fo
  38445. winAttr.fillRed = (b & 0x30) >> 4; // fr
  38446. winAttr.fillGreen = (b & 0x0c) >> 2; // fg
  38447. winAttr.fillBlue = b & 0x03; // fb
  38448. b = packetData[++i];
  38449. winAttr.borderType = (b & 0xc0) >> 6; // bt
  38450. winAttr.borderRed = (b & 0x30) >> 4; // br
  38451. winAttr.borderGreen = (b & 0x0c) >> 2; // bg
  38452. winAttr.borderBlue = b & 0x03; // bb
  38453. b = packetData[++i];
  38454. winAttr.borderType += (b & 0x80) >> 5; // bt
  38455. winAttr.wordWrap = (b & 0x40) >> 6; // ww
  38456. winAttr.printDirection = (b & 0x30) >> 4; // pd
  38457. winAttr.scrollDirection = (b & 0x0c) >> 2; // sd
  38458. winAttr.justify = b & 0x03; // j
  38459. b = packetData[++i];
  38460. winAttr.effectSpeed = (b & 0xf0) >> 4; // es
  38461. winAttr.effectDirection = (b & 0x0c) >> 2; // ed
  38462. winAttr.displayEffect = b & 0x03; // de
  38463. return i;
  38464. };
  38465. /**
  38466. * Gather text from all displayed windows and push a caption to output.
  38467. *
  38468. * @param {Integer} i Current index in the 708 packet
  38469. * @param {Service} service The service object to be affected
  38470. */
  38471. Cea708Stream.prototype.flushDisplayed = function (pts, service) {
  38472. var displayedText = []; // TODO: Positioning not supported, displaying multiple windows will not necessarily
  38473. // display text in the correct order, but sample files so far have not shown any issue.
  38474. for (var winId = 0; winId < 8; winId++) {
  38475. if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {
  38476. displayedText.push(service.windows[winId].getText());
  38477. }
  38478. }
  38479. service.endPts = pts;
  38480. service.text = displayedText.join('\n\n');
  38481. this.pushCaption(service);
  38482. service.startPts = pts;
  38483. };
  38484. /**
  38485. * Push a caption to output if the caption contains text.
  38486. *
  38487. * @param {Service} service The service object to be affected
  38488. */
  38489. Cea708Stream.prototype.pushCaption = function (service) {
  38490. if (service.text !== '') {
  38491. this.trigger('data', {
  38492. startPts: service.startPts,
  38493. endPts: service.endPts,
  38494. text: service.text,
  38495. stream: 'cc708_' + service.serviceNum
  38496. });
  38497. service.text = '';
  38498. service.startPts = service.endPts;
  38499. }
  38500. };
  38501. /**
  38502. * Parse and execute the DSW command.
  38503. *
  38504. * Set visible property of windows based on the parsed bitmask.
  38505. *
  38506. * @param {Integer} i Current index in the 708 packet
  38507. * @param {Service} service The service object to be affected
  38508. * @return {Integer} New index after parsing
  38509. */
  38510. Cea708Stream.prototype.displayWindows = function (i, service) {
  38511. var packetData = this.current708Packet.data;
  38512. var b = packetData[++i];
  38513. var pts = this.getPts(i);
  38514. this.flushDisplayed(pts, service);
  38515. for (var winId = 0; winId < 8; winId++) {
  38516. if (b & 0x01 << winId) {
  38517. service.windows[winId].visible = 1;
  38518. }
  38519. }
  38520. return i;
  38521. };
  38522. /**
  38523. * Parse and execute the HDW command.
  38524. *
  38525. * Set visible property of windows based on the parsed bitmask.
  38526. *
  38527. * @param {Integer} i Current index in the 708 packet
  38528. * @param {Service} service The service object to be affected
  38529. * @return {Integer} New index after parsing
  38530. */
  38531. Cea708Stream.prototype.hideWindows = function (i, service) {
  38532. var packetData = this.current708Packet.data;
  38533. var b = packetData[++i];
  38534. var pts = this.getPts(i);
  38535. this.flushDisplayed(pts, service);
  38536. for (var winId = 0; winId < 8; winId++) {
  38537. if (b & 0x01 << winId) {
  38538. service.windows[winId].visible = 0;
  38539. }
  38540. }
  38541. return i;
  38542. };
  38543. /**
  38544. * Parse and execute the TGW command.
  38545. *
  38546. * Set visible property of windows based on the parsed bitmask.
  38547. *
  38548. * @param {Integer} i Current index in the 708 packet
  38549. * @param {Service} service The service object to be affected
  38550. * @return {Integer} New index after parsing
  38551. */
  38552. Cea708Stream.prototype.toggleWindows = function (i, service) {
  38553. var packetData = this.current708Packet.data;
  38554. var b = packetData[++i];
  38555. var pts = this.getPts(i);
  38556. this.flushDisplayed(pts, service);
  38557. for (var winId = 0; winId < 8; winId++) {
  38558. if (b & 0x01 << winId) {
  38559. service.windows[winId].visible ^= 1;
  38560. }
  38561. }
  38562. return i;
  38563. };
  38564. /**
  38565. * Parse and execute the CLW command.
  38566. *
  38567. * Clear text of windows based on the parsed bitmask.
  38568. *
  38569. * @param {Integer} i Current index in the 708 packet
  38570. * @param {Service} service The service object to be affected
  38571. * @return {Integer} New index after parsing
  38572. */
  38573. Cea708Stream.prototype.clearWindows = function (i, service) {
  38574. var packetData = this.current708Packet.data;
  38575. var b = packetData[++i];
  38576. var pts = this.getPts(i);
  38577. this.flushDisplayed(pts, service);
  38578. for (var winId = 0; winId < 8; winId++) {
  38579. if (b & 0x01 << winId) {
  38580. service.windows[winId].clearText();
  38581. }
  38582. }
  38583. return i;
  38584. };
  38585. /**
  38586. * Parse and execute the DLW command.
  38587. *
  38588. * Re-initialize windows based on the parsed bitmask.
  38589. *
  38590. * @param {Integer} i Current index in the 708 packet
  38591. * @param {Service} service The service object to be affected
  38592. * @return {Integer} New index after parsing
  38593. */
  38594. Cea708Stream.prototype.deleteWindows = function (i, service) {
  38595. var packetData = this.current708Packet.data;
  38596. var b = packetData[++i];
  38597. var pts = this.getPts(i);
  38598. this.flushDisplayed(pts, service);
  38599. for (var winId = 0; winId < 8; winId++) {
  38600. if (b & 0x01 << winId) {
  38601. service.windows[winId].reset();
  38602. }
  38603. }
  38604. return i;
  38605. };
  38606. /**
  38607. * Parse and execute the SPA command.
  38608. *
  38609. * Set pen attributes of the current window.
  38610. *
  38611. * @param {Integer} i Current index in the 708 packet
  38612. * @param {Service} service The service object to be affected
  38613. * @return {Integer} New index after parsing
  38614. */
  38615. Cea708Stream.prototype.setPenAttributes = function (i, service) {
  38616. var packetData = this.current708Packet.data;
  38617. var b = packetData[i];
  38618. var penAttr = service.currentWindow.penAttr;
  38619. b = packetData[++i];
  38620. penAttr.textTag = (b & 0xf0) >> 4; // tt
  38621. penAttr.offset = (b & 0x0c) >> 2; // o
  38622. penAttr.penSize = b & 0x03; // s
  38623. b = packetData[++i];
  38624. penAttr.italics = (b & 0x80) >> 7; // i
  38625. penAttr.underline = (b & 0x40) >> 6; // u
  38626. penAttr.edgeType = (b & 0x38) >> 3; // et
  38627. penAttr.fontStyle = b & 0x07; // fs
  38628. return i;
  38629. };
  38630. /**
  38631. * Parse and execute the SPC command.
  38632. *
  38633. * Set pen color of the current window.
  38634. *
  38635. * @param {Integer} i Current index in the 708 packet
  38636. * @param {Service} service The service object to be affected
  38637. * @return {Integer} New index after parsing
  38638. */
  38639. Cea708Stream.prototype.setPenColor = function (i, service) {
  38640. var packetData = this.current708Packet.data;
  38641. var b = packetData[i];
  38642. var penColor = service.currentWindow.penColor;
  38643. b = packetData[++i];
  38644. penColor.fgOpacity = (b & 0xc0) >> 6; // fo
  38645. penColor.fgRed = (b & 0x30) >> 4; // fr
  38646. penColor.fgGreen = (b & 0x0c) >> 2; // fg
  38647. penColor.fgBlue = b & 0x03; // fb
  38648. b = packetData[++i];
  38649. penColor.bgOpacity = (b & 0xc0) >> 6; // bo
  38650. penColor.bgRed = (b & 0x30) >> 4; // br
  38651. penColor.bgGreen = (b & 0x0c) >> 2; // bg
  38652. penColor.bgBlue = b & 0x03; // bb
  38653. b = packetData[++i];
  38654. penColor.edgeRed = (b & 0x30) >> 4; // er
  38655. penColor.edgeGreen = (b & 0x0c) >> 2; // eg
  38656. penColor.edgeBlue = b & 0x03; // eb
  38657. return i;
  38658. };
  38659. /**
  38660. * Parse and execute the SPL command.
  38661. *
  38662. * Set pen location of the current window.
  38663. *
  38664. * @param {Integer} i Current index in the 708 packet
  38665. * @param {Service} service The service object to be affected
  38666. * @return {Integer} New index after parsing
  38667. */
  38668. Cea708Stream.prototype.setPenLocation = function (i, service) {
  38669. var packetData = this.current708Packet.data;
  38670. var b = packetData[i];
  38671. var penLoc = service.currentWindow.penLoc; // Positioning isn't really supported at the moment, so this essentially just inserts a linebreak
  38672. service.currentWindow.pendingNewLine = true;
  38673. b = packetData[++i];
  38674. penLoc.row = b & 0x0f; // r
  38675. b = packetData[++i];
  38676. penLoc.column = b & 0x3f; // c
  38677. return i;
  38678. };
  38679. /**
  38680. * Execute the RST command.
  38681. *
  38682. * Reset service to a clean slate. Re-initialize.
  38683. *
  38684. * @param {Integer} i Current index in the 708 packet
  38685. * @param {Service} service The service object to be affected
  38686. * @return {Service} Re-initialized service
  38687. */
  38688. Cea708Stream.prototype.reset = function (i, service) {
  38689. var pts = this.getPts(i);
  38690. this.flushDisplayed(pts, service);
  38691. return this.initService(service.serviceNum, i);
  38692. }; // This hash maps non-ASCII, special, and extended character codes to their
  38693. // proper Unicode equivalent. The first keys that are only a single byte
  38694. // are the non-standard ASCII characters, which simply map the CEA608 byte
  38695. // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
  38696. // character codes, but have their MSB bitmasked with 0x03 so that a lookup
  38697. // can be performed regardless of the field and data channel on which the
  38698. // character code was received.
  38699. var CHARACTER_TRANSLATION = {
  38700. 0x2a: 0xe1,
  38701. // á
  38702. 0x5c: 0xe9,
  38703. // é
  38704. 0x5e: 0xed,
  38705. // í
  38706. 0x5f: 0xf3,
  38707. // ó
  38708. 0x60: 0xfa,
  38709. // ú
  38710. 0x7b: 0xe7,
  38711. // ç
  38712. 0x7c: 0xf7,
  38713. // ÷
  38714. 0x7d: 0xd1,
  38715. // Ñ
  38716. 0x7e: 0xf1,
  38717. // ñ
  38718. 0x7f: 0x2588,
  38719. // █
  38720. 0x0130: 0xae,
  38721. // ®
  38722. 0x0131: 0xb0,
  38723. // °
  38724. 0x0132: 0xbd,
  38725. // ½
  38726. 0x0133: 0xbf,
  38727. // ¿
  38728. 0x0134: 0x2122,
  38729. // ™
  38730. 0x0135: 0xa2,
  38731. // ¢
  38732. 0x0136: 0xa3,
  38733. // £
  38734. 0x0137: 0x266a,
  38735. // ♪
  38736. 0x0138: 0xe0,
  38737. // à
  38738. 0x0139: 0xa0,
  38739. //
  38740. 0x013a: 0xe8,
  38741. // è
  38742. 0x013b: 0xe2,
  38743. // â
  38744. 0x013c: 0xea,
  38745. // ê
  38746. 0x013d: 0xee,
  38747. // î
  38748. 0x013e: 0xf4,
  38749. // ô
  38750. 0x013f: 0xfb,
  38751. // û
  38752. 0x0220: 0xc1,
  38753. // Á
  38754. 0x0221: 0xc9,
  38755. // É
  38756. 0x0222: 0xd3,
  38757. // Ó
  38758. 0x0223: 0xda,
  38759. // Ú
  38760. 0x0224: 0xdc,
  38761. // Ü
  38762. 0x0225: 0xfc,
  38763. // ü
  38764. 0x0226: 0x2018,
  38765. // ‘
  38766. 0x0227: 0xa1,
  38767. // ¡
  38768. 0x0228: 0x2a,
  38769. // *
  38770. 0x0229: 0x27,
  38771. // '
  38772. 0x022a: 0x2014,
  38773. // —
  38774. 0x022b: 0xa9,
  38775. // ©
  38776. 0x022c: 0x2120,
  38777. // ℠
  38778. 0x022d: 0x2022,
  38779. // •
  38780. 0x022e: 0x201c,
  38781. // “
  38782. 0x022f: 0x201d,
  38783. // ”
  38784. 0x0230: 0xc0,
  38785. // À
  38786. 0x0231: 0xc2,
  38787. // Â
  38788. 0x0232: 0xc7,
  38789. // Ç
  38790. 0x0233: 0xc8,
  38791. // È
  38792. 0x0234: 0xca,
  38793. // Ê
  38794. 0x0235: 0xcb,
  38795. // Ë
  38796. 0x0236: 0xeb,
  38797. // ë
  38798. 0x0237: 0xce,
  38799. // Î
  38800. 0x0238: 0xcf,
  38801. // Ï
  38802. 0x0239: 0xef,
  38803. // ï
  38804. 0x023a: 0xd4,
  38805. // Ô
  38806. 0x023b: 0xd9,
  38807. // Ù
  38808. 0x023c: 0xf9,
  38809. // ù
  38810. 0x023d: 0xdb,
  38811. // Û
  38812. 0x023e: 0xab,
  38813. // «
  38814. 0x023f: 0xbb,
  38815. // »
  38816. 0x0320: 0xc3,
  38817. // Ã
  38818. 0x0321: 0xe3,
  38819. // ã
  38820. 0x0322: 0xcd,
  38821. // Í
  38822. 0x0323: 0xcc,
  38823. // Ì
  38824. 0x0324: 0xec,
  38825. // ì
  38826. 0x0325: 0xd2,
  38827. // Ò
  38828. 0x0326: 0xf2,
  38829. // ò
  38830. 0x0327: 0xd5,
  38831. // Õ
  38832. 0x0328: 0xf5,
  38833. // õ
  38834. 0x0329: 0x7b,
  38835. // {
  38836. 0x032a: 0x7d,
  38837. // }
  38838. 0x032b: 0x5c,
  38839. // \
  38840. 0x032c: 0x5e,
  38841. // ^
  38842. 0x032d: 0x5f,
  38843. // _
  38844. 0x032e: 0x7c,
  38845. // |
  38846. 0x032f: 0x7e,
  38847. // ~
  38848. 0x0330: 0xc4,
  38849. // Ä
  38850. 0x0331: 0xe4,
  38851. // ä
  38852. 0x0332: 0xd6,
  38853. // Ö
  38854. 0x0333: 0xf6,
  38855. // ö
  38856. 0x0334: 0xdf,
  38857. // ß
  38858. 0x0335: 0xa5,
  38859. // ¥
  38860. 0x0336: 0xa4,
  38861. // ¤
  38862. 0x0337: 0x2502,
  38863. // │
  38864. 0x0338: 0xc5,
  38865. // Å
  38866. 0x0339: 0xe5,
  38867. // å
  38868. 0x033a: 0xd8,
  38869. // Ø
  38870. 0x033b: 0xf8,
  38871. // ø
  38872. 0x033c: 0x250c,
  38873. // ┌
  38874. 0x033d: 0x2510,
  38875. // ┐
  38876. 0x033e: 0x2514,
  38877. // └
  38878. 0x033f: 0x2518 // ┘
  38879. };
  38880. var getCharFromCode = function getCharFromCode(code) {
  38881. if (code === null) {
  38882. return '';
  38883. }
  38884. code = CHARACTER_TRANSLATION[code] || code;
  38885. return String.fromCharCode(code);
  38886. }; // the index of the last row in a CEA-608 display buffer
  38887. var BOTTOM_ROW = 14; // This array is used for mapping PACs -> row #, since there's no way of
  38888. // getting it through bit logic.
  38889. 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
  38890. // cells. The "bottom" row is the last element in the outer array.
  38891. var createDisplayBuffer = function createDisplayBuffer() {
  38892. var result = [],
  38893. i = BOTTOM_ROW + 1;
  38894. while (i--) {
  38895. result.push('');
  38896. }
  38897. return result;
  38898. };
  38899. var Cea608Stream = function Cea608Stream(field, dataChannel) {
  38900. Cea608Stream.prototype.init.call(this);
  38901. this.field_ = field || 0;
  38902. this.dataChannel_ = dataChannel || 0;
  38903. this.name_ = 'CC' + ((this.field_ << 1 | this.dataChannel_) + 1);
  38904. this.setConstants();
  38905. this.reset();
  38906. this.push = function (packet) {
  38907. var data, swap, char0, char1, text; // remove the parity bits
  38908. data = packet.ccData & 0x7f7f; // ignore duplicate control codes; the spec demands they're sent twice
  38909. if (data === this.lastControlCode_) {
  38910. this.lastControlCode_ = null;
  38911. return;
  38912. } // Store control codes
  38913. if ((data & 0xf000) === 0x1000) {
  38914. this.lastControlCode_ = data;
  38915. } else if (data !== this.PADDING_) {
  38916. this.lastControlCode_ = null;
  38917. }
  38918. char0 = data >>> 8;
  38919. char1 = data & 0xff;
  38920. if (data === this.PADDING_) {
  38921. return;
  38922. } else if (data === this.RESUME_CAPTION_LOADING_) {
  38923. this.mode_ = 'popOn';
  38924. } else if (data === this.END_OF_CAPTION_) {
  38925. // If an EOC is received while in paint-on mode, the displayed caption
  38926. // text should be swapped to non-displayed memory as if it was a pop-on
  38927. // caption. Because of that, we should explicitly switch back to pop-on
  38928. // mode
  38929. this.mode_ = 'popOn';
  38930. this.clearFormatting(packet.pts); // if a caption was being displayed, it's gone now
  38931. this.flushDisplayed(packet.pts); // flip memory
  38932. swap = this.displayed_;
  38933. this.displayed_ = this.nonDisplayed_;
  38934. this.nonDisplayed_ = swap; // start measuring the time to display the caption
  38935. this.startPts_ = packet.pts;
  38936. } else if (data === this.ROLL_UP_2_ROWS_) {
  38937. this.rollUpRows_ = 2;
  38938. this.setRollUp(packet.pts);
  38939. } else if (data === this.ROLL_UP_3_ROWS_) {
  38940. this.rollUpRows_ = 3;
  38941. this.setRollUp(packet.pts);
  38942. } else if (data === this.ROLL_UP_4_ROWS_) {
  38943. this.rollUpRows_ = 4;
  38944. this.setRollUp(packet.pts);
  38945. } else if (data === this.CARRIAGE_RETURN_) {
  38946. this.clearFormatting(packet.pts);
  38947. this.flushDisplayed(packet.pts);
  38948. this.shiftRowsUp_();
  38949. this.startPts_ = packet.pts;
  38950. } else if (data === this.BACKSPACE_) {
  38951. if (this.mode_ === 'popOn') {
  38952. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  38953. } else {
  38954. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  38955. }
  38956. } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
  38957. this.flushDisplayed(packet.pts);
  38958. this.displayed_ = createDisplayBuffer();
  38959. } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
  38960. this.nonDisplayed_ = createDisplayBuffer();
  38961. } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
  38962. if (this.mode_ !== 'paintOn') {
  38963. // NOTE: This should be removed when proper caption positioning is
  38964. // implemented
  38965. this.flushDisplayed(packet.pts);
  38966. this.displayed_ = createDisplayBuffer();
  38967. }
  38968. this.mode_ = 'paintOn';
  38969. this.startPts_ = packet.pts; // Append special characters to caption text
  38970. } else if (this.isSpecialCharacter(char0, char1)) {
  38971. // Bitmask char0 so that we can apply character transformations
  38972. // regardless of field and data channel.
  38973. // Then byte-shift to the left and OR with char1 so we can pass the
  38974. // entire character code to `getCharFromCode`.
  38975. char0 = (char0 & 0x03) << 8;
  38976. text = getCharFromCode(char0 | char1);
  38977. this[this.mode_](packet.pts, text);
  38978. this.column_++; // Append extended characters to caption text
  38979. } else if (this.isExtCharacter(char0, char1)) {
  38980. // Extended characters always follow their "non-extended" equivalents.
  38981. // IE if a "è" is desired, you'll always receive "eè"; non-compliant
  38982. // decoders are supposed to drop the "è", while compliant decoders
  38983. // backspace the "e" and insert "è".
  38984. // Delete the previous character
  38985. if (this.mode_ === 'popOn') {
  38986. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  38987. } else {
  38988. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  38989. } // Bitmask char0 so that we can apply character transformations
  38990. // regardless of field and data channel.
  38991. // Then byte-shift to the left and OR with char1 so we can pass the
  38992. // entire character code to `getCharFromCode`.
  38993. char0 = (char0 & 0x03) << 8;
  38994. text = getCharFromCode(char0 | char1);
  38995. this[this.mode_](packet.pts, text);
  38996. this.column_++; // Process mid-row codes
  38997. } else if (this.isMidRowCode(char0, char1)) {
  38998. // Attributes are not additive, so clear all formatting
  38999. this.clearFormatting(packet.pts); // According to the standard, mid-row codes
  39000. // should be replaced with spaces, so add one now
  39001. this[this.mode_](packet.pts, ' ');
  39002. this.column_++;
  39003. if ((char1 & 0xe) === 0xe) {
  39004. this.addFormatting(packet.pts, ['i']);
  39005. }
  39006. if ((char1 & 0x1) === 0x1) {
  39007. this.addFormatting(packet.pts, ['u']);
  39008. } // Detect offset control codes and adjust cursor
  39009. } else if (this.isOffsetControlCode(char0, char1)) {
  39010. // Cursor position is set by indent PAC (see below) in 4-column
  39011. // increments, with an additional offset code of 1-3 to reach any
  39012. // of the 32 columns specified by CEA-608. So all we need to do
  39013. // here is increment the column cursor by the given offset.
  39014. this.column_ += char1 & 0x03; // Detect PACs (Preamble Address Codes)
  39015. } else if (this.isPAC(char0, char1)) {
  39016. // There's no logic for PAC -> row mapping, so we have to just
  39017. // find the row code in an array and use its index :(
  39018. var row = ROWS.indexOf(data & 0x1f20); // Configure the caption window if we're in roll-up mode
  39019. if (this.mode_ === 'rollUp') {
  39020. // This implies that the base row is incorrectly set.
  39021. // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
  39022. // of roll-up rows set.
  39023. if (row - this.rollUpRows_ + 1 < 0) {
  39024. row = this.rollUpRows_ - 1;
  39025. }
  39026. this.setRollUp(packet.pts, row);
  39027. }
  39028. if (row !== this.row_) {
  39029. // formatting is only persistent for current row
  39030. this.clearFormatting(packet.pts);
  39031. this.row_ = row;
  39032. } // All PACs can apply underline, so detect and apply
  39033. // (All odd-numbered second bytes set underline)
  39034. if (char1 & 0x1 && this.formatting_.indexOf('u') === -1) {
  39035. this.addFormatting(packet.pts, ['u']);
  39036. }
  39037. if ((data & 0x10) === 0x10) {
  39038. // We've got an indent level code. Each successive even number
  39039. // increments the column cursor by 4, so we can get the desired
  39040. // column position by bit-shifting to the right (to get n/2)
  39041. // and multiplying by 4.
  39042. this.column_ = ((data & 0xe) >> 1) * 4;
  39043. }
  39044. if (this.isColorPAC(char1)) {
  39045. // it's a color code, though we only support white, which
  39046. // can be either normal or italicized. white italics can be
  39047. // either 0x4e or 0x6e depending on the row, so we just
  39048. // bitwise-and with 0xe to see if italics should be turned on
  39049. if ((char1 & 0xe) === 0xe) {
  39050. this.addFormatting(packet.pts, ['i']);
  39051. }
  39052. } // We have a normal character in char0, and possibly one in char1
  39053. } else if (this.isNormalChar(char0)) {
  39054. if (char1 === 0x00) {
  39055. char1 = null;
  39056. }
  39057. text = getCharFromCode(char0);
  39058. text += getCharFromCode(char1);
  39059. this[this.mode_](packet.pts, text);
  39060. this.column_ += text.length;
  39061. } // finish data processing
  39062. };
  39063. };
  39064. Cea608Stream.prototype = new stream(); // Trigger a cue point that captures the current state of the
  39065. // display buffer
  39066. Cea608Stream.prototype.flushDisplayed = function (pts) {
  39067. var content = this.displayed_ // remove spaces from the start and end of the string
  39068. .map(function (row, index) {
  39069. try {
  39070. return row.trim();
  39071. } catch (e) {
  39072. // Ordinarily, this shouldn't happen. However, caption
  39073. // parsing errors should not throw exceptions and
  39074. // break playback.
  39075. this.trigger('log', {
  39076. level: 'warn',
  39077. message: 'Skipping a malformed 608 caption at index ' + index + '.'
  39078. });
  39079. return '';
  39080. }
  39081. }, this) // combine all text rows to display in one cue
  39082. .join('\n') // and remove blank rows from the start and end, but not the middle
  39083. .replace(/^\n+|\n+$/g, '');
  39084. if (content.length) {
  39085. this.trigger('data', {
  39086. startPts: this.startPts_,
  39087. endPts: pts,
  39088. text: content,
  39089. stream: this.name_
  39090. });
  39091. }
  39092. };
  39093. /**
  39094. * Zero out the data, used for startup and on seek
  39095. */
  39096. Cea608Stream.prototype.reset = function () {
  39097. this.mode_ = 'popOn'; // When in roll-up mode, the index of the last row that will
  39098. // actually display captions. If a caption is shifted to a row
  39099. // with a lower index than this, it is cleared from the display
  39100. // buffer
  39101. this.topRow_ = 0;
  39102. this.startPts_ = 0;
  39103. this.displayed_ = createDisplayBuffer();
  39104. this.nonDisplayed_ = createDisplayBuffer();
  39105. this.lastControlCode_ = null; // Track row and column for proper line-breaking and spacing
  39106. this.column_ = 0;
  39107. this.row_ = BOTTOM_ROW;
  39108. this.rollUpRows_ = 2; // This variable holds currently-applied formatting
  39109. this.formatting_ = [];
  39110. };
  39111. /**
  39112. * Sets up control code and related constants for this instance
  39113. */
  39114. Cea608Stream.prototype.setConstants = function () {
  39115. // The following attributes have these uses:
  39116. // ext_ : char0 for mid-row codes, and the base for extended
  39117. // chars (ext_+0, ext_+1, and ext_+2 are char0s for
  39118. // extended codes)
  39119. // control_: char0 for control codes, except byte-shifted to the
  39120. // left so that we can do this.control_ | CONTROL_CODE
  39121. // offset_: char0 for tab offset codes
  39122. //
  39123. // It's also worth noting that control codes, and _only_ control codes,
  39124. // differ between field 1 and field2. Field 2 control codes are always
  39125. // their field 1 value plus 1. That's why there's the "| field" on the
  39126. // control value.
  39127. if (this.dataChannel_ === 0) {
  39128. this.BASE_ = 0x10;
  39129. this.EXT_ = 0x11;
  39130. this.CONTROL_ = (0x14 | this.field_) << 8;
  39131. this.OFFSET_ = 0x17;
  39132. } else if (this.dataChannel_ === 1) {
  39133. this.BASE_ = 0x18;
  39134. this.EXT_ = 0x19;
  39135. this.CONTROL_ = (0x1c | this.field_) << 8;
  39136. this.OFFSET_ = 0x1f;
  39137. } // Constants for the LSByte command codes recognized by Cea608Stream. This
  39138. // list is not exhaustive. For a more comprehensive listing and semantics see
  39139. // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
  39140. // Padding
  39141. this.PADDING_ = 0x0000; // Pop-on Mode
  39142. this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;
  39143. this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f; // Roll-up Mode
  39144. this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;
  39145. this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;
  39146. this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;
  39147. this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d; // paint-on mode
  39148. this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29; // Erasure
  39149. this.BACKSPACE_ = this.CONTROL_ | 0x21;
  39150. this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;
  39151. this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
  39152. };
  39153. /**
  39154. * Detects if the 2-byte packet data is a special character
  39155. *
  39156. * Special characters have a second byte in the range 0x30 to 0x3f,
  39157. * with the first byte being 0x11 (for data channel 1) or 0x19 (for
  39158. * data channel 2).
  39159. *
  39160. * @param {Integer} char0 The first byte
  39161. * @param {Integer} char1 The second byte
  39162. * @return {Boolean} Whether the 2 bytes are an special character
  39163. */
  39164. Cea608Stream.prototype.isSpecialCharacter = function (char0, char1) {
  39165. return char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f;
  39166. };
  39167. /**
  39168. * Detects if the 2-byte packet data is an extended character
  39169. *
  39170. * Extended characters have a second byte in the range 0x20 to 0x3f,
  39171. * with the first byte being 0x12 or 0x13 (for data channel 1) or
  39172. * 0x1a or 0x1b (for data channel 2).
  39173. *
  39174. * @param {Integer} char0 The first byte
  39175. * @param {Integer} char1 The second byte
  39176. * @return {Boolean} Whether the 2 bytes are an extended character
  39177. */
  39178. Cea608Stream.prototype.isExtCharacter = function (char0, char1) {
  39179. return (char0 === this.EXT_ + 1 || char0 === this.EXT_ + 2) && char1 >= 0x20 && char1 <= 0x3f;
  39180. };
  39181. /**
  39182. * Detects if the 2-byte packet is a mid-row code
  39183. *
  39184. * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
  39185. * the first byte being 0x11 (for data channel 1) or 0x19 (for data
  39186. * channel 2).
  39187. *
  39188. * @param {Integer} char0 The first byte
  39189. * @param {Integer} char1 The second byte
  39190. * @return {Boolean} Whether the 2 bytes are a mid-row code
  39191. */
  39192. Cea608Stream.prototype.isMidRowCode = function (char0, char1) {
  39193. return char0 === this.EXT_ && char1 >= 0x20 && char1 <= 0x2f;
  39194. };
  39195. /**
  39196. * Detects if the 2-byte packet is an offset control code
  39197. *
  39198. * Offset control codes have a second byte in the range 0x21 to 0x23,
  39199. * with the first byte being 0x17 (for data channel 1) or 0x1f (for
  39200. * data channel 2).
  39201. *
  39202. * @param {Integer} char0 The first byte
  39203. * @param {Integer} char1 The second byte
  39204. * @return {Boolean} Whether the 2 bytes are an offset control code
  39205. */
  39206. Cea608Stream.prototype.isOffsetControlCode = function (char0, char1) {
  39207. return char0 === this.OFFSET_ && char1 >= 0x21 && char1 <= 0x23;
  39208. };
  39209. /**
  39210. * Detects if the 2-byte packet is a Preamble Address Code
  39211. *
  39212. * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
  39213. * or 0x18 to 0x1f (for data channel 2), with the second byte in the
  39214. * range 0x40 to 0x7f.
  39215. *
  39216. * @param {Integer} char0 The first byte
  39217. * @param {Integer} char1 The second byte
  39218. * @return {Boolean} Whether the 2 bytes are a PAC
  39219. */
  39220. Cea608Stream.prototype.isPAC = function (char0, char1) {
  39221. return char0 >= this.BASE_ && char0 < this.BASE_ + 8 && char1 >= 0x40 && char1 <= 0x7f;
  39222. };
  39223. /**
  39224. * Detects if a packet's second byte is in the range of a PAC color code
  39225. *
  39226. * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
  39227. * 0x60 to 0x6f.
  39228. *
  39229. * @param {Integer} char1 The second byte
  39230. * @return {Boolean} Whether the byte is a color PAC
  39231. */
  39232. Cea608Stream.prototype.isColorPAC = function (char1) {
  39233. return char1 >= 0x40 && char1 <= 0x4f || char1 >= 0x60 && char1 <= 0x7f;
  39234. };
  39235. /**
  39236. * Detects if a single byte is in the range of a normal character
  39237. *
  39238. * Normal text bytes are in the range 0x20 to 0x7f.
  39239. *
  39240. * @param {Integer} char The byte
  39241. * @return {Boolean} Whether the byte is a normal character
  39242. */
  39243. Cea608Stream.prototype.isNormalChar = function (_char2) {
  39244. return _char2 >= 0x20 && _char2 <= 0x7f;
  39245. };
  39246. /**
  39247. * Configures roll-up
  39248. *
  39249. * @param {Integer} pts Current PTS
  39250. * @param {Integer} newBaseRow Used by PACs to slide the current window to
  39251. * a new position
  39252. */
  39253. Cea608Stream.prototype.setRollUp = function (pts, newBaseRow) {
  39254. // Reset the base row to the bottom row when switching modes
  39255. if (this.mode_ !== 'rollUp') {
  39256. this.row_ = BOTTOM_ROW;
  39257. this.mode_ = 'rollUp'; // Spec says to wipe memories when switching to roll-up
  39258. this.flushDisplayed(pts);
  39259. this.nonDisplayed_ = createDisplayBuffer();
  39260. this.displayed_ = createDisplayBuffer();
  39261. }
  39262. if (newBaseRow !== undefined && newBaseRow !== this.row_) {
  39263. // move currently displayed captions (up or down) to the new base row
  39264. for (var i = 0; i < this.rollUpRows_; i++) {
  39265. this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
  39266. this.displayed_[this.row_ - i] = '';
  39267. }
  39268. }
  39269. if (newBaseRow === undefined) {
  39270. newBaseRow = this.row_;
  39271. }
  39272. this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
  39273. }; // Adds the opening HTML tag for the passed character to the caption text,
  39274. // and keeps track of it for later closing
  39275. Cea608Stream.prototype.addFormatting = function (pts, format) {
  39276. this.formatting_ = this.formatting_.concat(format);
  39277. var text = format.reduce(function (text, format) {
  39278. return text + '<' + format + '>';
  39279. }, '');
  39280. this[this.mode_](pts, text);
  39281. }; // Adds HTML closing tags for current formatting to caption text and
  39282. // clears remembered formatting
  39283. Cea608Stream.prototype.clearFormatting = function (pts) {
  39284. if (!this.formatting_.length) {
  39285. return;
  39286. }
  39287. var text = this.formatting_.reverse().reduce(function (text, format) {
  39288. return text + '</' + format + '>';
  39289. }, '');
  39290. this.formatting_ = [];
  39291. this[this.mode_](pts, text);
  39292. }; // Mode Implementations
  39293. Cea608Stream.prototype.popOn = function (pts, text) {
  39294. var baseRow = this.nonDisplayed_[this.row_]; // buffer characters
  39295. baseRow += text;
  39296. this.nonDisplayed_[this.row_] = baseRow;
  39297. };
  39298. Cea608Stream.prototype.rollUp = function (pts, text) {
  39299. var baseRow = this.displayed_[this.row_];
  39300. baseRow += text;
  39301. this.displayed_[this.row_] = baseRow;
  39302. };
  39303. Cea608Stream.prototype.shiftRowsUp_ = function () {
  39304. var i; // clear out inactive rows
  39305. for (i = 0; i < this.topRow_; i++) {
  39306. this.displayed_[i] = '';
  39307. }
  39308. for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
  39309. this.displayed_[i] = '';
  39310. } // shift displayed rows up
  39311. for (i = this.topRow_; i < this.row_; i++) {
  39312. this.displayed_[i] = this.displayed_[i + 1];
  39313. } // clear out the bottom row
  39314. this.displayed_[this.row_] = '';
  39315. };
  39316. Cea608Stream.prototype.paintOn = function (pts, text) {
  39317. var baseRow = this.displayed_[this.row_];
  39318. baseRow += text;
  39319. this.displayed_[this.row_] = baseRow;
  39320. }; // exports
  39321. var captionStream = {
  39322. CaptionStream: CaptionStream$1,
  39323. Cea608Stream: Cea608Stream,
  39324. Cea708Stream: Cea708Stream
  39325. };
  39326. /**
  39327. * mux.js
  39328. *
  39329. * Copyright (c) Brightcove
  39330. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  39331. */
  39332. var streamTypes = {
  39333. H264_STREAM_TYPE: 0x1B,
  39334. ADTS_STREAM_TYPE: 0x0F,
  39335. METADATA_STREAM_TYPE: 0x15
  39336. };
  39337. var MAX_TS = 8589934592;
  39338. var RO_THRESH = 4294967296;
  39339. var TYPE_SHARED = 'shared';
  39340. var handleRollover$1 = function handleRollover(value, reference) {
  39341. var direction = 1;
  39342. if (value > reference) {
  39343. // If the current timestamp value is greater than our reference timestamp and we detect a
  39344. // timestamp rollover, this means the roll over is happening in the opposite direction.
  39345. // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
  39346. // point will be set to a small number, e.g. 1. The user then seeks backwards over the
  39347. // rollover point. In loading this segment, the timestamp values will be very large,
  39348. // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
  39349. // the time stamp to be `value - 2^33`.
  39350. direction = -1;
  39351. } // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
  39352. // cause an incorrect adjustment.
  39353. while (Math.abs(reference - value) > RO_THRESH) {
  39354. value += direction * MAX_TS;
  39355. }
  39356. return value;
  39357. };
  39358. var TimestampRolloverStream$1 = function TimestampRolloverStream(type) {
  39359. var lastDTS, referenceDTS;
  39360. TimestampRolloverStream.prototype.init.call(this); // The "shared" type is used in cases where a stream will contain muxed
  39361. // video and audio. We could use `undefined` here, but having a string
  39362. // makes debugging a little clearer.
  39363. this.type_ = type || TYPE_SHARED;
  39364. this.push = function (data) {
  39365. // Any "shared" rollover streams will accept _all_ data. Otherwise,
  39366. // streams will only accept data that matches their type.
  39367. if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
  39368. return;
  39369. }
  39370. if (referenceDTS === undefined) {
  39371. referenceDTS = data.dts;
  39372. }
  39373. data.dts = handleRollover$1(data.dts, referenceDTS);
  39374. data.pts = handleRollover$1(data.pts, referenceDTS);
  39375. lastDTS = data.dts;
  39376. this.trigger('data', data);
  39377. };
  39378. this.flush = function () {
  39379. referenceDTS = lastDTS;
  39380. this.trigger('done');
  39381. };
  39382. this.endTimeline = function () {
  39383. this.flush();
  39384. this.trigger('endedtimeline');
  39385. };
  39386. this.discontinuity = function () {
  39387. referenceDTS = void 0;
  39388. lastDTS = void 0;
  39389. };
  39390. this.reset = function () {
  39391. this.discontinuity();
  39392. this.trigger('reset');
  39393. };
  39394. };
  39395. TimestampRolloverStream$1.prototype = new stream();
  39396. var timestampRolloverStream = {
  39397. TimestampRolloverStream: TimestampRolloverStream$1,
  39398. handleRollover: handleRollover$1
  39399. };
  39400. var percentEncode$1 = function percentEncode(bytes, start, end) {
  39401. var i,
  39402. result = '';
  39403. for (i = start; i < end; i++) {
  39404. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  39405. }
  39406. return result;
  39407. },
  39408. // return the string representation of the specified byte range,
  39409. // interpreted as UTf-8.
  39410. parseUtf8 = function parseUtf8(bytes, start, end) {
  39411. return decodeURIComponent(percentEncode$1(bytes, start, end));
  39412. },
  39413. // return the string representation of the specified byte range,
  39414. // interpreted as ISO-8859-1.
  39415. parseIso88591$1 = function parseIso88591(bytes, start, end) {
  39416. return unescape(percentEncode$1(bytes, start, end)); // jshint ignore:line
  39417. },
  39418. parseSyncSafeInteger$1 = function parseSyncSafeInteger(data) {
  39419. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  39420. },
  39421. tagParsers = {
  39422. TXXX: function TXXX(tag) {
  39423. var i;
  39424. if (tag.data[0] !== 3) {
  39425. // ignore frames with unrecognized character encodings
  39426. return;
  39427. }
  39428. for (i = 1; i < tag.data.length; i++) {
  39429. if (tag.data[i] === 0) {
  39430. // parse the text fields
  39431. tag.description = parseUtf8(tag.data, 1, i); // do not include the null terminator in the tag value
  39432. tag.value = parseUtf8(tag.data, i + 1, tag.data.length).replace(/\0*$/, '');
  39433. break;
  39434. }
  39435. }
  39436. tag.data = tag.value;
  39437. },
  39438. WXXX: function WXXX(tag) {
  39439. var i;
  39440. if (tag.data[0] !== 3) {
  39441. // ignore frames with unrecognized character encodings
  39442. return;
  39443. }
  39444. for (i = 1; i < tag.data.length; i++) {
  39445. if (tag.data[i] === 0) {
  39446. // parse the description and URL fields
  39447. tag.description = parseUtf8(tag.data, 1, i);
  39448. tag.url = parseUtf8(tag.data, i + 1, tag.data.length);
  39449. break;
  39450. }
  39451. }
  39452. },
  39453. PRIV: function PRIV(tag) {
  39454. var i;
  39455. for (i = 0; i < tag.data.length; i++) {
  39456. if (tag.data[i] === 0) {
  39457. // parse the description and URL fields
  39458. tag.owner = parseIso88591$1(tag.data, 0, i);
  39459. break;
  39460. }
  39461. }
  39462. tag.privateData = tag.data.subarray(i + 1);
  39463. tag.data = tag.privateData;
  39464. }
  39465. },
  39466. _MetadataStream;
  39467. _MetadataStream = function MetadataStream(options) {
  39468. var settings = {
  39469. // the bytes of the program-level descriptor field in MP2T
  39470. // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
  39471. // program element descriptors"
  39472. descriptor: options && options.descriptor
  39473. },
  39474. // the total size in bytes of the ID3 tag being parsed
  39475. tagSize = 0,
  39476. // tag data that is not complete enough to be parsed
  39477. buffer = [],
  39478. // the total number of bytes currently in the buffer
  39479. bufferSize = 0,
  39480. i;
  39481. _MetadataStream.prototype.init.call(this); // calculate the text track in-band metadata track dispatch type
  39482. // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
  39483. this.dispatchType = streamTypes.METADATA_STREAM_TYPE.toString(16);
  39484. if (settings.descriptor) {
  39485. for (i = 0; i < settings.descriptor.length; i++) {
  39486. this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
  39487. }
  39488. }
  39489. this.push = function (chunk) {
  39490. var tag, frameStart, frameSize, frame, i, frameHeader;
  39491. if (chunk.type !== 'timed-metadata') {
  39492. return;
  39493. } // if data_alignment_indicator is set in the PES header,
  39494. // we must have the start of a new ID3 tag. Assume anything
  39495. // remaining in the buffer was malformed and throw it out
  39496. if (chunk.dataAlignmentIndicator) {
  39497. bufferSize = 0;
  39498. buffer.length = 0;
  39499. } // ignore events that don't look like ID3 data
  39500. 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))) {
  39501. this.trigger('log', {
  39502. level: 'warn',
  39503. message: 'Skipping unrecognized metadata packet'
  39504. });
  39505. return;
  39506. } // add this chunk to the data we've collected so far
  39507. buffer.push(chunk);
  39508. bufferSize += chunk.data.byteLength; // grab the size of the entire frame from the ID3 header
  39509. if (buffer.length === 1) {
  39510. // the frame size is transmitted as a 28-bit integer in the
  39511. // last four bytes of the ID3 header.
  39512. // The most significant bit of each byte is dropped and the
  39513. // results concatenated to recover the actual value.
  39514. tagSize = parseSyncSafeInteger$1(chunk.data.subarray(6, 10)); // ID3 reports the tag size excluding the header but it's more
  39515. // convenient for our comparisons to include it
  39516. tagSize += 10;
  39517. } // if the entire frame has not arrived, wait for more data
  39518. if (bufferSize < tagSize) {
  39519. return;
  39520. } // collect the entire frame so it can be parsed
  39521. tag = {
  39522. data: new Uint8Array(tagSize),
  39523. frames: [],
  39524. pts: buffer[0].pts,
  39525. dts: buffer[0].dts
  39526. };
  39527. for (i = 0; i < tagSize;) {
  39528. tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
  39529. i += buffer[0].data.byteLength;
  39530. bufferSize -= buffer[0].data.byteLength;
  39531. buffer.shift();
  39532. } // find the start of the first frame and the end of the tag
  39533. frameStart = 10;
  39534. if (tag.data[5] & 0x40) {
  39535. // advance the frame start past the extended header
  39536. frameStart += 4; // header size field
  39537. frameStart += parseSyncSafeInteger$1(tag.data.subarray(10, 14)); // clip any padding off the end
  39538. tagSize -= parseSyncSafeInteger$1(tag.data.subarray(16, 20));
  39539. } // parse one or more ID3 frames
  39540. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  39541. do {
  39542. // determine the number of bytes in this frame
  39543. frameSize = parseSyncSafeInteger$1(tag.data.subarray(frameStart + 4, frameStart + 8));
  39544. if (frameSize < 1) {
  39545. this.trigger('log', {
  39546. level: 'warn',
  39547. message: 'Malformed ID3 frame encountered. Skipping metadata parsing.'
  39548. });
  39549. return;
  39550. }
  39551. frameHeader = String.fromCharCode(tag.data[frameStart], tag.data[frameStart + 1], tag.data[frameStart + 2], tag.data[frameStart + 3]);
  39552. frame = {
  39553. id: frameHeader,
  39554. data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
  39555. };
  39556. frame.key = frame.id;
  39557. if (tagParsers[frame.id]) {
  39558. tagParsers[frame.id](frame); // handle the special PRIV frame used to indicate the start
  39559. // time for raw AAC data
  39560. if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
  39561. var d = frame.data,
  39562. size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  39563. size *= 4;
  39564. size += d[7] & 0x03;
  39565. frame.timeStamp = size; // in raw AAC, all subsequent data will be timestamped based
  39566. // on the value of this frame
  39567. // we couldn't have known the appropriate pts and dts before
  39568. // parsing this ID3 tag so set those values now
  39569. if (tag.pts === undefined && tag.dts === undefined) {
  39570. tag.pts = frame.timeStamp;
  39571. tag.dts = frame.timeStamp;
  39572. }
  39573. this.trigger('timestamp', frame);
  39574. }
  39575. }
  39576. tag.frames.push(frame);
  39577. frameStart += 10; // advance past the frame header
  39578. frameStart += frameSize; // advance past the frame body
  39579. } while (frameStart < tagSize);
  39580. this.trigger('data', tag);
  39581. };
  39582. };
  39583. _MetadataStream.prototype = new stream();
  39584. var metadataStream = _MetadataStream;
  39585. var TimestampRolloverStream = timestampRolloverStream.TimestampRolloverStream; // object types
  39586. var _TransportPacketStream, _TransportParseStream, _ElementaryStream; // constants
  39587. var MP2T_PACKET_LENGTH$1 = 188,
  39588. // bytes
  39589. SYNC_BYTE$1 = 0x47;
  39590. /**
  39591. * Splits an incoming stream of binary data into MPEG-2 Transport
  39592. * Stream packets.
  39593. */
  39594. _TransportPacketStream = function TransportPacketStream() {
  39595. var buffer = new Uint8Array(MP2T_PACKET_LENGTH$1),
  39596. bytesInBuffer = 0;
  39597. _TransportPacketStream.prototype.init.call(this); // Deliver new bytes to the stream.
  39598. /**
  39599. * Split a stream of data into M2TS packets
  39600. **/
  39601. this.push = function (bytes) {
  39602. var startIndex = 0,
  39603. endIndex = MP2T_PACKET_LENGTH$1,
  39604. everything; // If there are bytes remaining from the last segment, prepend them to the
  39605. // bytes that were pushed in
  39606. if (bytesInBuffer) {
  39607. everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
  39608. everything.set(buffer.subarray(0, bytesInBuffer));
  39609. everything.set(bytes, bytesInBuffer);
  39610. bytesInBuffer = 0;
  39611. } else {
  39612. everything = bytes;
  39613. } // While we have enough data for a packet
  39614. while (endIndex < everything.byteLength) {
  39615. // Look for a pair of start and end sync bytes in the data..
  39616. if (everything[startIndex] === SYNC_BYTE$1 && everything[endIndex] === SYNC_BYTE$1) {
  39617. // We found a packet so emit it and jump one whole packet forward in
  39618. // the stream
  39619. this.trigger('data', everything.subarray(startIndex, endIndex));
  39620. startIndex += MP2T_PACKET_LENGTH$1;
  39621. endIndex += MP2T_PACKET_LENGTH$1;
  39622. continue;
  39623. } // If we get here, we have somehow become de-synchronized and we need to step
  39624. // forward one byte at a time until we find a pair of sync bytes that denote
  39625. // a packet
  39626. startIndex++;
  39627. endIndex++;
  39628. } // If there was some data left over at the end of the segment that couldn't
  39629. // possibly be a whole packet, keep it because it might be the start of a packet
  39630. // that continues in the next segment
  39631. if (startIndex < everything.byteLength) {
  39632. buffer.set(everything.subarray(startIndex), 0);
  39633. bytesInBuffer = everything.byteLength - startIndex;
  39634. }
  39635. };
  39636. /**
  39637. * Passes identified M2TS packets to the TransportParseStream to be parsed
  39638. **/
  39639. this.flush = function () {
  39640. // If the buffer contains a whole packet when we are being flushed, emit it
  39641. // and empty the buffer. Otherwise hold onto the data because it may be
  39642. // important for decoding the next segment
  39643. if (bytesInBuffer === MP2T_PACKET_LENGTH$1 && buffer[0] === SYNC_BYTE$1) {
  39644. this.trigger('data', buffer);
  39645. bytesInBuffer = 0;
  39646. }
  39647. this.trigger('done');
  39648. };
  39649. this.endTimeline = function () {
  39650. this.flush();
  39651. this.trigger('endedtimeline');
  39652. };
  39653. this.reset = function () {
  39654. bytesInBuffer = 0;
  39655. this.trigger('reset');
  39656. };
  39657. };
  39658. _TransportPacketStream.prototype = new stream();
  39659. /**
  39660. * Accepts an MP2T TransportPacketStream and emits data events with parsed
  39661. * forms of the individual transport stream packets.
  39662. */
  39663. _TransportParseStream = function TransportParseStream() {
  39664. var parsePsi, parsePat, parsePmt, self;
  39665. _TransportParseStream.prototype.init.call(this);
  39666. self = this;
  39667. this.packetsWaitingForPmt = [];
  39668. this.programMapTable = undefined;
  39669. parsePsi = function parsePsi(payload, psi) {
  39670. var offset = 0; // PSI packets may be split into multiple sections and those
  39671. // sections may be split into multiple packets. If a PSI
  39672. // section starts in this packet, the payload_unit_start_indicator
  39673. // will be true and the first byte of the payload will indicate
  39674. // the offset from the current position to the start of the
  39675. // section.
  39676. if (psi.payloadUnitStartIndicator) {
  39677. offset += payload[offset] + 1;
  39678. }
  39679. if (psi.type === 'pat') {
  39680. parsePat(payload.subarray(offset), psi);
  39681. } else {
  39682. parsePmt(payload.subarray(offset), psi);
  39683. }
  39684. };
  39685. parsePat = function parsePat(payload, pat) {
  39686. pat.section_number = payload[7]; // eslint-disable-line camelcase
  39687. pat.last_section_number = payload[8]; // eslint-disable-line camelcase
  39688. // skip the PSI header and parse the first PMT entry
  39689. self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
  39690. pat.pmtPid = self.pmtPid;
  39691. };
  39692. /**
  39693. * Parse out the relevant fields of a Program Map Table (PMT).
  39694. * @param payload {Uint8Array} the PMT-specific portion of an MP2T
  39695. * packet. The first byte in this array should be the table_id
  39696. * field.
  39697. * @param pmt {object} the object that should be decorated with
  39698. * fields parsed from the PMT.
  39699. */
  39700. parsePmt = function parsePmt(payload, pmt) {
  39701. var sectionLength, tableEnd, programInfoLength, offset; // PMTs can be sent ahead of the time when they should actually
  39702. // take effect. We don't believe this should ever be the case
  39703. // for HLS but we'll ignore "forward" PMT declarations if we see
  39704. // them. Future PMT declarations have the current_next_indicator
  39705. // set to zero.
  39706. if (!(payload[5] & 0x01)) {
  39707. return;
  39708. } // overwrite any existing program map table
  39709. self.programMapTable = {
  39710. video: null,
  39711. audio: null,
  39712. 'timed-metadata': {}
  39713. }; // the mapping table ends at the end of the current section
  39714. sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
  39715. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  39716. // long the program info descriptors are
  39717. programInfoLength = (payload[10] & 0x0f) << 8 | payload[11]; // advance the offset to the first entry in the mapping table
  39718. offset = 12 + programInfoLength;
  39719. while (offset < tableEnd) {
  39720. var streamType = payload[offset];
  39721. var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2]; // only map a single elementary_pid for audio and video stream types
  39722. // TODO: should this be done for metadata too? for now maintain behavior of
  39723. // multiple metadata streams
  39724. if (streamType === streamTypes.H264_STREAM_TYPE && self.programMapTable.video === null) {
  39725. self.programMapTable.video = pid;
  39726. } else if (streamType === streamTypes.ADTS_STREAM_TYPE && self.programMapTable.audio === null) {
  39727. self.programMapTable.audio = pid;
  39728. } else if (streamType === streamTypes.METADATA_STREAM_TYPE) {
  39729. // map pid to stream type for metadata streams
  39730. self.programMapTable['timed-metadata'][pid] = streamType;
  39731. } // move to the next table entry
  39732. // skip past the elementary stream descriptors, if present
  39733. offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
  39734. } // record the map on the packet as well
  39735. pmt.programMapTable = self.programMapTable;
  39736. };
  39737. /**
  39738. * Deliver a new MP2T packet to the next stream in the pipeline.
  39739. */
  39740. this.push = function (packet) {
  39741. var result = {},
  39742. offset = 4;
  39743. result.payloadUnitStartIndicator = !!(packet[1] & 0x40); // pid is a 13-bit field starting at the last bit of packet[1]
  39744. result.pid = packet[1] & 0x1f;
  39745. result.pid <<= 8;
  39746. result.pid |= packet[2]; // if an adaption field is present, its length is specified by the
  39747. // fifth byte of the TS packet header. The adaptation field is
  39748. // used to add stuffing to PES packets that don't fill a complete
  39749. // TS packet, and to specify some forms of timing and control data
  39750. // that we do not currently use.
  39751. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  39752. offset += packet[offset] + 1;
  39753. } // parse the rest of the packet based on the type
  39754. if (result.pid === 0) {
  39755. result.type = 'pat';
  39756. parsePsi(packet.subarray(offset), result);
  39757. this.trigger('data', result);
  39758. } else if (result.pid === this.pmtPid) {
  39759. result.type = 'pmt';
  39760. parsePsi(packet.subarray(offset), result);
  39761. this.trigger('data', result); // if there are any packets waiting for a PMT to be found, process them now
  39762. while (this.packetsWaitingForPmt.length) {
  39763. this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
  39764. }
  39765. } else if (this.programMapTable === undefined) {
  39766. // When we have not seen a PMT yet, defer further processing of
  39767. // PES packets until one has been parsed
  39768. this.packetsWaitingForPmt.push([packet, offset, result]);
  39769. } else {
  39770. this.processPes_(packet, offset, result);
  39771. }
  39772. };
  39773. this.processPes_ = function (packet, offset, result) {
  39774. // set the appropriate stream type
  39775. if (result.pid === this.programMapTable.video) {
  39776. result.streamType = streamTypes.H264_STREAM_TYPE;
  39777. } else if (result.pid === this.programMapTable.audio) {
  39778. result.streamType = streamTypes.ADTS_STREAM_TYPE;
  39779. } else {
  39780. // if not video or audio, it is timed-metadata or unknown
  39781. // if unknown, streamType will be undefined
  39782. result.streamType = this.programMapTable['timed-metadata'][result.pid];
  39783. }
  39784. result.type = 'pes';
  39785. result.data = packet.subarray(offset);
  39786. this.trigger('data', result);
  39787. };
  39788. };
  39789. _TransportParseStream.prototype = new stream();
  39790. _TransportParseStream.STREAM_TYPES = {
  39791. h264: 0x1b,
  39792. adts: 0x0f
  39793. };
  39794. /**
  39795. * Reconsistutes program elementary stream (PES) packets from parsed
  39796. * transport stream packets. That is, if you pipe an
  39797. * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
  39798. * events will be events which capture the bytes for individual PES
  39799. * packets plus relevant metadata that has been extracted from the
  39800. * container.
  39801. */
  39802. _ElementaryStream = function ElementaryStream() {
  39803. var self = this,
  39804. segmentHadPmt = false,
  39805. // PES packet fragments
  39806. video = {
  39807. data: [],
  39808. size: 0
  39809. },
  39810. audio = {
  39811. data: [],
  39812. size: 0
  39813. },
  39814. timedMetadata = {
  39815. data: [],
  39816. size: 0
  39817. },
  39818. programMapTable,
  39819. parsePes = function parsePes(payload, pes) {
  39820. var ptsDtsFlags;
  39821. var startPrefix = payload[0] << 16 | payload[1] << 8 | payload[2]; // default to an empty array
  39822. pes.data = new Uint8Array(); // In certain live streams, the start of a TS fragment has ts packets
  39823. // that are frame data that is continuing from the previous fragment. This
  39824. // is to check that the pes data is the start of a new pes payload
  39825. if (startPrefix !== 1) {
  39826. return;
  39827. } // get the packet length, this will be 0 for video
  39828. pes.packetLength = 6 + (payload[4] << 8 | payload[5]); // find out if this packets starts a new keyframe
  39829. pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0; // PES packets may be annotated with a PTS value, or a PTS value
  39830. // and a DTS value. Determine what combination of values is
  39831. // available to work with.
  39832. ptsDtsFlags = payload[7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  39833. // performs all bitwise operations on 32-bit integers but javascript
  39834. // supports a much greater range (52-bits) of integer using standard
  39835. // mathematical operations.
  39836. // We construct a 31-bit value using bitwise operators over the 31
  39837. // most significant bits and then multiply by 4 (equal to a left-shift
  39838. // of 2) before we add the final 2 least significant bits of the
  39839. // timestamp (equal to an OR.)
  39840. if (ptsDtsFlags & 0xC0) {
  39841. // the PTS and DTS are not written out directly. For information
  39842. // on how they are encoded, see
  39843. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  39844. pes.pts = (payload[9] & 0x0E) << 27 | (payload[10] & 0xFF) << 20 | (payload[11] & 0xFE) << 12 | (payload[12] & 0xFF) << 5 | (payload[13] & 0xFE) >>> 3;
  39845. pes.pts *= 4; // Left shift by 2
  39846. pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
  39847. pes.dts = pes.pts;
  39848. if (ptsDtsFlags & 0x40) {
  39849. pes.dts = (payload[14] & 0x0E) << 27 | (payload[15] & 0xFF) << 20 | (payload[16] & 0xFE) << 12 | (payload[17] & 0xFF) << 5 | (payload[18] & 0xFE) >>> 3;
  39850. pes.dts *= 4; // Left shift by 2
  39851. pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
  39852. }
  39853. } // the data section starts immediately after the PES header.
  39854. // pes_header_data_length specifies the number of header bytes
  39855. // that follow the last byte of the field.
  39856. pes.data = payload.subarray(9 + payload[8]);
  39857. },
  39858. /**
  39859. * Pass completely parsed PES packets to the next stream in the pipeline
  39860. **/
  39861. flushStream = function flushStream(stream, type, forceFlush) {
  39862. var packetData = new Uint8Array(stream.size),
  39863. event = {
  39864. type: type
  39865. },
  39866. i = 0,
  39867. offset = 0,
  39868. packetFlushable = false,
  39869. fragment; // do nothing if there is not enough buffered data for a complete
  39870. // PES header
  39871. if (!stream.data.length || stream.size < 9) {
  39872. return;
  39873. }
  39874. event.trackId = stream.data[0].pid; // reassemble the packet
  39875. for (i = 0; i < stream.data.length; i++) {
  39876. fragment = stream.data[i];
  39877. packetData.set(fragment.data, offset);
  39878. offset += fragment.data.byteLength;
  39879. } // parse assembled packet's PES header
  39880. parsePes(packetData, event); // non-video PES packets MUST have a non-zero PES_packet_length
  39881. // check that there is enough stream data to fill the packet
  39882. packetFlushable = type === 'video' || event.packetLength <= stream.size; // flush pending packets if the conditions are right
  39883. if (forceFlush || packetFlushable) {
  39884. stream.size = 0;
  39885. stream.data.length = 0;
  39886. } // only emit packets that are complete. this is to avoid assembling
  39887. // incomplete PES packets due to poor segmentation
  39888. if (packetFlushable) {
  39889. self.trigger('data', event);
  39890. }
  39891. };
  39892. _ElementaryStream.prototype.init.call(this);
  39893. /**
  39894. * Identifies M2TS packet types and parses PES packets using metadata
  39895. * parsed from the PMT
  39896. **/
  39897. this.push = function (data) {
  39898. ({
  39899. pat: function pat() {// we have to wait for the PMT to arrive as well before we
  39900. // have any meaningful metadata
  39901. },
  39902. pes: function pes() {
  39903. var stream, streamType;
  39904. switch (data.streamType) {
  39905. case streamTypes.H264_STREAM_TYPE:
  39906. stream = video;
  39907. streamType = 'video';
  39908. break;
  39909. case streamTypes.ADTS_STREAM_TYPE:
  39910. stream = audio;
  39911. streamType = 'audio';
  39912. break;
  39913. case streamTypes.METADATA_STREAM_TYPE:
  39914. stream = timedMetadata;
  39915. streamType = 'timed-metadata';
  39916. break;
  39917. default:
  39918. // ignore unknown stream types
  39919. return;
  39920. } // if a new packet is starting, we can flush the completed
  39921. // packet
  39922. if (data.payloadUnitStartIndicator) {
  39923. flushStream(stream, streamType, true);
  39924. } // buffer this fragment until we are sure we've received the
  39925. // complete payload
  39926. stream.data.push(data);
  39927. stream.size += data.data.byteLength;
  39928. },
  39929. pmt: function pmt() {
  39930. var event = {
  39931. type: 'metadata',
  39932. tracks: []
  39933. };
  39934. programMapTable = data.programMapTable; // translate audio and video streams to tracks
  39935. if (programMapTable.video !== null) {
  39936. event.tracks.push({
  39937. timelineStartInfo: {
  39938. baseMediaDecodeTime: 0
  39939. },
  39940. id: +programMapTable.video,
  39941. codec: 'avc',
  39942. type: 'video'
  39943. });
  39944. }
  39945. if (programMapTable.audio !== null) {
  39946. event.tracks.push({
  39947. timelineStartInfo: {
  39948. baseMediaDecodeTime: 0
  39949. },
  39950. id: +programMapTable.audio,
  39951. codec: 'adts',
  39952. type: 'audio'
  39953. });
  39954. }
  39955. segmentHadPmt = true;
  39956. self.trigger('data', event);
  39957. }
  39958. })[data.type]();
  39959. };
  39960. this.reset = function () {
  39961. video.size = 0;
  39962. video.data.length = 0;
  39963. audio.size = 0;
  39964. audio.data.length = 0;
  39965. this.trigger('reset');
  39966. };
  39967. /**
  39968. * Flush any remaining input. Video PES packets may be of variable
  39969. * length. Normally, the start of a new video packet can trigger the
  39970. * finalization of the previous packet. That is not possible if no
  39971. * more video is forthcoming, however. In that case, some other
  39972. * mechanism (like the end of the file) has to be employed. When it is
  39973. * clear that no additional data is forthcoming, calling this method
  39974. * will flush the buffered packets.
  39975. */
  39976. this.flushStreams_ = function () {
  39977. // !!THIS ORDER IS IMPORTANT!!
  39978. // video first then audio
  39979. flushStream(video, 'video');
  39980. flushStream(audio, 'audio');
  39981. flushStream(timedMetadata, 'timed-metadata');
  39982. };
  39983. this.flush = function () {
  39984. // if on flush we haven't had a pmt emitted
  39985. // and we have a pmt to emit. emit the pmt
  39986. // so that we trigger a trackinfo downstream.
  39987. if (!segmentHadPmt && programMapTable) {
  39988. var pmt = {
  39989. type: 'metadata',
  39990. tracks: []
  39991. }; // translate audio and video streams to tracks
  39992. if (programMapTable.video !== null) {
  39993. pmt.tracks.push({
  39994. timelineStartInfo: {
  39995. baseMediaDecodeTime: 0
  39996. },
  39997. id: +programMapTable.video,
  39998. codec: 'avc',
  39999. type: 'video'
  40000. });
  40001. }
  40002. if (programMapTable.audio !== null) {
  40003. pmt.tracks.push({
  40004. timelineStartInfo: {
  40005. baseMediaDecodeTime: 0
  40006. },
  40007. id: +programMapTable.audio,
  40008. codec: 'adts',
  40009. type: 'audio'
  40010. });
  40011. }
  40012. self.trigger('data', pmt);
  40013. }
  40014. segmentHadPmt = false;
  40015. this.flushStreams_();
  40016. this.trigger('done');
  40017. };
  40018. };
  40019. _ElementaryStream.prototype = new stream();
  40020. var m2ts = {
  40021. PAT_PID: 0x0000,
  40022. MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH$1,
  40023. TransportPacketStream: _TransportPacketStream,
  40024. TransportParseStream: _TransportParseStream,
  40025. ElementaryStream: _ElementaryStream,
  40026. TimestampRolloverStream: TimestampRolloverStream,
  40027. CaptionStream: captionStream.CaptionStream,
  40028. Cea608Stream: captionStream.Cea608Stream,
  40029. Cea708Stream: captionStream.Cea708Stream,
  40030. MetadataStream: metadataStream
  40031. };
  40032. for (var type in streamTypes) {
  40033. if (streamTypes.hasOwnProperty(type)) {
  40034. m2ts[type] = streamTypes[type];
  40035. }
  40036. }
  40037. var m2ts_1 = m2ts;
  40038. var ONE_SECOND_IN_TS$2 = clock.ONE_SECOND_IN_TS;
  40039. var _AdtsStream;
  40040. var ADTS_SAMPLING_FREQUENCIES$1 = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  40041. /*
  40042. * Accepts a ElementaryStream and emits data events with parsed
  40043. * AAC Audio Frames of the individual packets. Input audio in ADTS
  40044. * format is unpacked and re-emitted as AAC frames.
  40045. *
  40046. * @see http://wiki.multimedia.cx/index.php?title=ADTS
  40047. * @see http://wiki.multimedia.cx/?title=Understanding_AAC
  40048. */
  40049. _AdtsStream = function AdtsStream(handlePartialSegments) {
  40050. var buffer,
  40051. frameNum = 0;
  40052. _AdtsStream.prototype.init.call(this);
  40053. this.skipWarn_ = function (start, end) {
  40054. this.trigger('log', {
  40055. level: 'warn',
  40056. message: "adts skiping bytes " + start + " to " + end + " in frame " + frameNum + " outside syncword"
  40057. });
  40058. };
  40059. this.push = function (packet) {
  40060. var i = 0,
  40061. frameLength,
  40062. protectionSkipBytes,
  40063. oldBuffer,
  40064. sampleCount,
  40065. adtsFrameDuration;
  40066. if (!handlePartialSegments) {
  40067. frameNum = 0;
  40068. }
  40069. if (packet.type !== 'audio') {
  40070. // ignore non-audio data
  40071. return;
  40072. } // Prepend any data in the buffer to the input data so that we can parse
  40073. // aac frames the cross a PES packet boundary
  40074. if (buffer && buffer.length) {
  40075. oldBuffer = buffer;
  40076. buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
  40077. buffer.set(oldBuffer);
  40078. buffer.set(packet.data, oldBuffer.byteLength);
  40079. } else {
  40080. buffer = packet.data;
  40081. } // unpack any ADTS frames which have been fully received
  40082. // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
  40083. var skip; // We use i + 7 here because we want to be able to parse the entire header.
  40084. // If we don't have enough bytes to do that, then we definitely won't have a full frame.
  40085. while (i + 7 < buffer.length) {
  40086. // Look for the start of an ADTS header..
  40087. if (buffer[i] !== 0xFF || (buffer[i + 1] & 0xF6) !== 0xF0) {
  40088. if (typeof skip !== 'number') {
  40089. skip = i;
  40090. } // If a valid header was not found, jump one forward and attempt to
  40091. // find a valid ADTS header starting at the next byte
  40092. i++;
  40093. continue;
  40094. }
  40095. if (typeof skip === 'number') {
  40096. this.skipWarn_(skip, i);
  40097. skip = null;
  40098. } // The protection skip bit tells us if we have 2 bytes of CRC data at the
  40099. // end of the ADTS header
  40100. protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2; // Frame length is a 13 bit integer starting 16 bits from the
  40101. // end of the sync sequence
  40102. // NOTE: frame length includes the size of the header
  40103. frameLength = (buffer[i + 3] & 0x03) << 11 | buffer[i + 4] << 3 | (buffer[i + 5] & 0xe0) >> 5;
  40104. sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
  40105. 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,
  40106. // then we have to wait for more data
  40107. if (buffer.byteLength - i < frameLength) {
  40108. break;
  40109. } // Otherwise, deliver the complete AAC frame
  40110. this.trigger('data', {
  40111. pts: packet.pts + frameNum * adtsFrameDuration,
  40112. dts: packet.dts + frameNum * adtsFrameDuration,
  40113. sampleCount: sampleCount,
  40114. audioobjecttype: (buffer[i + 2] >>> 6 & 0x03) + 1,
  40115. channelcount: (buffer[i + 2] & 1) << 2 | (buffer[i + 3] & 0xc0) >>> 6,
  40116. samplerate: ADTS_SAMPLING_FREQUENCIES$1[(buffer[i + 2] & 0x3c) >>> 2],
  40117. samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
  40118. // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
  40119. samplesize: 16,
  40120. // data is the frame without it's header
  40121. data: buffer.subarray(i + 7 + protectionSkipBytes, i + frameLength)
  40122. });
  40123. frameNum++;
  40124. i += frameLength;
  40125. }
  40126. if (typeof skip === 'number') {
  40127. this.skipWarn_(skip, i);
  40128. skip = null;
  40129. } // remove processed bytes from the buffer.
  40130. buffer = buffer.subarray(i);
  40131. };
  40132. this.flush = function () {
  40133. frameNum = 0;
  40134. this.trigger('done');
  40135. };
  40136. this.reset = function () {
  40137. buffer = void 0;
  40138. this.trigger('reset');
  40139. };
  40140. this.endTimeline = function () {
  40141. buffer = void 0;
  40142. this.trigger('endedtimeline');
  40143. };
  40144. };
  40145. _AdtsStream.prototype = new stream();
  40146. var adts = _AdtsStream;
  40147. /**
  40148. * mux.js
  40149. *
  40150. * Copyright (c) Brightcove
  40151. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  40152. */
  40153. var ExpGolomb;
  40154. /**
  40155. * Parser for exponential Golomb codes, a variable-bitwidth number encoding
  40156. * scheme used by h264.
  40157. */
  40158. ExpGolomb = function ExpGolomb(workingData) {
  40159. var // the number of bytes left to examine in workingData
  40160. workingBytesAvailable = workingData.byteLength,
  40161. // the current word being examined
  40162. workingWord = 0,
  40163. // :uint
  40164. // the number of bits left to examine in the current word
  40165. workingBitsAvailable = 0; // :uint;
  40166. // ():uint
  40167. this.length = function () {
  40168. return 8 * workingBytesAvailable;
  40169. }; // ():uint
  40170. this.bitsAvailable = function () {
  40171. return 8 * workingBytesAvailable + workingBitsAvailable;
  40172. }; // ():void
  40173. this.loadWord = function () {
  40174. var position = workingData.byteLength - workingBytesAvailable,
  40175. workingBytes = new Uint8Array(4),
  40176. availableBytes = Math.min(4, workingBytesAvailable);
  40177. if (availableBytes === 0) {
  40178. throw new Error('no bytes available');
  40179. }
  40180. workingBytes.set(workingData.subarray(position, position + availableBytes));
  40181. workingWord = new DataView(workingBytes.buffer).getUint32(0); // track the amount of workingData that has been processed
  40182. workingBitsAvailable = availableBytes * 8;
  40183. workingBytesAvailable -= availableBytes;
  40184. }; // (count:int):void
  40185. this.skipBits = function (count) {
  40186. var skipBytes; // :int
  40187. if (workingBitsAvailable > count) {
  40188. workingWord <<= count;
  40189. workingBitsAvailable -= count;
  40190. } else {
  40191. count -= workingBitsAvailable;
  40192. skipBytes = Math.floor(count / 8);
  40193. count -= skipBytes * 8;
  40194. workingBytesAvailable -= skipBytes;
  40195. this.loadWord();
  40196. workingWord <<= count;
  40197. workingBitsAvailable -= count;
  40198. }
  40199. }; // (size:int):uint
  40200. this.readBits = function (size) {
  40201. var bits = Math.min(workingBitsAvailable, size),
  40202. // :uint
  40203. valu = workingWord >>> 32 - bits; // :uint
  40204. // if size > 31, handle error
  40205. workingBitsAvailable -= bits;
  40206. if (workingBitsAvailable > 0) {
  40207. workingWord <<= bits;
  40208. } else if (workingBytesAvailable > 0) {
  40209. this.loadWord();
  40210. }
  40211. bits = size - bits;
  40212. if (bits > 0) {
  40213. return valu << bits | this.readBits(bits);
  40214. }
  40215. return valu;
  40216. }; // ():uint
  40217. this.skipLeadingZeros = function () {
  40218. var leadingZeroCount; // :uint
  40219. for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
  40220. if ((workingWord & 0x80000000 >>> leadingZeroCount) !== 0) {
  40221. // the first bit of working word is 1
  40222. workingWord <<= leadingZeroCount;
  40223. workingBitsAvailable -= leadingZeroCount;
  40224. return leadingZeroCount;
  40225. }
  40226. } // we exhausted workingWord and still have not found a 1
  40227. this.loadWord();
  40228. return leadingZeroCount + this.skipLeadingZeros();
  40229. }; // ():void
  40230. this.skipUnsignedExpGolomb = function () {
  40231. this.skipBits(1 + this.skipLeadingZeros());
  40232. }; // ():void
  40233. this.skipExpGolomb = function () {
  40234. this.skipBits(1 + this.skipLeadingZeros());
  40235. }; // ():uint
  40236. this.readUnsignedExpGolomb = function () {
  40237. var clz = this.skipLeadingZeros(); // :uint
  40238. return this.readBits(clz + 1) - 1;
  40239. }; // ():int
  40240. this.readExpGolomb = function () {
  40241. var valu = this.readUnsignedExpGolomb(); // :int
  40242. if (0x01 & valu) {
  40243. // the number is odd if the low order bit is set
  40244. return 1 + valu >>> 1; // add 1 to make it even, and divide by 2
  40245. }
  40246. return -1 * (valu >>> 1); // divide by two then make it negative
  40247. }; // Some convenience functions
  40248. // :Boolean
  40249. this.readBoolean = function () {
  40250. return this.readBits(1) === 1;
  40251. }; // ():int
  40252. this.readUnsignedByte = function () {
  40253. return this.readBits(8);
  40254. };
  40255. this.loadWord();
  40256. };
  40257. var expGolomb = ExpGolomb;
  40258. var _H264Stream, _NalByteStream;
  40259. var PROFILES_WITH_OPTIONAL_SPS_DATA;
  40260. /**
  40261. * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
  40262. */
  40263. _NalByteStream = function NalByteStream() {
  40264. var syncPoint = 0,
  40265. i,
  40266. buffer;
  40267. _NalByteStream.prototype.init.call(this);
  40268. /*
  40269. * Scans a byte stream and triggers a data event with the NAL units found.
  40270. * @param {Object} data Event received from H264Stream
  40271. * @param {Uint8Array} data.data The h264 byte stream to be scanned
  40272. *
  40273. * @see H264Stream.push
  40274. */
  40275. this.push = function (data) {
  40276. var swapBuffer;
  40277. if (!buffer) {
  40278. buffer = data.data;
  40279. } else {
  40280. swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
  40281. swapBuffer.set(buffer);
  40282. swapBuffer.set(data.data, buffer.byteLength);
  40283. buffer = swapBuffer;
  40284. }
  40285. var len = buffer.byteLength; // Rec. ITU-T H.264, Annex B
  40286. // scan for NAL unit boundaries
  40287. // a match looks like this:
  40288. // 0 0 1 .. NAL .. 0 0 1
  40289. // ^ sync point ^ i
  40290. // or this:
  40291. // 0 0 1 .. NAL .. 0 0 0
  40292. // ^ sync point ^ i
  40293. // advance the sync point to a NAL start, if necessary
  40294. for (; syncPoint < len - 3; syncPoint++) {
  40295. if (buffer[syncPoint + 2] === 1) {
  40296. // the sync point is properly aligned
  40297. i = syncPoint + 5;
  40298. break;
  40299. }
  40300. }
  40301. while (i < len) {
  40302. // look at the current byte to determine if we've hit the end of
  40303. // a NAL unit boundary
  40304. switch (buffer[i]) {
  40305. case 0:
  40306. // skip past non-sync sequences
  40307. if (buffer[i - 1] !== 0) {
  40308. i += 2;
  40309. break;
  40310. } else if (buffer[i - 2] !== 0) {
  40311. i++;
  40312. break;
  40313. } // deliver the NAL unit if it isn't empty
  40314. if (syncPoint + 3 !== i - 2) {
  40315. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  40316. } // drop trailing zeroes
  40317. do {
  40318. i++;
  40319. } while (buffer[i] !== 1 && i < len);
  40320. syncPoint = i - 2;
  40321. i += 3;
  40322. break;
  40323. case 1:
  40324. // skip past non-sync sequences
  40325. if (buffer[i - 1] !== 0 || buffer[i - 2] !== 0) {
  40326. i += 3;
  40327. break;
  40328. } // deliver the NAL unit
  40329. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  40330. syncPoint = i - 2;
  40331. i += 3;
  40332. break;
  40333. default:
  40334. // the current byte isn't a one or zero, so it cannot be part
  40335. // of a sync sequence
  40336. i += 3;
  40337. break;
  40338. }
  40339. } // filter out the NAL units that were delivered
  40340. buffer = buffer.subarray(syncPoint);
  40341. i -= syncPoint;
  40342. syncPoint = 0;
  40343. };
  40344. this.reset = function () {
  40345. buffer = null;
  40346. syncPoint = 0;
  40347. this.trigger('reset');
  40348. };
  40349. this.flush = function () {
  40350. // deliver the last buffered NAL unit
  40351. if (buffer && buffer.byteLength > 3) {
  40352. this.trigger('data', buffer.subarray(syncPoint + 3));
  40353. } // reset the stream state
  40354. buffer = null;
  40355. syncPoint = 0;
  40356. this.trigger('done');
  40357. };
  40358. this.endTimeline = function () {
  40359. this.flush();
  40360. this.trigger('endedtimeline');
  40361. };
  40362. };
  40363. _NalByteStream.prototype = new stream(); // values of profile_idc that indicate additional fields are included in the SPS
  40364. // see Recommendation ITU-T H.264 (4/2013),
  40365. // 7.3.2.1.1 Sequence parameter set data syntax
  40366. PROFILES_WITH_OPTIONAL_SPS_DATA = {
  40367. 100: true,
  40368. 110: true,
  40369. 122: true,
  40370. 244: true,
  40371. 44: true,
  40372. 83: true,
  40373. 86: true,
  40374. 118: true,
  40375. 128: true,
  40376. // TODO: the three profiles below don't
  40377. // appear to have sps data in the specificiation anymore?
  40378. 138: true,
  40379. 139: true,
  40380. 134: true
  40381. };
  40382. /**
  40383. * Accepts input from a ElementaryStream and produces H.264 NAL unit data
  40384. * events.
  40385. */
  40386. _H264Stream = function H264Stream() {
  40387. var nalByteStream = new _NalByteStream(),
  40388. self,
  40389. trackId,
  40390. currentPts,
  40391. currentDts,
  40392. discardEmulationPreventionBytes,
  40393. readSequenceParameterSet,
  40394. skipScalingList;
  40395. _H264Stream.prototype.init.call(this);
  40396. self = this;
  40397. /*
  40398. * Pushes a packet from a stream onto the NalByteStream
  40399. *
  40400. * @param {Object} packet - A packet received from a stream
  40401. * @param {Uint8Array} packet.data - The raw bytes of the packet
  40402. * @param {Number} packet.dts - Decode timestamp of the packet
  40403. * @param {Number} packet.pts - Presentation timestamp of the packet
  40404. * @param {Number} packet.trackId - The id of the h264 track this packet came from
  40405. * @param {('video'|'audio')} packet.type - The type of packet
  40406. *
  40407. */
  40408. this.push = function (packet) {
  40409. if (packet.type !== 'video') {
  40410. return;
  40411. }
  40412. trackId = packet.trackId;
  40413. currentPts = packet.pts;
  40414. currentDts = packet.dts;
  40415. nalByteStream.push(packet);
  40416. };
  40417. /*
  40418. * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
  40419. * for the NALUs to the next stream component.
  40420. * Also, preprocess caption and sequence parameter NALUs.
  40421. *
  40422. * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
  40423. * @see NalByteStream.push
  40424. */
  40425. nalByteStream.on('data', function (data) {
  40426. var event = {
  40427. trackId: trackId,
  40428. pts: currentPts,
  40429. dts: currentDts,
  40430. data: data,
  40431. nalUnitTypeCode: data[0] & 0x1f
  40432. };
  40433. switch (event.nalUnitTypeCode) {
  40434. case 0x05:
  40435. event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
  40436. break;
  40437. case 0x06:
  40438. event.nalUnitType = 'sei_rbsp';
  40439. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  40440. break;
  40441. case 0x07:
  40442. event.nalUnitType = 'seq_parameter_set_rbsp';
  40443. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  40444. event.config = readSequenceParameterSet(event.escapedRBSP);
  40445. break;
  40446. case 0x08:
  40447. event.nalUnitType = 'pic_parameter_set_rbsp';
  40448. break;
  40449. case 0x09:
  40450. event.nalUnitType = 'access_unit_delimiter_rbsp';
  40451. break;
  40452. } // This triggers data on the H264Stream
  40453. self.trigger('data', event);
  40454. });
  40455. nalByteStream.on('done', function () {
  40456. self.trigger('done');
  40457. });
  40458. nalByteStream.on('partialdone', function () {
  40459. self.trigger('partialdone');
  40460. });
  40461. nalByteStream.on('reset', function () {
  40462. self.trigger('reset');
  40463. });
  40464. nalByteStream.on('endedtimeline', function () {
  40465. self.trigger('endedtimeline');
  40466. });
  40467. this.flush = function () {
  40468. nalByteStream.flush();
  40469. };
  40470. this.partialFlush = function () {
  40471. nalByteStream.partialFlush();
  40472. };
  40473. this.reset = function () {
  40474. nalByteStream.reset();
  40475. };
  40476. this.endTimeline = function () {
  40477. nalByteStream.endTimeline();
  40478. };
  40479. /**
  40480. * Advance the ExpGolomb decoder past a scaling list. The scaling
  40481. * list is optionally transmitted as part of a sequence parameter
  40482. * set and is not relevant to transmuxing.
  40483. * @param count {number} the number of entries in this scaling list
  40484. * @param expGolombDecoder {object} an ExpGolomb pointed to the
  40485. * start of a scaling list
  40486. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  40487. */
  40488. skipScalingList = function skipScalingList(count, expGolombDecoder) {
  40489. var lastScale = 8,
  40490. nextScale = 8,
  40491. j,
  40492. deltaScale;
  40493. for (j = 0; j < count; j++) {
  40494. if (nextScale !== 0) {
  40495. deltaScale = expGolombDecoder.readExpGolomb();
  40496. nextScale = (lastScale + deltaScale + 256) % 256;
  40497. }
  40498. lastScale = nextScale === 0 ? lastScale : nextScale;
  40499. }
  40500. };
  40501. /**
  40502. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  40503. * Sequence Payload"
  40504. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  40505. * unit
  40506. * @return {Uint8Array} the RBSP without any Emulation
  40507. * Prevention Bytes
  40508. */
  40509. discardEmulationPreventionBytes = function discardEmulationPreventionBytes(data) {
  40510. var length = data.byteLength,
  40511. emulationPreventionBytesPositions = [],
  40512. i = 1,
  40513. newLength,
  40514. newData; // Find all `Emulation Prevention Bytes`
  40515. while (i < length - 2) {
  40516. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  40517. emulationPreventionBytesPositions.push(i + 2);
  40518. i += 2;
  40519. } else {
  40520. i++;
  40521. }
  40522. } // If no Emulation Prevention Bytes were found just return the original
  40523. // array
  40524. if (emulationPreventionBytesPositions.length === 0) {
  40525. return data;
  40526. } // Create a new array to hold the NAL unit data
  40527. newLength = length - emulationPreventionBytesPositions.length;
  40528. newData = new Uint8Array(newLength);
  40529. var sourceIndex = 0;
  40530. for (i = 0; i < newLength; sourceIndex++, i++) {
  40531. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  40532. // Skip this byte
  40533. sourceIndex++; // Remove this position index
  40534. emulationPreventionBytesPositions.shift();
  40535. }
  40536. newData[i] = data[sourceIndex];
  40537. }
  40538. return newData;
  40539. };
  40540. /**
  40541. * Read a sequence parameter set and return some interesting video
  40542. * properties. A sequence parameter set is the H264 metadata that
  40543. * describes the properties of upcoming video frames.
  40544. * @param data {Uint8Array} the bytes of a sequence parameter set
  40545. * @return {object} an object with configuration parsed from the
  40546. * sequence parameter set, including the dimensions of the
  40547. * associated video frames.
  40548. */
  40549. readSequenceParameterSet = function readSequenceParameterSet(data) {
  40550. var frameCropLeftOffset = 0,
  40551. frameCropRightOffset = 0,
  40552. frameCropTopOffset = 0,
  40553. frameCropBottomOffset = 0,
  40554. expGolombDecoder,
  40555. profileIdc,
  40556. levelIdc,
  40557. profileCompatibility,
  40558. chromaFormatIdc,
  40559. picOrderCntType,
  40560. numRefFramesInPicOrderCntCycle,
  40561. picWidthInMbsMinus1,
  40562. picHeightInMapUnitsMinus1,
  40563. frameMbsOnlyFlag,
  40564. scalingListCount,
  40565. sarRatio = [1, 1],
  40566. aspectRatioIdc,
  40567. i;
  40568. expGolombDecoder = new expGolomb(data);
  40569. profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
  40570. profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
  40571. levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
  40572. expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
  40573. // some profiles have more optional data we don't need
  40574. if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
  40575. chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
  40576. if (chromaFormatIdc === 3) {
  40577. expGolombDecoder.skipBits(1); // separate_colour_plane_flag
  40578. }
  40579. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
  40580. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
  40581. expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
  40582. if (expGolombDecoder.readBoolean()) {
  40583. // seq_scaling_matrix_present_flag
  40584. scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;
  40585. for (i = 0; i < scalingListCount; i++) {
  40586. if (expGolombDecoder.readBoolean()) {
  40587. // seq_scaling_list_present_flag[ i ]
  40588. if (i < 6) {
  40589. skipScalingList(16, expGolombDecoder);
  40590. } else {
  40591. skipScalingList(64, expGolombDecoder);
  40592. }
  40593. }
  40594. }
  40595. }
  40596. }
  40597. expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
  40598. picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
  40599. if (picOrderCntType === 0) {
  40600. expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
  40601. } else if (picOrderCntType === 1) {
  40602. expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
  40603. expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
  40604. expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
  40605. numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
  40606. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  40607. expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
  40608. }
  40609. }
  40610. expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
  40611. expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
  40612. picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  40613. picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  40614. frameMbsOnlyFlag = expGolombDecoder.readBits(1);
  40615. if (frameMbsOnlyFlag === 0) {
  40616. expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
  40617. }
  40618. expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
  40619. if (expGolombDecoder.readBoolean()) {
  40620. // frame_cropping_flag
  40621. frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
  40622. frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
  40623. frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
  40624. frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
  40625. }
  40626. if (expGolombDecoder.readBoolean()) {
  40627. // vui_parameters_present_flag
  40628. if (expGolombDecoder.readBoolean()) {
  40629. // aspect_ratio_info_present_flag
  40630. aspectRatioIdc = expGolombDecoder.readUnsignedByte();
  40631. switch (aspectRatioIdc) {
  40632. case 1:
  40633. sarRatio = [1, 1];
  40634. break;
  40635. case 2:
  40636. sarRatio = [12, 11];
  40637. break;
  40638. case 3:
  40639. sarRatio = [10, 11];
  40640. break;
  40641. case 4:
  40642. sarRatio = [16, 11];
  40643. break;
  40644. case 5:
  40645. sarRatio = [40, 33];
  40646. break;
  40647. case 6:
  40648. sarRatio = [24, 11];
  40649. break;
  40650. case 7:
  40651. sarRatio = [20, 11];
  40652. break;
  40653. case 8:
  40654. sarRatio = [32, 11];
  40655. break;
  40656. case 9:
  40657. sarRatio = [80, 33];
  40658. break;
  40659. case 10:
  40660. sarRatio = [18, 11];
  40661. break;
  40662. case 11:
  40663. sarRatio = [15, 11];
  40664. break;
  40665. case 12:
  40666. sarRatio = [64, 33];
  40667. break;
  40668. case 13:
  40669. sarRatio = [160, 99];
  40670. break;
  40671. case 14:
  40672. sarRatio = [4, 3];
  40673. break;
  40674. case 15:
  40675. sarRatio = [3, 2];
  40676. break;
  40677. case 16:
  40678. sarRatio = [2, 1];
  40679. break;
  40680. case 255:
  40681. {
  40682. sarRatio = [expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte()];
  40683. break;
  40684. }
  40685. }
  40686. if (sarRatio) {
  40687. sarRatio[0] / sarRatio[1];
  40688. }
  40689. }
  40690. }
  40691. return {
  40692. profileIdc: profileIdc,
  40693. levelIdc: levelIdc,
  40694. profileCompatibility: profileCompatibility,
  40695. width: (picWidthInMbsMinus1 + 1) * 16 - frameCropLeftOffset * 2 - frameCropRightOffset * 2,
  40696. height: (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 - frameCropTopOffset * 2 - frameCropBottomOffset * 2,
  40697. // sar is sample aspect ratio
  40698. sarRatio: sarRatio
  40699. };
  40700. };
  40701. };
  40702. _H264Stream.prototype = new stream();
  40703. var h264 = {
  40704. H264Stream: _H264Stream,
  40705. NalByteStream: _NalByteStream
  40706. };
  40707. /**
  40708. * mux.js
  40709. *
  40710. * Copyright (c) Brightcove
  40711. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  40712. *
  40713. * Utilities to detect basic properties and metadata about Aac data.
  40714. */
  40715. var ADTS_SAMPLING_FREQUENCIES = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350];
  40716. var parseId3TagSize = function parseId3TagSize(header, byteIndex) {
  40717. var returnSize = header[byteIndex + 6] << 21 | header[byteIndex + 7] << 14 | header[byteIndex + 8] << 7 | header[byteIndex + 9],
  40718. flags = header[byteIndex + 5],
  40719. footerPresent = (flags & 16) >> 4; // if we get a negative returnSize clamp it to 0
  40720. returnSize = returnSize >= 0 ? returnSize : 0;
  40721. if (footerPresent) {
  40722. return returnSize + 20;
  40723. }
  40724. return returnSize + 10;
  40725. };
  40726. var getId3Offset = function getId3Offset(data, offset) {
  40727. if (data.length - offset < 10 || data[offset] !== 'I'.charCodeAt(0) || data[offset + 1] !== 'D'.charCodeAt(0) || data[offset + 2] !== '3'.charCodeAt(0)) {
  40728. return offset;
  40729. }
  40730. offset += parseId3TagSize(data, offset);
  40731. return getId3Offset(data, offset);
  40732. }; // TODO: use vhs-utils
  40733. var isLikelyAacData$1 = function isLikelyAacData(data) {
  40734. var offset = getId3Offset(data, 0);
  40735. return data.length >= offset + 2 && (data[offset] & 0xFF) === 0xFF && (data[offset + 1] & 0xF0) === 0xF0 && // verify that the 2 layer bits are 0, aka this
  40736. // is not mp3 data but aac data.
  40737. (data[offset + 1] & 0x16) === 0x10;
  40738. };
  40739. var parseSyncSafeInteger = function parseSyncSafeInteger(data) {
  40740. return data[0] << 21 | data[1] << 14 | data[2] << 7 | data[3];
  40741. }; // return a percent-encoded representation of the specified byte range
  40742. // @see http://en.wikipedia.org/wiki/Percent-encoding
  40743. var percentEncode = function percentEncode(bytes, start, end) {
  40744. var i,
  40745. result = '';
  40746. for (i = start; i < end; i++) {
  40747. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  40748. }
  40749. return result;
  40750. }; // return the string representation of the specified byte range,
  40751. // interpreted as ISO-8859-1.
  40752. var parseIso88591 = function parseIso88591(bytes, start, end) {
  40753. return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
  40754. };
  40755. var parseAdtsSize = function parseAdtsSize(header, byteIndex) {
  40756. var lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
  40757. middle = header[byteIndex + 4] << 3,
  40758. highTwo = header[byteIndex + 3] & 0x3 << 11;
  40759. return highTwo | middle | lowThree;
  40760. };
  40761. var parseType$2 = function parseType(header, byteIndex) {
  40762. if (header[byteIndex] === 'I'.charCodeAt(0) && header[byteIndex + 1] === 'D'.charCodeAt(0) && header[byteIndex + 2] === '3'.charCodeAt(0)) {
  40763. return 'timed-metadata';
  40764. } else if (header[byteIndex] & 0xff === 0xff && (header[byteIndex + 1] & 0xf0) === 0xf0) {
  40765. return 'audio';
  40766. }
  40767. return null;
  40768. };
  40769. var parseSampleRate = function parseSampleRate(packet) {
  40770. var i = 0;
  40771. while (i + 5 < packet.length) {
  40772. if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
  40773. // If a valid header was not found, jump one forward and attempt to
  40774. // find a valid ADTS header starting at the next byte
  40775. i++;
  40776. continue;
  40777. }
  40778. return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];
  40779. }
  40780. return null;
  40781. };
  40782. var parseAacTimestamp = function parseAacTimestamp(packet) {
  40783. var frameStart, frameSize, frame, frameHeader; // find the start of the first frame and the end of the tag
  40784. frameStart = 10;
  40785. if (packet[5] & 0x40) {
  40786. // advance the frame start past the extended header
  40787. frameStart += 4; // header size field
  40788. frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
  40789. } // parse one or more ID3 frames
  40790. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  40791. do {
  40792. // determine the number of bytes in this frame
  40793. frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
  40794. if (frameSize < 1) {
  40795. return null;
  40796. }
  40797. frameHeader = String.fromCharCode(packet[frameStart], packet[frameStart + 1], packet[frameStart + 2], packet[frameStart + 3]);
  40798. if (frameHeader === 'PRIV') {
  40799. frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
  40800. for (var i = 0; i < frame.byteLength; i++) {
  40801. if (frame[i] === 0) {
  40802. var owner = parseIso88591(frame, 0, i);
  40803. if (owner === 'com.apple.streaming.transportStreamTimestamp') {
  40804. var d = frame.subarray(i + 1);
  40805. var size = (d[3] & 0x01) << 30 | d[4] << 22 | d[5] << 14 | d[6] << 6 | d[7] >>> 2;
  40806. size *= 4;
  40807. size += d[7] & 0x03;
  40808. return size;
  40809. }
  40810. break;
  40811. }
  40812. }
  40813. }
  40814. frameStart += 10; // advance past the frame header
  40815. frameStart += frameSize; // advance past the frame body
  40816. } while (frameStart < packet.byteLength);
  40817. return null;
  40818. };
  40819. var utils = {
  40820. isLikelyAacData: isLikelyAacData$1,
  40821. parseId3TagSize: parseId3TagSize,
  40822. parseAdtsSize: parseAdtsSize,
  40823. parseType: parseType$2,
  40824. parseSampleRate: parseSampleRate,
  40825. parseAacTimestamp: parseAacTimestamp
  40826. };
  40827. var _AacStream;
  40828. /**
  40829. * Splits an incoming stream of binary data into ADTS and ID3 Frames.
  40830. */
  40831. _AacStream = function AacStream() {
  40832. var everything = new Uint8Array(),
  40833. timeStamp = 0;
  40834. _AacStream.prototype.init.call(this);
  40835. this.setTimestamp = function (timestamp) {
  40836. timeStamp = timestamp;
  40837. };
  40838. this.push = function (bytes) {
  40839. var frameSize = 0,
  40840. byteIndex = 0,
  40841. bytesLeft,
  40842. chunk,
  40843. packet,
  40844. tempLength; // If there are bytes remaining from the last segment, prepend them to the
  40845. // bytes that were pushed in
  40846. if (everything.length) {
  40847. tempLength = everything.length;
  40848. everything = new Uint8Array(bytes.byteLength + tempLength);
  40849. everything.set(everything.subarray(0, tempLength));
  40850. everything.set(bytes, tempLength);
  40851. } else {
  40852. everything = bytes;
  40853. }
  40854. while (everything.length - byteIndex >= 3) {
  40855. if (everything[byteIndex] === 'I'.charCodeAt(0) && everything[byteIndex + 1] === 'D'.charCodeAt(0) && everything[byteIndex + 2] === '3'.charCodeAt(0)) {
  40856. // Exit early because we don't have enough to parse
  40857. // the ID3 tag header
  40858. if (everything.length - byteIndex < 10) {
  40859. break;
  40860. } // check framesize
  40861. frameSize = utils.parseId3TagSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  40862. // to emit a full packet
  40863. // Add to byteIndex to support multiple ID3 tags in sequence
  40864. if (byteIndex + frameSize > everything.length) {
  40865. break;
  40866. }
  40867. chunk = {
  40868. type: 'timed-metadata',
  40869. data: everything.subarray(byteIndex, byteIndex + frameSize)
  40870. };
  40871. this.trigger('data', chunk);
  40872. byteIndex += frameSize;
  40873. continue;
  40874. } else if ((everything[byteIndex] & 0xff) === 0xff && (everything[byteIndex + 1] & 0xf0) === 0xf0) {
  40875. // Exit early because we don't have enough to parse
  40876. // the ADTS frame header
  40877. if (everything.length - byteIndex < 7) {
  40878. break;
  40879. }
  40880. frameSize = utils.parseAdtsSize(everything, byteIndex); // Exit early if we don't have enough in the buffer
  40881. // to emit a full packet
  40882. if (byteIndex + frameSize > everything.length) {
  40883. break;
  40884. }
  40885. packet = {
  40886. type: 'audio',
  40887. data: everything.subarray(byteIndex, byteIndex + frameSize),
  40888. pts: timeStamp,
  40889. dts: timeStamp
  40890. };
  40891. this.trigger('data', packet);
  40892. byteIndex += frameSize;
  40893. continue;
  40894. }
  40895. byteIndex++;
  40896. }
  40897. bytesLeft = everything.length - byteIndex;
  40898. if (bytesLeft > 0) {
  40899. everything = everything.subarray(byteIndex);
  40900. } else {
  40901. everything = new Uint8Array();
  40902. }
  40903. };
  40904. this.reset = function () {
  40905. everything = new Uint8Array();
  40906. this.trigger('reset');
  40907. };
  40908. this.endTimeline = function () {
  40909. everything = new Uint8Array();
  40910. this.trigger('endedtimeline');
  40911. };
  40912. };
  40913. _AacStream.prototype = new stream();
  40914. var aac = _AacStream; // constants
  40915. var AUDIO_PROPERTIES = ['audioobjecttype', 'channelcount', 'samplerate', 'samplingfrequencyindex', 'samplesize'];
  40916. var audioProperties = AUDIO_PROPERTIES;
  40917. var VIDEO_PROPERTIES = ['width', 'height', 'profileIdc', 'levelIdc', 'profileCompatibility', 'sarRatio'];
  40918. var videoProperties = VIDEO_PROPERTIES;
  40919. var H264Stream = h264.H264Stream;
  40920. var isLikelyAacData = utils.isLikelyAacData;
  40921. var ONE_SECOND_IN_TS$1 = clock.ONE_SECOND_IN_TS; // object types
  40922. var _VideoSegmentStream, _AudioSegmentStream, _Transmuxer, _CoalesceStream;
  40923. var retriggerForStream = function retriggerForStream(key, event) {
  40924. event.stream = key;
  40925. this.trigger('log', event);
  40926. };
  40927. var addPipelineLogRetriggers = function addPipelineLogRetriggers(transmuxer, pipeline) {
  40928. var keys = Object.keys(pipeline);
  40929. for (var i = 0; i < keys.length; i++) {
  40930. var key = keys[i]; // skip non-stream keys and headOfPipeline
  40931. // which is just a duplicate
  40932. if (key === 'headOfPipeline' || !pipeline[key].on) {
  40933. continue;
  40934. }
  40935. pipeline[key].on('log', retriggerForStream.bind(transmuxer, key));
  40936. }
  40937. };
  40938. /**
  40939. * Compare two arrays (even typed) for same-ness
  40940. */
  40941. var arrayEquals = function arrayEquals(a, b) {
  40942. var i;
  40943. if (a.length !== b.length) {
  40944. return false;
  40945. } // compare the value of each element in the array
  40946. for (i = 0; i < a.length; i++) {
  40947. if (a[i] !== b[i]) {
  40948. return false;
  40949. }
  40950. }
  40951. return true;
  40952. };
  40953. var generateSegmentTimingInfo = function generateSegmentTimingInfo(baseMediaDecodeTime, startDts, startPts, endDts, endPts, prependedContentDuration) {
  40954. var ptsOffsetFromDts = startPts - startDts,
  40955. decodeDuration = endDts - startDts,
  40956. presentationDuration = endPts - startPts; // The PTS and DTS values are based on the actual stream times from the segment,
  40957. // however, the player time values will reflect a start from the baseMediaDecodeTime.
  40958. // In order to provide relevant values for the player times, base timing info on the
  40959. // baseMediaDecodeTime and the DTS and PTS durations of the segment.
  40960. return {
  40961. start: {
  40962. dts: baseMediaDecodeTime,
  40963. pts: baseMediaDecodeTime + ptsOffsetFromDts
  40964. },
  40965. end: {
  40966. dts: baseMediaDecodeTime + decodeDuration,
  40967. pts: baseMediaDecodeTime + presentationDuration
  40968. },
  40969. prependedContentDuration: prependedContentDuration,
  40970. baseMediaDecodeTime: baseMediaDecodeTime
  40971. };
  40972. };
  40973. /**
  40974. * Constructs a single-track, ISO BMFF media segment from AAC data
  40975. * events. The output of this stream can be fed to a SourceBuffer
  40976. * configured with a suitable initialization segment.
  40977. * @param track {object} track metadata configuration
  40978. * @param options {object} transmuxer options object
  40979. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  40980. * in the source; false to adjust the first segment to start at 0.
  40981. */
  40982. _AudioSegmentStream = function AudioSegmentStream(track, options) {
  40983. var adtsFrames = [],
  40984. sequenceNumber,
  40985. earliestAllowedDts = 0,
  40986. audioAppendStartTs = 0,
  40987. videoBaseMediaDecodeTime = Infinity;
  40988. options = options || {};
  40989. sequenceNumber = options.firstSequenceNumber || 0;
  40990. _AudioSegmentStream.prototype.init.call(this);
  40991. this.push = function (data) {
  40992. trackDecodeInfo.collectDtsInfo(track, data);
  40993. if (track) {
  40994. audioProperties.forEach(function (prop) {
  40995. track[prop] = data[prop];
  40996. });
  40997. } // buffer audio data until end() is called
  40998. adtsFrames.push(data);
  40999. };
  41000. this.setEarliestDts = function (earliestDts) {
  41001. earliestAllowedDts = earliestDts;
  41002. };
  41003. this.setVideoBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  41004. videoBaseMediaDecodeTime = baseMediaDecodeTime;
  41005. };
  41006. this.setAudioAppendStart = function (timestamp) {
  41007. audioAppendStartTs = timestamp;
  41008. };
  41009. this.flush = function () {
  41010. var frames, moof, mdat, boxes, frameDuration, segmentDuration, videoClockCyclesOfSilencePrefixed; // return early if no audio data has been observed
  41011. if (adtsFrames.length === 0) {
  41012. this.trigger('done', 'AudioSegmentStream');
  41013. return;
  41014. }
  41015. frames = audioFrameUtils.trimAdtsFramesByEarliestDts(adtsFrames, track, earliestAllowedDts);
  41016. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps); // amount of audio filled but the value is in video clock rather than audio clock
  41017. videoClockCyclesOfSilencePrefixed = audioFrameUtils.prefixWithSilence(track, frames, audioAppendStartTs, videoBaseMediaDecodeTime); // we have to build the index from byte locations to
  41018. // samples (that is, adts frames) in the audio data
  41019. track.samples = audioFrameUtils.generateSampleTable(frames); // concatenate the audio data to constuct the mdat
  41020. mdat = mp4Generator.mdat(audioFrameUtils.concatenateFrameData(frames));
  41021. adtsFrames = [];
  41022. moof = mp4Generator.moof(sequenceNumber, [track]);
  41023. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // bump the sequence number for next time
  41024. sequenceNumber++;
  41025. boxes.set(moof);
  41026. boxes.set(mdat, moof.byteLength);
  41027. trackDecodeInfo.clearDtsInfo(track);
  41028. frameDuration = Math.ceil(ONE_SECOND_IN_TS$1 * 1024 / track.samplerate); // TODO this check was added to maintain backwards compatibility (particularly with
  41029. // tests) on adding the timingInfo event. However, it seems unlikely that there's a
  41030. // valid use-case where an init segment/data should be triggered without associated
  41031. // frames. Leaving for now, but should be looked into.
  41032. if (frames.length) {
  41033. segmentDuration = frames.length * frameDuration;
  41034. this.trigger('segmentTimingInfo', generateSegmentTimingInfo( // The audio track's baseMediaDecodeTime is in audio clock cycles, but the
  41035. // frame info is in video clock cycles. Convert to match expectation of
  41036. // listeners (that all timestamps will be based on video clock cycles).
  41037. clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate), // frame times are already in video clock, as is segment duration
  41038. frames[0].dts, frames[0].pts, frames[0].dts + segmentDuration, frames[0].pts + segmentDuration, videoClockCyclesOfSilencePrefixed || 0));
  41039. this.trigger('timingInfo', {
  41040. start: frames[0].pts,
  41041. end: frames[0].pts + segmentDuration
  41042. });
  41043. }
  41044. this.trigger('data', {
  41045. track: track,
  41046. boxes: boxes
  41047. });
  41048. this.trigger('done', 'AudioSegmentStream');
  41049. };
  41050. this.reset = function () {
  41051. trackDecodeInfo.clearDtsInfo(track);
  41052. adtsFrames = [];
  41053. this.trigger('reset');
  41054. };
  41055. };
  41056. _AudioSegmentStream.prototype = new stream();
  41057. /**
  41058. * Constructs a single-track, ISO BMFF media segment from H264 data
  41059. * events. The output of this stream can be fed to a SourceBuffer
  41060. * configured with a suitable initialization segment.
  41061. * @param track {object} track metadata configuration
  41062. * @param options {object} transmuxer options object
  41063. * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
  41064. * gopsToAlignWith list when attempting to align gop pts
  41065. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  41066. * in the source; false to adjust the first segment to start at 0.
  41067. */
  41068. _VideoSegmentStream = function VideoSegmentStream(track, options) {
  41069. var sequenceNumber,
  41070. nalUnits = [],
  41071. gopsToAlignWith = [],
  41072. config,
  41073. pps;
  41074. options = options || {};
  41075. sequenceNumber = options.firstSequenceNumber || 0;
  41076. _VideoSegmentStream.prototype.init.call(this);
  41077. delete track.minPTS;
  41078. this.gopCache_ = [];
  41079. /**
  41080. * Constructs a ISO BMFF segment given H264 nalUnits
  41081. * @param {Object} nalUnit A data event representing a nalUnit
  41082. * @param {String} nalUnit.nalUnitType
  41083. * @param {Object} nalUnit.config Properties for a mp4 track
  41084. * @param {Uint8Array} nalUnit.data The nalUnit bytes
  41085. * @see lib/codecs/h264.js
  41086. **/
  41087. this.push = function (nalUnit) {
  41088. trackDecodeInfo.collectDtsInfo(track, nalUnit); // record the track config
  41089. if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
  41090. config = nalUnit.config;
  41091. track.sps = [nalUnit.data];
  41092. videoProperties.forEach(function (prop) {
  41093. track[prop] = config[prop];
  41094. }, this);
  41095. }
  41096. if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' && !pps) {
  41097. pps = nalUnit.data;
  41098. track.pps = [nalUnit.data];
  41099. } // buffer video until flush() is called
  41100. nalUnits.push(nalUnit);
  41101. };
  41102. /**
  41103. * Pass constructed ISO BMFF track and boxes on to the
  41104. * next stream in the pipeline
  41105. **/
  41106. this.flush = function () {
  41107. var frames,
  41108. gopForFusion,
  41109. gops,
  41110. moof,
  41111. mdat,
  41112. boxes,
  41113. prependedContentDuration = 0,
  41114. firstGop,
  41115. lastGop; // Throw away nalUnits at the start of the byte stream until
  41116. // we find the first AUD
  41117. while (nalUnits.length) {
  41118. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  41119. break;
  41120. }
  41121. nalUnits.shift();
  41122. } // Return early if no video data has been observed
  41123. if (nalUnits.length === 0) {
  41124. this.resetStream_();
  41125. this.trigger('done', 'VideoSegmentStream');
  41126. return;
  41127. } // Organize the raw nal-units into arrays that represent
  41128. // higher-level constructs such as frames and gops
  41129. // (group-of-pictures)
  41130. frames = frameUtils.groupNalsIntoFrames(nalUnits);
  41131. gops = frameUtils.groupFramesIntoGops(frames); // If the first frame of this fragment is not a keyframe we have
  41132. // a problem since MSE (on Chrome) requires a leading keyframe.
  41133. //
  41134. // We have two approaches to repairing this situation:
  41135. // 1) GOP-FUSION:
  41136. // This is where we keep track of the GOPS (group-of-pictures)
  41137. // from previous fragments and attempt to find one that we can
  41138. // prepend to the current fragment in order to create a valid
  41139. // fragment.
  41140. // 2) KEYFRAME-PULLING:
  41141. // Here we search for the first keyframe in the fragment and
  41142. // throw away all the frames between the start of the fragment
  41143. // and that keyframe. We then extend the duration and pull the
  41144. // PTS of the keyframe forward so that it covers the time range
  41145. // of the frames that were disposed of.
  41146. //
  41147. // #1 is far prefereable over #2 which can cause "stuttering" but
  41148. // requires more things to be just right.
  41149. if (!gops[0][0].keyFrame) {
  41150. // Search for a gop for fusion from our gopCache
  41151. gopForFusion = this.getGopForFusion_(nalUnits[0], track);
  41152. if (gopForFusion) {
  41153. // in order to provide more accurate timing information about the segment, save
  41154. // the number of seconds prepended to the original segment due to GOP fusion
  41155. prependedContentDuration = gopForFusion.duration;
  41156. gops.unshift(gopForFusion); // Adjust Gops' metadata to account for the inclusion of the
  41157. // new gop at the beginning
  41158. gops.byteLength += gopForFusion.byteLength;
  41159. gops.nalCount += gopForFusion.nalCount;
  41160. gops.pts = gopForFusion.pts;
  41161. gops.dts = gopForFusion.dts;
  41162. gops.duration += gopForFusion.duration;
  41163. } else {
  41164. // If we didn't find a candidate gop fall back to keyframe-pulling
  41165. gops = frameUtils.extendFirstKeyFrame(gops);
  41166. }
  41167. } // Trim gops to align with gopsToAlignWith
  41168. if (gopsToAlignWith.length) {
  41169. var alignedGops;
  41170. if (options.alignGopsAtEnd) {
  41171. alignedGops = this.alignGopsAtEnd_(gops);
  41172. } else {
  41173. alignedGops = this.alignGopsAtStart_(gops);
  41174. }
  41175. if (!alignedGops) {
  41176. // save all the nals in the last GOP into the gop cache
  41177. this.gopCache_.unshift({
  41178. gop: gops.pop(),
  41179. pps: track.pps,
  41180. sps: track.sps
  41181. }); // Keep a maximum of 6 GOPs in the cache
  41182. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  41183. nalUnits = []; // return early no gops can be aligned with desired gopsToAlignWith
  41184. this.resetStream_();
  41185. this.trigger('done', 'VideoSegmentStream');
  41186. return;
  41187. } // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
  41188. // when recalculated before sending off to CoalesceStream
  41189. trackDecodeInfo.clearDtsInfo(track);
  41190. gops = alignedGops;
  41191. }
  41192. trackDecodeInfo.collectDtsInfo(track, gops); // First, we have to build the index from byte locations to
  41193. // samples (that is, frames) in the video data
  41194. track.samples = frameUtils.generateSampleTable(gops); // Concatenate the video data and construct the mdat
  41195. mdat = mp4Generator.mdat(frameUtils.concatenateNalData(gops));
  41196. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(track, options.keepOriginalTimestamps);
  41197. this.trigger('processedGopsInfo', gops.map(function (gop) {
  41198. return {
  41199. pts: gop.pts,
  41200. dts: gop.dts,
  41201. byteLength: gop.byteLength
  41202. };
  41203. }));
  41204. firstGop = gops[0];
  41205. lastGop = gops[gops.length - 1];
  41206. this.trigger('segmentTimingInfo', generateSegmentTimingInfo(track.baseMediaDecodeTime, firstGop.dts, firstGop.pts, lastGop.dts + lastGop.duration, lastGop.pts + lastGop.duration, prependedContentDuration));
  41207. this.trigger('timingInfo', {
  41208. start: gops[0].pts,
  41209. end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
  41210. }); // save all the nals in the last GOP into the gop cache
  41211. this.gopCache_.unshift({
  41212. gop: gops.pop(),
  41213. pps: track.pps,
  41214. sps: track.sps
  41215. }); // Keep a maximum of 6 GOPs in the cache
  41216. this.gopCache_.length = Math.min(6, this.gopCache_.length); // Clear nalUnits
  41217. nalUnits = [];
  41218. this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
  41219. this.trigger('timelineStartInfo', track.timelineStartInfo);
  41220. moof = mp4Generator.moof(sequenceNumber, [track]); // it would be great to allocate this array up front instead of
  41221. // throwing away hundreds of media segment fragments
  41222. boxes = new Uint8Array(moof.byteLength + mdat.byteLength); // Bump the sequence number for next time
  41223. sequenceNumber++;
  41224. boxes.set(moof);
  41225. boxes.set(mdat, moof.byteLength);
  41226. this.trigger('data', {
  41227. track: track,
  41228. boxes: boxes
  41229. });
  41230. this.resetStream_(); // Continue with the flush process now
  41231. this.trigger('done', 'VideoSegmentStream');
  41232. };
  41233. this.reset = function () {
  41234. this.resetStream_();
  41235. nalUnits = [];
  41236. this.gopCache_.length = 0;
  41237. gopsToAlignWith.length = 0;
  41238. this.trigger('reset');
  41239. };
  41240. this.resetStream_ = function () {
  41241. trackDecodeInfo.clearDtsInfo(track); // reset config and pps because they may differ across segments
  41242. // for instance, when we are rendition switching
  41243. config = undefined;
  41244. pps = undefined;
  41245. }; // Search for a candidate Gop for gop-fusion from the gop cache and
  41246. // return it or return null if no good candidate was found
  41247. this.getGopForFusion_ = function (nalUnit) {
  41248. var halfSecond = 45000,
  41249. // Half-a-second in a 90khz clock
  41250. allowableOverlap = 10000,
  41251. // About 3 frames @ 30fps
  41252. nearestDistance = Infinity,
  41253. dtsDistance,
  41254. nearestGopObj,
  41255. currentGop,
  41256. currentGopObj,
  41257. i; // Search for the GOP nearest to the beginning of this nal unit
  41258. for (i = 0; i < this.gopCache_.length; i++) {
  41259. currentGopObj = this.gopCache_[i];
  41260. currentGop = currentGopObj.gop; // Reject Gops with different SPS or PPS
  41261. if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) || !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
  41262. continue;
  41263. } // Reject Gops that would require a negative baseMediaDecodeTime
  41264. if (currentGop.dts < track.timelineStartInfo.dts) {
  41265. continue;
  41266. } // The distance between the end of the gop and the start of the nalUnit
  41267. dtsDistance = nalUnit.dts - currentGop.dts - currentGop.duration; // Only consider GOPS that start before the nal unit and end within
  41268. // a half-second of the nal unit
  41269. if (dtsDistance >= -allowableOverlap && dtsDistance <= halfSecond) {
  41270. // Always use the closest GOP we found if there is more than
  41271. // one candidate
  41272. if (!nearestGopObj || nearestDistance > dtsDistance) {
  41273. nearestGopObj = currentGopObj;
  41274. nearestDistance = dtsDistance;
  41275. }
  41276. }
  41277. }
  41278. if (nearestGopObj) {
  41279. return nearestGopObj.gop;
  41280. }
  41281. return null;
  41282. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  41283. // of gopsToAlignWith starting from the START of the list
  41284. this.alignGopsAtStart_ = function (gops) {
  41285. var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
  41286. byteLength = gops.byteLength;
  41287. nalCount = gops.nalCount;
  41288. duration = gops.duration;
  41289. alignIndex = gopIndex = 0;
  41290. while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
  41291. align = gopsToAlignWith[alignIndex];
  41292. gop = gops[gopIndex];
  41293. if (align.pts === gop.pts) {
  41294. break;
  41295. }
  41296. if (gop.pts > align.pts) {
  41297. // this current gop starts after the current gop we want to align on, so increment
  41298. // align index
  41299. alignIndex++;
  41300. continue;
  41301. } // current gop starts before the current gop we want to align on. so increment gop
  41302. // index
  41303. gopIndex++;
  41304. byteLength -= gop.byteLength;
  41305. nalCount -= gop.nalCount;
  41306. duration -= gop.duration;
  41307. }
  41308. if (gopIndex === 0) {
  41309. // no gops to trim
  41310. return gops;
  41311. }
  41312. if (gopIndex === gops.length) {
  41313. // all gops trimmed, skip appending all gops
  41314. return null;
  41315. }
  41316. alignedGops = gops.slice(gopIndex);
  41317. alignedGops.byteLength = byteLength;
  41318. alignedGops.duration = duration;
  41319. alignedGops.nalCount = nalCount;
  41320. alignedGops.pts = alignedGops[0].pts;
  41321. alignedGops.dts = alignedGops[0].dts;
  41322. return alignedGops;
  41323. }; // trim gop list to the first gop found that has a matching pts with a gop in the list
  41324. // of gopsToAlignWith starting from the END of the list
  41325. this.alignGopsAtEnd_ = function (gops) {
  41326. var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
  41327. alignIndex = gopsToAlignWith.length - 1;
  41328. gopIndex = gops.length - 1;
  41329. alignEndIndex = null;
  41330. matchFound = false;
  41331. while (alignIndex >= 0 && gopIndex >= 0) {
  41332. align = gopsToAlignWith[alignIndex];
  41333. gop = gops[gopIndex];
  41334. if (align.pts === gop.pts) {
  41335. matchFound = true;
  41336. break;
  41337. }
  41338. if (align.pts > gop.pts) {
  41339. alignIndex--;
  41340. continue;
  41341. }
  41342. if (alignIndex === gopsToAlignWith.length - 1) {
  41343. // gop.pts is greater than the last alignment candidate. If no match is found
  41344. // by the end of this loop, we still want to append gops that come after this
  41345. // point
  41346. alignEndIndex = gopIndex;
  41347. }
  41348. gopIndex--;
  41349. }
  41350. if (!matchFound && alignEndIndex === null) {
  41351. return null;
  41352. }
  41353. var trimIndex;
  41354. if (matchFound) {
  41355. trimIndex = gopIndex;
  41356. } else {
  41357. trimIndex = alignEndIndex;
  41358. }
  41359. if (trimIndex === 0) {
  41360. return gops;
  41361. }
  41362. var alignedGops = gops.slice(trimIndex);
  41363. var metadata = alignedGops.reduce(function (total, gop) {
  41364. total.byteLength += gop.byteLength;
  41365. total.duration += gop.duration;
  41366. total.nalCount += gop.nalCount;
  41367. return total;
  41368. }, {
  41369. byteLength: 0,
  41370. duration: 0,
  41371. nalCount: 0
  41372. });
  41373. alignedGops.byteLength = metadata.byteLength;
  41374. alignedGops.duration = metadata.duration;
  41375. alignedGops.nalCount = metadata.nalCount;
  41376. alignedGops.pts = alignedGops[0].pts;
  41377. alignedGops.dts = alignedGops[0].dts;
  41378. return alignedGops;
  41379. };
  41380. this.alignGopsWith = function (newGopsToAlignWith) {
  41381. gopsToAlignWith = newGopsToAlignWith;
  41382. };
  41383. };
  41384. _VideoSegmentStream.prototype = new stream();
  41385. /**
  41386. * A Stream that can combine multiple streams (ie. audio & video)
  41387. * into a single output segment for MSE. Also supports audio-only
  41388. * and video-only streams.
  41389. * @param options {object} transmuxer options object
  41390. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  41391. * in the source; false to adjust the first segment to start at media timeline start.
  41392. */
  41393. _CoalesceStream = function CoalesceStream(options, metadataStream) {
  41394. // Number of Tracks per output segment
  41395. // If greater than 1, we combine multiple
  41396. // tracks into a single segment
  41397. this.numberOfTracks = 0;
  41398. this.metadataStream = metadataStream;
  41399. options = options || {};
  41400. if (typeof options.remux !== 'undefined') {
  41401. this.remuxTracks = !!options.remux;
  41402. } else {
  41403. this.remuxTracks = true;
  41404. }
  41405. if (typeof options.keepOriginalTimestamps === 'boolean') {
  41406. this.keepOriginalTimestamps = options.keepOriginalTimestamps;
  41407. } else {
  41408. this.keepOriginalTimestamps = false;
  41409. }
  41410. this.pendingTracks = [];
  41411. this.videoTrack = null;
  41412. this.pendingBoxes = [];
  41413. this.pendingCaptions = [];
  41414. this.pendingMetadata = [];
  41415. this.pendingBytes = 0;
  41416. this.emittedTracks = 0;
  41417. _CoalesceStream.prototype.init.call(this); // Take output from multiple
  41418. this.push = function (output) {
  41419. // buffer incoming captions until the associated video segment
  41420. // finishes
  41421. if (output.text) {
  41422. return this.pendingCaptions.push(output);
  41423. } // buffer incoming id3 tags until the final flush
  41424. if (output.frames) {
  41425. return this.pendingMetadata.push(output);
  41426. } // Add this track to the list of pending tracks and store
  41427. // important information required for the construction of
  41428. // the final segment
  41429. this.pendingTracks.push(output.track);
  41430. this.pendingBytes += output.boxes.byteLength; // TODO: is there an issue for this against chrome?
  41431. // We unshift audio and push video because
  41432. // as of Chrome 75 when switching from
  41433. // one init segment to another if the video
  41434. // mdat does not appear after the audio mdat
  41435. // only audio will play for the duration of our transmux.
  41436. if (output.track.type === 'video') {
  41437. this.videoTrack = output.track;
  41438. this.pendingBoxes.push(output.boxes);
  41439. }
  41440. if (output.track.type === 'audio') {
  41441. this.audioTrack = output.track;
  41442. this.pendingBoxes.unshift(output.boxes);
  41443. }
  41444. };
  41445. };
  41446. _CoalesceStream.prototype = new stream();
  41447. _CoalesceStream.prototype.flush = function (flushSource) {
  41448. var offset = 0,
  41449. event = {
  41450. captions: [],
  41451. captionStreams: {},
  41452. metadata: [],
  41453. info: {}
  41454. },
  41455. caption,
  41456. id3,
  41457. initSegment,
  41458. timelineStartPts = 0,
  41459. i;
  41460. if (this.pendingTracks.length < this.numberOfTracks) {
  41461. if (flushSource !== 'VideoSegmentStream' && flushSource !== 'AudioSegmentStream') {
  41462. // Return because we haven't received a flush from a data-generating
  41463. // portion of the segment (meaning that we have only recieved meta-data
  41464. // or captions.)
  41465. return;
  41466. } else if (this.remuxTracks) {
  41467. // Return until we have enough tracks from the pipeline to remux (if we
  41468. // are remuxing audio and video into a single MP4)
  41469. return;
  41470. } else if (this.pendingTracks.length === 0) {
  41471. // In the case where we receive a flush without any data having been
  41472. // received we consider it an emitted track for the purposes of coalescing
  41473. // `done` events.
  41474. // We do this for the case where there is an audio and video track in the
  41475. // segment but no audio data. (seen in several playlists with alternate
  41476. // audio tracks and no audio present in the main TS segments.)
  41477. this.emittedTracks++;
  41478. if (this.emittedTracks >= this.numberOfTracks) {
  41479. this.trigger('done');
  41480. this.emittedTracks = 0;
  41481. }
  41482. return;
  41483. }
  41484. }
  41485. if (this.videoTrack) {
  41486. timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  41487. videoProperties.forEach(function (prop) {
  41488. event.info[prop] = this.videoTrack[prop];
  41489. }, this);
  41490. } else if (this.audioTrack) {
  41491. timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  41492. audioProperties.forEach(function (prop) {
  41493. event.info[prop] = this.audioTrack[prop];
  41494. }, this);
  41495. }
  41496. if (this.videoTrack || this.audioTrack) {
  41497. if (this.pendingTracks.length === 1) {
  41498. event.type = this.pendingTracks[0].type;
  41499. } else {
  41500. event.type = 'combined';
  41501. }
  41502. this.emittedTracks += this.pendingTracks.length;
  41503. initSegment = mp4Generator.initSegment(this.pendingTracks); // Create a new typed array to hold the init segment
  41504. event.initSegment = new Uint8Array(initSegment.byteLength); // Create an init segment containing a moov
  41505. // and track definitions
  41506. event.initSegment.set(initSegment); // Create a new typed array to hold the moof+mdats
  41507. event.data = new Uint8Array(this.pendingBytes); // Append each moof+mdat (one per track) together
  41508. for (i = 0; i < this.pendingBoxes.length; i++) {
  41509. event.data.set(this.pendingBoxes[i], offset);
  41510. offset += this.pendingBoxes[i].byteLength;
  41511. } // Translate caption PTS times into second offsets to match the
  41512. // video timeline for the segment, and add track info
  41513. for (i = 0; i < this.pendingCaptions.length; i++) {
  41514. caption = this.pendingCaptions[i];
  41515. caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
  41516. caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
  41517. event.captionStreams[caption.stream] = true;
  41518. event.captions.push(caption);
  41519. } // Translate ID3 frame PTS times into second offsets to match the
  41520. // video timeline for the segment
  41521. for (i = 0; i < this.pendingMetadata.length; i++) {
  41522. id3 = this.pendingMetadata[i];
  41523. id3.cueTime = clock.metadataTsToSeconds(id3.pts, timelineStartPts, this.keepOriginalTimestamps);
  41524. event.metadata.push(id3);
  41525. } // We add this to every single emitted segment even though we only need
  41526. // it for the first
  41527. event.metadata.dispatchType = this.metadataStream.dispatchType; // Reset stream state
  41528. this.pendingTracks.length = 0;
  41529. this.videoTrack = null;
  41530. this.pendingBoxes.length = 0;
  41531. this.pendingCaptions.length = 0;
  41532. this.pendingBytes = 0;
  41533. this.pendingMetadata.length = 0; // Emit the built segment
  41534. // We include captions and ID3 tags for backwards compatibility,
  41535. // ideally we should send only video and audio in the data event
  41536. this.trigger('data', event); // Emit each caption to the outside world
  41537. // Ideally, this would happen immediately on parsing captions,
  41538. // but we need to ensure that video data is sent back first
  41539. // so that caption timing can be adjusted to match video timing
  41540. for (i = 0; i < event.captions.length; i++) {
  41541. caption = event.captions[i];
  41542. this.trigger('caption', caption);
  41543. } // Emit each id3 tag to the outside world
  41544. // Ideally, this would happen immediately on parsing the tag,
  41545. // but we need to ensure that video data is sent back first
  41546. // so that ID3 frame timing can be adjusted to match video timing
  41547. for (i = 0; i < event.metadata.length; i++) {
  41548. id3 = event.metadata[i];
  41549. this.trigger('id3Frame', id3);
  41550. }
  41551. } // Only emit `done` if all tracks have been flushed and emitted
  41552. if (this.emittedTracks >= this.numberOfTracks) {
  41553. this.trigger('done');
  41554. this.emittedTracks = 0;
  41555. }
  41556. };
  41557. _CoalesceStream.prototype.setRemux = function (val) {
  41558. this.remuxTracks = val;
  41559. };
  41560. /**
  41561. * A Stream that expects MP2T binary data as input and produces
  41562. * corresponding media segments, suitable for use with Media Source
  41563. * Extension (MSE) implementations that support the ISO BMFF byte
  41564. * stream format, like Chrome.
  41565. */
  41566. _Transmuxer = function Transmuxer(options) {
  41567. var self = this,
  41568. hasFlushed = true,
  41569. videoTrack,
  41570. audioTrack;
  41571. _Transmuxer.prototype.init.call(this);
  41572. options = options || {};
  41573. this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
  41574. this.transmuxPipeline_ = {};
  41575. this.setupAacPipeline = function () {
  41576. var pipeline = {};
  41577. this.transmuxPipeline_ = pipeline;
  41578. pipeline.type = 'aac';
  41579. pipeline.metadataStream = new m2ts_1.MetadataStream(); // set up the parsing pipeline
  41580. pipeline.aacStream = new aac();
  41581. pipeline.audioTimestampRolloverStream = new m2ts_1.TimestampRolloverStream('audio');
  41582. pipeline.timedMetadataTimestampRolloverStream = new m2ts_1.TimestampRolloverStream('timed-metadata');
  41583. pipeline.adtsStream = new adts();
  41584. pipeline.coalesceStream = new _CoalesceStream(options, pipeline.metadataStream);
  41585. pipeline.headOfPipeline = pipeline.aacStream;
  41586. pipeline.aacStream.pipe(pipeline.audioTimestampRolloverStream).pipe(pipeline.adtsStream);
  41587. pipeline.aacStream.pipe(pipeline.timedMetadataTimestampRolloverStream).pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream);
  41588. pipeline.metadataStream.on('timestamp', function (frame) {
  41589. pipeline.aacStream.setTimestamp(frame.timeStamp);
  41590. });
  41591. pipeline.aacStream.on('data', function (data) {
  41592. if (data.type !== 'timed-metadata' && data.type !== 'audio' || pipeline.audioSegmentStream) {
  41593. return;
  41594. }
  41595. audioTrack = audioTrack || {
  41596. timelineStartInfo: {
  41597. baseMediaDecodeTime: self.baseMediaDecodeTime
  41598. },
  41599. codec: 'adts',
  41600. type: 'audio'
  41601. }; // hook up the audio segment stream to the first track with aac data
  41602. pipeline.coalesceStream.numberOfTracks++;
  41603. pipeline.audioSegmentStream = new _AudioSegmentStream(audioTrack, options);
  41604. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  41605. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo')); // Set up the final part of the audio pipeline
  41606. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream); // emit pmt info
  41607. self.trigger('trackinfo', {
  41608. hasAudio: !!audioTrack,
  41609. hasVideo: !!videoTrack
  41610. });
  41611. }); // Re-emit any data coming from the coalesce stream to the outside world
  41612. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data')); // Let the consumer know we have finished flushing the entire pipeline
  41613. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  41614. addPipelineLogRetriggers(this, pipeline);
  41615. };
  41616. this.setupTsPipeline = function () {
  41617. var pipeline = {};
  41618. this.transmuxPipeline_ = pipeline;
  41619. pipeline.type = 'ts';
  41620. pipeline.metadataStream = new m2ts_1.MetadataStream(); // set up the parsing pipeline
  41621. pipeline.packetStream = new m2ts_1.TransportPacketStream();
  41622. pipeline.parseStream = new m2ts_1.TransportParseStream();
  41623. pipeline.elementaryStream = new m2ts_1.ElementaryStream();
  41624. pipeline.timestampRolloverStream = new m2ts_1.TimestampRolloverStream();
  41625. pipeline.adtsStream = new adts();
  41626. pipeline.h264Stream = new H264Stream();
  41627. pipeline.captionStream = new m2ts_1.CaptionStream(options);
  41628. pipeline.coalesceStream = new _CoalesceStream(options, pipeline.metadataStream);
  41629. pipeline.headOfPipeline = pipeline.packetStream; // disassemble MPEG2-TS packets into elementary streams
  41630. pipeline.packetStream.pipe(pipeline.parseStream).pipe(pipeline.elementaryStream).pipe(pipeline.timestampRolloverStream); // !!THIS ORDER IS IMPORTANT!!
  41631. // demux the streams
  41632. pipeline.timestampRolloverStream.pipe(pipeline.h264Stream);
  41633. pipeline.timestampRolloverStream.pipe(pipeline.adtsStream);
  41634. pipeline.timestampRolloverStream.pipe(pipeline.metadataStream).pipe(pipeline.coalesceStream); // Hook up CEA-608/708 caption stream
  41635. pipeline.h264Stream.pipe(pipeline.captionStream).pipe(pipeline.coalesceStream);
  41636. pipeline.elementaryStream.on('data', function (data) {
  41637. var i;
  41638. if (data.type === 'metadata') {
  41639. i = data.tracks.length; // scan the tracks listed in the metadata
  41640. while (i--) {
  41641. if (!videoTrack && data.tracks[i].type === 'video') {
  41642. videoTrack = data.tracks[i];
  41643. videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  41644. } else if (!audioTrack && data.tracks[i].type === 'audio') {
  41645. audioTrack = data.tracks[i];
  41646. audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  41647. }
  41648. } // hook up the video segment stream to the first track with h264 data
  41649. if (videoTrack && !pipeline.videoSegmentStream) {
  41650. pipeline.coalesceStream.numberOfTracks++;
  41651. pipeline.videoSegmentStream = new _VideoSegmentStream(videoTrack, options);
  41652. pipeline.videoSegmentStream.on('log', self.getLogTrigger_('videoSegmentStream'));
  41653. pipeline.videoSegmentStream.on('timelineStartInfo', function (timelineStartInfo) {
  41654. // When video emits timelineStartInfo data after a flush, we forward that
  41655. // info to the AudioSegmentStream, if it exists, because video timeline
  41656. // data takes precedence. Do not do this if keepOriginalTimestamps is set,
  41657. // because this is a particularly subtle form of timestamp alteration.
  41658. if (audioTrack && !options.keepOriginalTimestamps) {
  41659. audioTrack.timelineStartInfo = timelineStartInfo; // On the first segment we trim AAC frames that exist before the
  41660. // very earliest DTS we have seen in video because Chrome will
  41661. // interpret any video track with a baseMediaDecodeTime that is
  41662. // non-zero as a gap.
  41663. pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);
  41664. }
  41665. });
  41666. pipeline.videoSegmentStream.on('processedGopsInfo', self.trigger.bind(self, 'gopInfo'));
  41667. pipeline.videoSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'videoSegmentTimingInfo'));
  41668. pipeline.videoSegmentStream.on('baseMediaDecodeTime', function (baseMediaDecodeTime) {
  41669. if (audioTrack) {
  41670. pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
  41671. }
  41672. });
  41673. pipeline.videoSegmentStream.on('timingInfo', self.trigger.bind(self, 'videoTimingInfo')); // Set up the final part of the video pipeline
  41674. pipeline.h264Stream.pipe(pipeline.videoSegmentStream).pipe(pipeline.coalesceStream);
  41675. }
  41676. if (audioTrack && !pipeline.audioSegmentStream) {
  41677. // hook up the audio segment stream to the first track with aac data
  41678. pipeline.coalesceStream.numberOfTracks++;
  41679. pipeline.audioSegmentStream = new _AudioSegmentStream(audioTrack, options);
  41680. pipeline.audioSegmentStream.on('log', self.getLogTrigger_('audioSegmentStream'));
  41681. pipeline.audioSegmentStream.on('timingInfo', self.trigger.bind(self, 'audioTimingInfo'));
  41682. pipeline.audioSegmentStream.on('segmentTimingInfo', self.trigger.bind(self, 'audioSegmentTimingInfo')); // Set up the final part of the audio pipeline
  41683. pipeline.adtsStream.pipe(pipeline.audioSegmentStream).pipe(pipeline.coalesceStream);
  41684. } // emit pmt info
  41685. self.trigger('trackinfo', {
  41686. hasAudio: !!audioTrack,
  41687. hasVideo: !!videoTrack
  41688. });
  41689. }
  41690. }); // Re-emit any data coming from the coalesce stream to the outside world
  41691. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  41692. pipeline.coalesceStream.on('id3Frame', function (id3Frame) {
  41693. id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
  41694. self.trigger('id3Frame', id3Frame);
  41695. });
  41696. pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption')); // Let the consumer know we have finished flushing the entire pipeline
  41697. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  41698. addPipelineLogRetriggers(this, pipeline);
  41699. }; // hook up the segment streams once track metadata is delivered
  41700. this.setBaseMediaDecodeTime = function (baseMediaDecodeTime) {
  41701. var pipeline = this.transmuxPipeline_;
  41702. if (!options.keepOriginalTimestamps) {
  41703. this.baseMediaDecodeTime = baseMediaDecodeTime;
  41704. }
  41705. if (audioTrack) {
  41706. audioTrack.timelineStartInfo.dts = undefined;
  41707. audioTrack.timelineStartInfo.pts = undefined;
  41708. trackDecodeInfo.clearDtsInfo(audioTrack);
  41709. if (pipeline.audioTimestampRolloverStream) {
  41710. pipeline.audioTimestampRolloverStream.discontinuity();
  41711. }
  41712. }
  41713. if (videoTrack) {
  41714. if (pipeline.videoSegmentStream) {
  41715. pipeline.videoSegmentStream.gopCache_ = [];
  41716. }
  41717. videoTrack.timelineStartInfo.dts = undefined;
  41718. videoTrack.timelineStartInfo.pts = undefined;
  41719. trackDecodeInfo.clearDtsInfo(videoTrack);
  41720. pipeline.captionStream.reset();
  41721. }
  41722. if (pipeline.timestampRolloverStream) {
  41723. pipeline.timestampRolloverStream.discontinuity();
  41724. }
  41725. };
  41726. this.setAudioAppendStart = function (timestamp) {
  41727. if (audioTrack) {
  41728. this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
  41729. }
  41730. };
  41731. this.setRemux = function (val) {
  41732. var pipeline = this.transmuxPipeline_;
  41733. options.remux = val;
  41734. if (pipeline && pipeline.coalesceStream) {
  41735. pipeline.coalesceStream.setRemux(val);
  41736. }
  41737. };
  41738. this.alignGopsWith = function (gopsToAlignWith) {
  41739. if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
  41740. this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
  41741. }
  41742. };
  41743. this.getLogTrigger_ = function (key) {
  41744. var self = this;
  41745. return function (event) {
  41746. event.stream = key;
  41747. self.trigger('log', event);
  41748. };
  41749. }; // feed incoming data to the front of the parsing pipeline
  41750. this.push = function (data) {
  41751. if (hasFlushed) {
  41752. var isAac = isLikelyAacData(data);
  41753. if (isAac && this.transmuxPipeline_.type !== 'aac') {
  41754. this.setupAacPipeline();
  41755. } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
  41756. this.setupTsPipeline();
  41757. }
  41758. hasFlushed = false;
  41759. }
  41760. this.transmuxPipeline_.headOfPipeline.push(data);
  41761. }; // flush any buffered data
  41762. this.flush = function () {
  41763. hasFlushed = true; // Start at the top of the pipeline and flush all pending work
  41764. this.transmuxPipeline_.headOfPipeline.flush();
  41765. };
  41766. this.endTimeline = function () {
  41767. this.transmuxPipeline_.headOfPipeline.endTimeline();
  41768. };
  41769. this.reset = function () {
  41770. if (this.transmuxPipeline_.headOfPipeline) {
  41771. this.transmuxPipeline_.headOfPipeline.reset();
  41772. }
  41773. }; // Caption data has to be reset when seeking outside buffered range
  41774. this.resetCaptions = function () {
  41775. if (this.transmuxPipeline_.captionStream) {
  41776. this.transmuxPipeline_.captionStream.reset();
  41777. }
  41778. };
  41779. };
  41780. _Transmuxer.prototype = new stream();
  41781. var transmuxer = {
  41782. Transmuxer: _Transmuxer,
  41783. VideoSegmentStream: _VideoSegmentStream,
  41784. AudioSegmentStream: _AudioSegmentStream,
  41785. AUDIO_PROPERTIES: audioProperties,
  41786. VIDEO_PROPERTIES: videoProperties,
  41787. // exported for testing
  41788. generateSegmentTimingInfo: generateSegmentTimingInfo
  41789. };
  41790. /**
  41791. * mux.js
  41792. *
  41793. * Copyright (c) Brightcove
  41794. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  41795. */
  41796. var toUnsigned$3 = function toUnsigned(value) {
  41797. return value >>> 0;
  41798. };
  41799. var toHexString$1 = function toHexString(value) {
  41800. return ('00' + value.toString(16)).slice(-2);
  41801. };
  41802. var bin = {
  41803. toUnsigned: toUnsigned$3,
  41804. toHexString: toHexString$1
  41805. };
  41806. var parseType$1 = function parseType(buffer) {
  41807. var result = '';
  41808. result += String.fromCharCode(buffer[0]);
  41809. result += String.fromCharCode(buffer[1]);
  41810. result += String.fromCharCode(buffer[2]);
  41811. result += String.fromCharCode(buffer[3]);
  41812. return result;
  41813. };
  41814. var parseType_1 = parseType$1;
  41815. var toUnsigned$2 = bin.toUnsigned;
  41816. var findBox = function findBox(data, path) {
  41817. var results = [],
  41818. i,
  41819. size,
  41820. type,
  41821. end,
  41822. subresults;
  41823. if (!path.length) {
  41824. // short-circuit the search for empty paths
  41825. return null;
  41826. }
  41827. for (i = 0; i < data.byteLength;) {
  41828. size = toUnsigned$2(data[i] << 24 | data[i + 1] << 16 | data[i + 2] << 8 | data[i + 3]);
  41829. type = parseType_1(data.subarray(i + 4, i + 8));
  41830. end = size > 1 ? i + size : data.byteLength;
  41831. if (type === path[0]) {
  41832. if (path.length === 1) {
  41833. // this is the end of the path and we've found the box we were
  41834. // looking for
  41835. results.push(data.subarray(i + 8, end));
  41836. } else {
  41837. // recursively search for the next box along the path
  41838. subresults = findBox(data.subarray(i + 8, end), path.slice(1));
  41839. if (subresults.length) {
  41840. results = results.concat(subresults);
  41841. }
  41842. }
  41843. }
  41844. i = end;
  41845. } // we've finished searching all of data
  41846. return results;
  41847. };
  41848. var findBox_1 = findBox;
  41849. var toUnsigned$1 = bin.toUnsigned;
  41850. var getUint64$1 = numbers.getUint64;
  41851. var tfdt = function tfdt(data) {
  41852. var result = {
  41853. version: data[0],
  41854. flags: new Uint8Array(data.subarray(1, 4))
  41855. };
  41856. if (result.version === 1) {
  41857. result.baseMediaDecodeTime = getUint64$1(data.subarray(4));
  41858. } else {
  41859. result.baseMediaDecodeTime = toUnsigned$1(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]);
  41860. }
  41861. return result;
  41862. };
  41863. var parseTfdt = tfdt;
  41864. var parseSampleFlags = function parseSampleFlags(flags) {
  41865. return {
  41866. isLeading: (flags[0] & 0x0c) >>> 2,
  41867. dependsOn: flags[0] & 0x03,
  41868. isDependedOn: (flags[1] & 0xc0) >>> 6,
  41869. hasRedundancy: (flags[1] & 0x30) >>> 4,
  41870. paddingValue: (flags[1] & 0x0e) >>> 1,
  41871. isNonSyncSample: flags[1] & 0x01,
  41872. degradationPriority: flags[2] << 8 | flags[3]
  41873. };
  41874. };
  41875. var parseSampleFlags_1 = parseSampleFlags;
  41876. var trun = function trun(data) {
  41877. var result = {
  41878. version: data[0],
  41879. flags: new Uint8Array(data.subarray(1, 4)),
  41880. samples: []
  41881. },
  41882. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  41883. // Flag interpretation
  41884. dataOffsetPresent = result.flags[2] & 0x01,
  41885. // compare with 2nd byte of 0x1
  41886. firstSampleFlagsPresent = result.flags[2] & 0x04,
  41887. // compare with 2nd byte of 0x4
  41888. sampleDurationPresent = result.flags[1] & 0x01,
  41889. // compare with 2nd byte of 0x100
  41890. sampleSizePresent = result.flags[1] & 0x02,
  41891. // compare with 2nd byte of 0x200
  41892. sampleFlagsPresent = result.flags[1] & 0x04,
  41893. // compare with 2nd byte of 0x400
  41894. sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08,
  41895. // compare with 2nd byte of 0x800
  41896. sampleCount = view.getUint32(4),
  41897. offset = 8,
  41898. sample;
  41899. if (dataOffsetPresent) {
  41900. // 32 bit signed integer
  41901. result.dataOffset = view.getInt32(offset);
  41902. offset += 4;
  41903. } // Overrides the flags for the first sample only. The order of
  41904. // optional values will be: duration, size, compositionTimeOffset
  41905. if (firstSampleFlagsPresent && sampleCount) {
  41906. sample = {
  41907. flags: parseSampleFlags_1(data.subarray(offset, offset + 4))
  41908. };
  41909. offset += 4;
  41910. if (sampleDurationPresent) {
  41911. sample.duration = view.getUint32(offset);
  41912. offset += 4;
  41913. }
  41914. if (sampleSizePresent) {
  41915. sample.size = view.getUint32(offset);
  41916. offset += 4;
  41917. }
  41918. if (sampleCompositionTimeOffsetPresent) {
  41919. if (result.version === 1) {
  41920. sample.compositionTimeOffset = view.getInt32(offset);
  41921. } else {
  41922. sample.compositionTimeOffset = view.getUint32(offset);
  41923. }
  41924. offset += 4;
  41925. }
  41926. result.samples.push(sample);
  41927. sampleCount--;
  41928. }
  41929. while (sampleCount--) {
  41930. sample = {};
  41931. if (sampleDurationPresent) {
  41932. sample.duration = view.getUint32(offset);
  41933. offset += 4;
  41934. }
  41935. if (sampleSizePresent) {
  41936. sample.size = view.getUint32(offset);
  41937. offset += 4;
  41938. }
  41939. if (sampleFlagsPresent) {
  41940. sample.flags = parseSampleFlags_1(data.subarray(offset, offset + 4));
  41941. offset += 4;
  41942. }
  41943. if (sampleCompositionTimeOffsetPresent) {
  41944. if (result.version === 1) {
  41945. sample.compositionTimeOffset = view.getInt32(offset);
  41946. } else {
  41947. sample.compositionTimeOffset = view.getUint32(offset);
  41948. }
  41949. offset += 4;
  41950. }
  41951. result.samples.push(sample);
  41952. }
  41953. return result;
  41954. };
  41955. var parseTrun = trun;
  41956. var tfhd = function tfhd(data) {
  41957. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  41958. result = {
  41959. version: data[0],
  41960. flags: new Uint8Array(data.subarray(1, 4)),
  41961. trackId: view.getUint32(4)
  41962. },
  41963. baseDataOffsetPresent = result.flags[2] & 0x01,
  41964. sampleDescriptionIndexPresent = result.flags[2] & 0x02,
  41965. defaultSampleDurationPresent = result.flags[2] & 0x08,
  41966. defaultSampleSizePresent = result.flags[2] & 0x10,
  41967. defaultSampleFlagsPresent = result.flags[2] & 0x20,
  41968. durationIsEmpty = result.flags[0] & 0x010000,
  41969. defaultBaseIsMoof = result.flags[0] & 0x020000,
  41970. i;
  41971. i = 8;
  41972. if (baseDataOffsetPresent) {
  41973. i += 4; // truncate top 4 bytes
  41974. // FIXME: should we read the full 64 bits?
  41975. result.baseDataOffset = view.getUint32(12);
  41976. i += 4;
  41977. }
  41978. if (sampleDescriptionIndexPresent) {
  41979. result.sampleDescriptionIndex = view.getUint32(i);
  41980. i += 4;
  41981. }
  41982. if (defaultSampleDurationPresent) {
  41983. result.defaultSampleDuration = view.getUint32(i);
  41984. i += 4;
  41985. }
  41986. if (defaultSampleSizePresent) {
  41987. result.defaultSampleSize = view.getUint32(i);
  41988. i += 4;
  41989. }
  41990. if (defaultSampleFlagsPresent) {
  41991. result.defaultSampleFlags = view.getUint32(i);
  41992. }
  41993. if (durationIsEmpty) {
  41994. result.durationIsEmpty = true;
  41995. }
  41996. if (!baseDataOffsetPresent && defaultBaseIsMoof) {
  41997. result.baseDataOffsetIsMoof = true;
  41998. }
  41999. return result;
  42000. };
  42001. var parseTfhd = tfhd;
  42002. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  42003. var win;
  42004. if (typeof window !== "undefined") {
  42005. win = window;
  42006. } else if (typeof commonjsGlobal !== "undefined") {
  42007. win = commonjsGlobal;
  42008. } else if (typeof self !== "undefined") {
  42009. win = self;
  42010. } else {
  42011. win = {};
  42012. }
  42013. var window_1 = win;
  42014. var discardEmulationPreventionBytes = captionPacketParser.discardEmulationPreventionBytes;
  42015. var CaptionStream = captionStream.CaptionStream;
  42016. /**
  42017. * Maps an offset in the mdat to a sample based on the the size of the samples.
  42018. * Assumes that `parseSamples` has been called first.
  42019. *
  42020. * @param {Number} offset - The offset into the mdat
  42021. * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
  42022. * @return {?Object} The matching sample, or null if no match was found.
  42023. *
  42024. * @see ISO-BMFF-12/2015, Section 8.8.8
  42025. **/
  42026. var mapToSample = function mapToSample(offset, samples) {
  42027. var approximateOffset = offset;
  42028. for (var i = 0; i < samples.length; i++) {
  42029. var sample = samples[i];
  42030. if (approximateOffset < sample.size) {
  42031. return sample;
  42032. }
  42033. approximateOffset -= sample.size;
  42034. }
  42035. return null;
  42036. };
  42037. /**
  42038. * Finds SEI nal units contained in a Media Data Box.
  42039. * Assumes that `parseSamples` has been called first.
  42040. *
  42041. * @param {Uint8Array} avcStream - The bytes of the mdat
  42042. * @param {Object[]} samples - The samples parsed out by `parseSamples`
  42043. * @param {Number} trackId - The trackId of this video track
  42044. * @return {Object[]} seiNals - the parsed SEI NALUs found.
  42045. * The contents of the seiNal should match what is expected by
  42046. * CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
  42047. *
  42048. * @see ISO-BMFF-12/2015, Section 8.1.1
  42049. * @see Rec. ITU-T H.264, 7.3.2.3.1
  42050. **/
  42051. var findSeiNals = function findSeiNals(avcStream, samples, trackId) {
  42052. var avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
  42053. result = {
  42054. logs: [],
  42055. seiNals: []
  42056. },
  42057. seiNal,
  42058. i,
  42059. length,
  42060. lastMatchedSample;
  42061. for (i = 0; i + 4 < avcStream.length; i += length) {
  42062. length = avcView.getUint32(i);
  42063. i += 4; // Bail if this doesn't appear to be an H264 stream
  42064. if (length <= 0) {
  42065. continue;
  42066. }
  42067. switch (avcStream[i] & 0x1F) {
  42068. case 0x06:
  42069. var data = avcStream.subarray(i + 1, i + 1 + length);
  42070. var matchingSample = mapToSample(i, samples);
  42071. seiNal = {
  42072. nalUnitType: 'sei_rbsp',
  42073. size: length,
  42074. data: data,
  42075. escapedRBSP: discardEmulationPreventionBytes(data),
  42076. trackId: trackId
  42077. };
  42078. if (matchingSample) {
  42079. seiNal.pts = matchingSample.pts;
  42080. seiNal.dts = matchingSample.dts;
  42081. lastMatchedSample = matchingSample;
  42082. } else if (lastMatchedSample) {
  42083. // If a matching sample cannot be found, use the last
  42084. // sample's values as they should be as close as possible
  42085. seiNal.pts = lastMatchedSample.pts;
  42086. seiNal.dts = lastMatchedSample.dts;
  42087. } else {
  42088. result.logs.push({
  42089. level: 'warn',
  42090. message: 'We\'ve encountered a nal unit without data at ' + i + ' for trackId ' + trackId + '. See mux.js#223.'
  42091. });
  42092. break;
  42093. }
  42094. result.seiNals.push(seiNal);
  42095. break;
  42096. }
  42097. }
  42098. return result;
  42099. };
  42100. /**
  42101. * Parses sample information out of Track Run Boxes and calculates
  42102. * the absolute presentation and decode timestamps of each sample.
  42103. *
  42104. * @param {Array<Uint8Array>} truns - The Trun Run boxes to be parsed
  42105. * @param {Number|BigInt} baseMediaDecodeTime - base media decode time from tfdt
  42106. @see ISO-BMFF-12/2015, Section 8.8.12
  42107. * @param {Object} tfhd - The parsed Track Fragment Header
  42108. * @see inspect.parseTfhd
  42109. * @return {Object[]} the parsed samples
  42110. *
  42111. * @see ISO-BMFF-12/2015, Section 8.8.8
  42112. **/
  42113. var parseSamples = function parseSamples(truns, baseMediaDecodeTime, tfhd) {
  42114. var currentDts = baseMediaDecodeTime;
  42115. var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
  42116. var defaultSampleSize = tfhd.defaultSampleSize || 0;
  42117. var trackId = tfhd.trackId;
  42118. var allSamples = [];
  42119. truns.forEach(function (trun) {
  42120. // Note: We currently do not parse the sample table as well
  42121. // as the trun. It's possible some sources will require this.
  42122. // moov > trak > mdia > minf > stbl
  42123. var trackRun = parseTrun(trun);
  42124. var samples = trackRun.samples;
  42125. samples.forEach(function (sample) {
  42126. if (sample.duration === undefined) {
  42127. sample.duration = defaultSampleDuration;
  42128. }
  42129. if (sample.size === undefined) {
  42130. sample.size = defaultSampleSize;
  42131. }
  42132. sample.trackId = trackId;
  42133. sample.dts = currentDts;
  42134. if (sample.compositionTimeOffset === undefined) {
  42135. sample.compositionTimeOffset = 0;
  42136. }
  42137. if (typeof currentDts === 'bigint') {
  42138. sample.pts = currentDts + window_1.BigInt(sample.compositionTimeOffset);
  42139. currentDts += window_1.BigInt(sample.duration);
  42140. } else {
  42141. sample.pts = currentDts + sample.compositionTimeOffset;
  42142. currentDts += sample.duration;
  42143. }
  42144. });
  42145. allSamples = allSamples.concat(samples);
  42146. });
  42147. return allSamples;
  42148. };
  42149. /**
  42150. * Parses out caption nals from an FMP4 segment's video tracks.
  42151. *
  42152. * @param {Uint8Array} segment - The bytes of a single segment
  42153. * @param {Number} videoTrackId - The trackId of a video track in the segment
  42154. * @return {Object.<Number, Object[]>} A mapping of video trackId to
  42155. * a list of seiNals found in that track
  42156. **/
  42157. var parseCaptionNals = function parseCaptionNals(segment, videoTrackId) {
  42158. // To get the samples
  42159. var trafs = findBox_1(segment, ['moof', 'traf']); // To get SEI NAL units
  42160. var mdats = findBox_1(segment, ['mdat']);
  42161. var captionNals = {};
  42162. var mdatTrafPairs = []; // Pair up each traf with a mdat as moofs and mdats are in pairs
  42163. mdats.forEach(function (mdat, index) {
  42164. var matchingTraf = trafs[index];
  42165. mdatTrafPairs.push({
  42166. mdat: mdat,
  42167. traf: matchingTraf
  42168. });
  42169. });
  42170. mdatTrafPairs.forEach(function (pair) {
  42171. var mdat = pair.mdat;
  42172. var traf = pair.traf;
  42173. var tfhd = findBox_1(traf, ['tfhd']); // Exactly 1 tfhd per traf
  42174. var headerInfo = parseTfhd(tfhd[0]);
  42175. var trackId = headerInfo.trackId;
  42176. var tfdt = findBox_1(traf, ['tfdt']); // Either 0 or 1 tfdt per traf
  42177. var baseMediaDecodeTime = tfdt.length > 0 ? parseTfdt(tfdt[0]).baseMediaDecodeTime : 0;
  42178. var truns = findBox_1(traf, ['trun']);
  42179. var samples;
  42180. var result; // Only parse video data for the chosen video track
  42181. if (videoTrackId === trackId && truns.length > 0) {
  42182. samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);
  42183. result = findSeiNals(mdat, samples, trackId);
  42184. if (!captionNals[trackId]) {
  42185. captionNals[trackId] = {
  42186. seiNals: [],
  42187. logs: []
  42188. };
  42189. }
  42190. captionNals[trackId].seiNals = captionNals[trackId].seiNals.concat(result.seiNals);
  42191. captionNals[trackId].logs = captionNals[trackId].logs.concat(result.logs);
  42192. }
  42193. });
  42194. return captionNals;
  42195. };
  42196. /**
  42197. * Parses out inband captions from an MP4 container and returns
  42198. * caption objects that can be used by WebVTT and the TextTrack API.
  42199. * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
  42200. * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
  42201. * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
  42202. *
  42203. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  42204. * @param {Number} trackId - The id of the video track to parse
  42205. * @param {Number} timescale - The timescale for the video track from the init segment
  42206. *
  42207. * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
  42208. * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
  42209. * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
  42210. * @return {String} parsedCaptions[].text - The visible content of the caption
  42211. **/
  42212. var parseEmbeddedCaptions = function parseEmbeddedCaptions(segment, trackId, timescale) {
  42213. var captionNals; // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  42214. if (trackId === null) {
  42215. return null;
  42216. }
  42217. captionNals = parseCaptionNals(segment, trackId);
  42218. var trackNals = captionNals[trackId] || {};
  42219. return {
  42220. seiNals: trackNals.seiNals,
  42221. logs: trackNals.logs,
  42222. timescale: timescale
  42223. };
  42224. };
  42225. /**
  42226. * Converts SEI NALUs into captions that can be used by video.js
  42227. **/
  42228. var CaptionParser = function CaptionParser() {
  42229. var isInitialized = false;
  42230. var captionStream; // Stores segments seen before trackId and timescale are set
  42231. var segmentCache; // Stores video track ID of the track being parsed
  42232. var trackId; // Stores the timescale of the track being parsed
  42233. var timescale; // Stores captions parsed so far
  42234. var parsedCaptions; // Stores whether we are receiving partial data or not
  42235. var parsingPartial;
  42236. /**
  42237. * A method to indicate whether a CaptionParser has been initalized
  42238. * @returns {Boolean}
  42239. **/
  42240. this.isInitialized = function () {
  42241. return isInitialized;
  42242. };
  42243. /**
  42244. * Initializes the underlying CaptionStream, SEI NAL parsing
  42245. * and management, and caption collection
  42246. **/
  42247. this.init = function (options) {
  42248. captionStream = new CaptionStream();
  42249. isInitialized = true;
  42250. parsingPartial = options ? options.isPartial : false; // Collect dispatched captions
  42251. captionStream.on('data', function (event) {
  42252. // Convert to seconds in the source's timescale
  42253. event.startTime = event.startPts / timescale;
  42254. event.endTime = event.endPts / timescale;
  42255. parsedCaptions.captions.push(event);
  42256. parsedCaptions.captionStreams[event.stream] = true;
  42257. });
  42258. captionStream.on('log', function (log) {
  42259. parsedCaptions.logs.push(log);
  42260. });
  42261. };
  42262. /**
  42263. * Determines if a new video track will be selected
  42264. * or if the timescale changed
  42265. * @return {Boolean}
  42266. **/
  42267. this.isNewInit = function (videoTrackIds, timescales) {
  42268. if (videoTrackIds && videoTrackIds.length === 0 || timescales && typeof timescales === 'object' && Object.keys(timescales).length === 0) {
  42269. return false;
  42270. }
  42271. return trackId !== videoTrackIds[0] || timescale !== timescales[trackId];
  42272. };
  42273. /**
  42274. * Parses out SEI captions and interacts with underlying
  42275. * CaptionStream to return dispatched captions
  42276. *
  42277. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  42278. * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
  42279. * @param {Object.<Number, Number>} timescales - The timescales found in the init segment
  42280. * @see parseEmbeddedCaptions
  42281. * @see m2ts/caption-stream.js
  42282. **/
  42283. this.parse = function (segment, videoTrackIds, timescales) {
  42284. var parsedData;
  42285. if (!this.isInitialized()) {
  42286. return null; // This is not likely to be a video segment
  42287. } else if (!videoTrackIds || !timescales) {
  42288. return null;
  42289. } else if (this.isNewInit(videoTrackIds, timescales)) {
  42290. // Use the first video track only as there is no
  42291. // mechanism to switch to other video tracks
  42292. trackId = videoTrackIds[0];
  42293. timescale = timescales[trackId]; // If an init segment has not been seen yet, hold onto segment
  42294. // data until we have one.
  42295. // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  42296. } else if (trackId === null || !timescale) {
  42297. segmentCache.push(segment);
  42298. return null;
  42299. } // Now that a timescale and trackId is set, parse cached segments
  42300. while (segmentCache.length > 0) {
  42301. var cachedSegment = segmentCache.shift();
  42302. this.parse(cachedSegment, videoTrackIds, timescales);
  42303. }
  42304. parsedData = parseEmbeddedCaptions(segment, trackId, timescale);
  42305. if (parsedData && parsedData.logs) {
  42306. parsedCaptions.logs = parsedCaptions.logs.concat(parsedData.logs);
  42307. }
  42308. if (parsedData === null || !parsedData.seiNals) {
  42309. if (parsedCaptions.logs.length) {
  42310. return {
  42311. logs: parsedCaptions.logs,
  42312. captions: [],
  42313. captionStreams: []
  42314. };
  42315. }
  42316. return null;
  42317. }
  42318. this.pushNals(parsedData.seiNals); // Force the parsed captions to be dispatched
  42319. this.flushStream();
  42320. return parsedCaptions;
  42321. };
  42322. /**
  42323. * Pushes SEI NALUs onto CaptionStream
  42324. * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
  42325. * Assumes that `parseCaptionNals` has been called first
  42326. * @see m2ts/caption-stream.js
  42327. **/
  42328. this.pushNals = function (nals) {
  42329. if (!this.isInitialized() || !nals || nals.length === 0) {
  42330. return null;
  42331. }
  42332. nals.forEach(function (nal) {
  42333. captionStream.push(nal);
  42334. });
  42335. };
  42336. /**
  42337. * Flushes underlying CaptionStream to dispatch processed, displayable captions
  42338. * @see m2ts/caption-stream.js
  42339. **/
  42340. this.flushStream = function () {
  42341. if (!this.isInitialized()) {
  42342. return null;
  42343. }
  42344. if (!parsingPartial) {
  42345. captionStream.flush();
  42346. } else {
  42347. captionStream.partialFlush();
  42348. }
  42349. };
  42350. /**
  42351. * Reset caption buckets for new data
  42352. **/
  42353. this.clearParsedCaptions = function () {
  42354. parsedCaptions.captions = [];
  42355. parsedCaptions.captionStreams = {};
  42356. parsedCaptions.logs = [];
  42357. };
  42358. /**
  42359. * Resets underlying CaptionStream
  42360. * @see m2ts/caption-stream.js
  42361. **/
  42362. this.resetCaptionStream = function () {
  42363. if (!this.isInitialized()) {
  42364. return null;
  42365. }
  42366. captionStream.reset();
  42367. };
  42368. /**
  42369. * Convenience method to clear all captions flushed from the
  42370. * CaptionStream and still being parsed
  42371. * @see m2ts/caption-stream.js
  42372. **/
  42373. this.clearAllCaptions = function () {
  42374. this.clearParsedCaptions();
  42375. this.resetCaptionStream();
  42376. };
  42377. /**
  42378. * Reset caption parser
  42379. **/
  42380. this.reset = function () {
  42381. segmentCache = [];
  42382. trackId = null;
  42383. timescale = null;
  42384. if (!parsedCaptions) {
  42385. parsedCaptions = {
  42386. captions: [],
  42387. // CC1, CC2, CC3, CC4
  42388. captionStreams: {},
  42389. logs: []
  42390. };
  42391. } else {
  42392. this.clearParsedCaptions();
  42393. }
  42394. this.resetCaptionStream();
  42395. };
  42396. this.reset();
  42397. };
  42398. var captionParser = CaptionParser;
  42399. var toUnsigned = bin.toUnsigned;
  42400. var toHexString = bin.toHexString;
  42401. var getUint64 = numbers.getUint64;
  42402. var timescale, startTime, compositionStartTime, getVideoTrackIds, getTracks, getTimescaleFromMediaHeader;
  42403. /**
  42404. * Parses an MP4 initialization segment and extracts the timescale
  42405. * values for any declared tracks. Timescale values indicate the
  42406. * number of clock ticks per second to assume for time-based values
  42407. * elsewhere in the MP4.
  42408. *
  42409. * To determine the start time of an MP4, you need two pieces of
  42410. * information: the timescale unit and the earliest base media decode
  42411. * time. Multiple timescales can be specified within an MP4 but the
  42412. * base media decode time is always expressed in the timescale from
  42413. * the media header box for the track:
  42414. * ```
  42415. * moov > trak > mdia > mdhd.timescale
  42416. * ```
  42417. * @param init {Uint8Array} the bytes of the init segment
  42418. * @return {object} a hash of track ids to timescale values or null if
  42419. * the init segment is malformed.
  42420. */
  42421. timescale = function timescale(init) {
  42422. var result = {},
  42423. traks = findBox_1(init, ['moov', 'trak']); // mdhd timescale
  42424. return traks.reduce(function (result, trak) {
  42425. var tkhd, version, index, id, mdhd;
  42426. tkhd = findBox_1(trak, ['tkhd'])[0];
  42427. if (!tkhd) {
  42428. return null;
  42429. }
  42430. version = tkhd[0];
  42431. index = version === 0 ? 12 : 20;
  42432. id = toUnsigned(tkhd[index] << 24 | tkhd[index + 1] << 16 | tkhd[index + 2] << 8 | tkhd[index + 3]);
  42433. mdhd = findBox_1(trak, ['mdia', 'mdhd'])[0];
  42434. if (!mdhd) {
  42435. return null;
  42436. }
  42437. version = mdhd[0];
  42438. index = version === 0 ? 12 : 20;
  42439. result[id] = toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  42440. return result;
  42441. }, result);
  42442. };
  42443. /**
  42444. * Determine the base media decode start time, in seconds, for an MP4
  42445. * fragment. If multiple fragments are specified, the earliest time is
  42446. * returned.
  42447. *
  42448. * The base media decode time can be parsed from track fragment
  42449. * metadata:
  42450. * ```
  42451. * moof > traf > tfdt.baseMediaDecodeTime
  42452. * ```
  42453. * It requires the timescale value from the mdhd to interpret.
  42454. *
  42455. * @param timescale {object} a hash of track ids to timescale values.
  42456. * @return {number} the earliest base media decode start time for the
  42457. * fragment, in seconds
  42458. */
  42459. startTime = function startTime(timescale, fragment) {
  42460. var trafs; // we need info from two childrend of each track fragment box
  42461. trafs = findBox_1(fragment, ['moof', 'traf']); // determine the start times for each track
  42462. var lowestTime = trafs.reduce(function (acc, traf) {
  42463. var tfhd = findBox_1(traf, ['tfhd'])[0]; // get the track id from the tfhd
  42464. var id = toUnsigned(tfhd[4] << 24 | tfhd[5] << 16 | tfhd[6] << 8 | tfhd[7]); // assume a 90kHz clock if no timescale was specified
  42465. var scale = timescale[id] || 90e3; // get the base media decode time from the tfdt
  42466. var tfdt = findBox_1(traf, ['tfdt'])[0];
  42467. var dv = new DataView(tfdt.buffer, tfdt.byteOffset, tfdt.byteLength);
  42468. var baseTime; // version 1 is 64 bit
  42469. if (tfdt[0] === 1) {
  42470. baseTime = getUint64(tfdt.subarray(4, 12));
  42471. } else {
  42472. baseTime = dv.getUint32(4);
  42473. } // convert base time to seconds if it is a valid number.
  42474. var seconds;
  42475. if (typeof baseTime === 'bigint') {
  42476. seconds = baseTime / window_1.BigInt(scale);
  42477. } else if (typeof baseTime === 'number' && !isNaN(baseTime)) {
  42478. seconds = baseTime / scale;
  42479. }
  42480. if (seconds < Number.MAX_SAFE_INTEGER) {
  42481. seconds = Number(seconds);
  42482. }
  42483. if (seconds < acc) {
  42484. acc = seconds;
  42485. }
  42486. return acc;
  42487. }, Infinity);
  42488. return typeof lowestTime === 'bigint' || isFinite(lowestTime) ? lowestTime : 0;
  42489. };
  42490. /**
  42491. * Determine the composition start, in seconds, for an MP4
  42492. * fragment.
  42493. *
  42494. * The composition start time of a fragment can be calculated using the base
  42495. * media decode time, composition time offset, and timescale, as follows:
  42496. *
  42497. * compositionStartTime = (baseMediaDecodeTime + compositionTimeOffset) / timescale
  42498. *
  42499. * All of the aforementioned information is contained within a media fragment's
  42500. * `traf` box, except for timescale info, which comes from the initialization
  42501. * segment, so a track id (also contained within a `traf`) is also necessary to
  42502. * associate it with a timescale
  42503. *
  42504. *
  42505. * @param timescales {object} - a hash of track ids to timescale values.
  42506. * @param fragment {Unit8Array} - the bytes of a media segment
  42507. * @return {number} the composition start time for the fragment, in seconds
  42508. **/
  42509. compositionStartTime = function compositionStartTime(timescales, fragment) {
  42510. var trafBoxes = findBox_1(fragment, ['moof', 'traf']);
  42511. var baseMediaDecodeTime = 0;
  42512. var compositionTimeOffset = 0;
  42513. var trackId;
  42514. if (trafBoxes && trafBoxes.length) {
  42515. // The spec states that track run samples contained within a `traf` box are contiguous, but
  42516. // it does not explicitly state whether the `traf` boxes themselves are contiguous.
  42517. // We will assume that they are, so we only need the first to calculate start time.
  42518. var tfhd = findBox_1(trafBoxes[0], ['tfhd'])[0];
  42519. var trun = findBox_1(trafBoxes[0], ['trun'])[0];
  42520. var tfdt = findBox_1(trafBoxes[0], ['tfdt'])[0];
  42521. if (tfhd) {
  42522. var parsedTfhd = parseTfhd(tfhd);
  42523. trackId = parsedTfhd.trackId;
  42524. }
  42525. if (tfdt) {
  42526. var parsedTfdt = parseTfdt(tfdt);
  42527. baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;
  42528. }
  42529. if (trun) {
  42530. var parsedTrun = parseTrun(trun);
  42531. if (parsedTrun.samples && parsedTrun.samples.length) {
  42532. compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;
  42533. }
  42534. }
  42535. } // Get timescale for this specific track. Assume a 90kHz clock if no timescale was
  42536. // specified.
  42537. var timescale = timescales[trackId] || 90e3; // return the composition start time, in seconds
  42538. if (typeof baseMediaDecodeTime === 'bigint') {
  42539. compositionTimeOffset = window_1.BigInt(compositionTimeOffset);
  42540. timescale = window_1.BigInt(timescale);
  42541. }
  42542. var result = (baseMediaDecodeTime + compositionTimeOffset) / timescale;
  42543. if (typeof result === 'bigint' && result < Number.MAX_SAFE_INTEGER) {
  42544. result = Number(result);
  42545. }
  42546. return result;
  42547. };
  42548. /**
  42549. * Find the trackIds of the video tracks in this source.
  42550. * Found by parsing the Handler Reference and Track Header Boxes:
  42551. * moov > trak > mdia > hdlr
  42552. * moov > trak > tkhd
  42553. *
  42554. * @param {Uint8Array} init - The bytes of the init segment for this source
  42555. * @return {Number[]} A list of trackIds
  42556. *
  42557. * @see ISO-BMFF-12/2015, Section 8.4.3
  42558. **/
  42559. getVideoTrackIds = function getVideoTrackIds(init) {
  42560. var traks = findBox_1(init, ['moov', 'trak']);
  42561. var videoTrackIds = [];
  42562. traks.forEach(function (trak) {
  42563. var hdlrs = findBox_1(trak, ['mdia', 'hdlr']);
  42564. var tkhds = findBox_1(trak, ['tkhd']);
  42565. hdlrs.forEach(function (hdlr, index) {
  42566. var handlerType = parseType_1(hdlr.subarray(8, 12));
  42567. var tkhd = tkhds[index];
  42568. var view;
  42569. var version;
  42570. var trackId;
  42571. if (handlerType === 'vide') {
  42572. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  42573. version = view.getUint8(0);
  42574. trackId = version === 0 ? view.getUint32(12) : view.getUint32(20);
  42575. videoTrackIds.push(trackId);
  42576. }
  42577. });
  42578. });
  42579. return videoTrackIds;
  42580. };
  42581. getTimescaleFromMediaHeader = function getTimescaleFromMediaHeader(mdhd) {
  42582. // mdhd is a FullBox, meaning it will have its own version as the first byte
  42583. var version = mdhd[0];
  42584. var index = version === 0 ? 12 : 20;
  42585. return toUnsigned(mdhd[index] << 24 | mdhd[index + 1] << 16 | mdhd[index + 2] << 8 | mdhd[index + 3]);
  42586. };
  42587. /**
  42588. * Get all the video, audio, and hint tracks from a non fragmented
  42589. * mp4 segment
  42590. */
  42591. getTracks = function getTracks(init) {
  42592. var traks = findBox_1(init, ['moov', 'trak']);
  42593. var tracks = [];
  42594. traks.forEach(function (trak) {
  42595. var track = {};
  42596. var tkhd = findBox_1(trak, ['tkhd'])[0];
  42597. var view, tkhdVersion; // id
  42598. if (tkhd) {
  42599. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  42600. tkhdVersion = view.getUint8(0);
  42601. track.id = tkhdVersion === 0 ? view.getUint32(12) : view.getUint32(20);
  42602. }
  42603. var hdlr = findBox_1(trak, ['mdia', 'hdlr'])[0]; // type
  42604. if (hdlr) {
  42605. var type = parseType_1(hdlr.subarray(8, 12));
  42606. if (type === 'vide') {
  42607. track.type = 'video';
  42608. } else if (type === 'soun') {
  42609. track.type = 'audio';
  42610. } else {
  42611. track.type = type;
  42612. }
  42613. } // codec
  42614. var stsd = findBox_1(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  42615. if (stsd) {
  42616. var sampleDescriptions = stsd.subarray(8); // gives the codec type string
  42617. track.codec = parseType_1(sampleDescriptions.subarray(4, 8));
  42618. var codecBox = findBox_1(sampleDescriptions, [track.codec])[0];
  42619. var codecConfig, codecConfigType;
  42620. if (codecBox) {
  42621. // https://tools.ietf.org/html/rfc6381#section-3.3
  42622. if (/^[asm]vc[1-9]$/i.test(track.codec)) {
  42623. // we don't need anything but the "config" parameter of the
  42624. // avc1 codecBox
  42625. codecConfig = codecBox.subarray(78);
  42626. codecConfigType = parseType_1(codecConfig.subarray(4, 8));
  42627. if (codecConfigType === 'avcC' && codecConfig.length > 11) {
  42628. track.codec += '.'; // left padded with zeroes for single digit hex
  42629. // profile idc
  42630. track.codec += toHexString(codecConfig[9]); // the byte containing the constraint_set flags
  42631. track.codec += toHexString(codecConfig[10]); // level idc
  42632. track.codec += toHexString(codecConfig[11]);
  42633. } else {
  42634. // TODO: show a warning that we couldn't parse the codec
  42635. // and are using the default
  42636. track.codec = 'avc1.4d400d';
  42637. }
  42638. } else if (/^mp4[a,v]$/i.test(track.codec)) {
  42639. // we do not need anything but the streamDescriptor of the mp4a codecBox
  42640. codecConfig = codecBox.subarray(28);
  42641. codecConfigType = parseType_1(codecConfig.subarray(4, 8));
  42642. if (codecConfigType === 'esds' && codecConfig.length > 20 && codecConfig[19] !== 0) {
  42643. track.codec += '.' + toHexString(codecConfig[19]); // this value is only a single digit
  42644. track.codec += '.' + toHexString(codecConfig[20] >>> 2 & 0x3f).replace(/^0/, '');
  42645. } else {
  42646. // TODO: show a warning that we couldn't parse the codec
  42647. // and are using the default
  42648. track.codec = 'mp4a.40.2';
  42649. }
  42650. } else {
  42651. // flac, opus, etc
  42652. track.codec = track.codec.toLowerCase();
  42653. }
  42654. }
  42655. }
  42656. var mdhd = findBox_1(trak, ['mdia', 'mdhd'])[0];
  42657. if (mdhd) {
  42658. track.timescale = getTimescaleFromMediaHeader(mdhd);
  42659. }
  42660. tracks.push(track);
  42661. });
  42662. return tracks;
  42663. };
  42664. var probe$2 = {
  42665. // export mp4 inspector's findBox and parseType for backwards compatibility
  42666. findBox: findBox_1,
  42667. parseType: parseType_1,
  42668. timescale: timescale,
  42669. startTime: startTime,
  42670. compositionStartTime: compositionStartTime,
  42671. videoTrackIds: getVideoTrackIds,
  42672. tracks: getTracks,
  42673. getTimescaleFromMediaHeader: getTimescaleFromMediaHeader
  42674. };
  42675. var parsePid = function parsePid(packet) {
  42676. var pid = packet[1] & 0x1f;
  42677. pid <<= 8;
  42678. pid |= packet[2];
  42679. return pid;
  42680. };
  42681. var parsePayloadUnitStartIndicator = function parsePayloadUnitStartIndicator(packet) {
  42682. return !!(packet[1] & 0x40);
  42683. };
  42684. var parseAdaptionField = function parseAdaptionField(packet) {
  42685. var offset = 0; // if an adaption field is present, its length is specified by the
  42686. // fifth byte of the TS packet header. The adaptation field is
  42687. // used to add stuffing to PES packets that don't fill a complete
  42688. // TS packet, and to specify some forms of timing and control data
  42689. // that we do not currently use.
  42690. if ((packet[3] & 0x30) >>> 4 > 0x01) {
  42691. offset += packet[4] + 1;
  42692. }
  42693. return offset;
  42694. };
  42695. var parseType = function parseType(packet, pmtPid) {
  42696. var pid = parsePid(packet);
  42697. if (pid === 0) {
  42698. return 'pat';
  42699. } else if (pid === pmtPid) {
  42700. return 'pmt';
  42701. } else if (pmtPid) {
  42702. return 'pes';
  42703. }
  42704. return null;
  42705. };
  42706. var parsePat = function parsePat(packet) {
  42707. var pusi = parsePayloadUnitStartIndicator(packet);
  42708. var offset = 4 + parseAdaptionField(packet);
  42709. if (pusi) {
  42710. offset += packet[offset] + 1;
  42711. }
  42712. return (packet[offset + 10] & 0x1f) << 8 | packet[offset + 11];
  42713. };
  42714. var parsePmt = function parsePmt(packet) {
  42715. var programMapTable = {};
  42716. var pusi = parsePayloadUnitStartIndicator(packet);
  42717. var payloadOffset = 4 + parseAdaptionField(packet);
  42718. if (pusi) {
  42719. payloadOffset += packet[payloadOffset] + 1;
  42720. } // PMTs can be sent ahead of the time when they should actually
  42721. // take effect. We don't believe this should ever be the case
  42722. // for HLS but we'll ignore "forward" PMT declarations if we see
  42723. // them. Future PMT declarations have the current_next_indicator
  42724. // set to zero.
  42725. if (!(packet[payloadOffset + 5] & 0x01)) {
  42726. return;
  42727. }
  42728. var sectionLength, tableEnd, programInfoLength; // the mapping table ends at the end of the current section
  42729. sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];
  42730. tableEnd = 3 + sectionLength - 4; // to determine where the table is, we have to figure out how
  42731. // long the program info descriptors are
  42732. programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11]; // advance the offset to the first entry in the mapping table
  42733. var offset = 12 + programInfoLength;
  42734. while (offset < tableEnd) {
  42735. var i = payloadOffset + offset; // add an entry that maps the elementary_pid to the stream_type
  42736. programMapTable[(packet[i + 1] & 0x1F) << 8 | packet[i + 2]] = packet[i]; // move to the next table entry
  42737. // skip past the elementary stream descriptors, if present
  42738. offset += ((packet[i + 3] & 0x0F) << 8 | packet[i + 4]) + 5;
  42739. }
  42740. return programMapTable;
  42741. };
  42742. var parsePesType = function parsePesType(packet, programMapTable) {
  42743. var pid = parsePid(packet);
  42744. var type = programMapTable[pid];
  42745. switch (type) {
  42746. case streamTypes.H264_STREAM_TYPE:
  42747. return 'video';
  42748. case streamTypes.ADTS_STREAM_TYPE:
  42749. return 'audio';
  42750. case streamTypes.METADATA_STREAM_TYPE:
  42751. return 'timed-metadata';
  42752. default:
  42753. return null;
  42754. }
  42755. };
  42756. var parsePesTime = function parsePesTime(packet) {
  42757. var pusi = parsePayloadUnitStartIndicator(packet);
  42758. if (!pusi) {
  42759. return null;
  42760. }
  42761. var offset = 4 + parseAdaptionField(packet);
  42762. if (offset >= packet.byteLength) {
  42763. // From the H 222.0 MPEG-TS spec
  42764. // "For transport stream packets carrying PES packets, stuffing is needed when there
  42765. // is insufficient PES packet data to completely fill the transport stream packet
  42766. // payload bytes. Stuffing is accomplished by defining an adaptation field longer than
  42767. // the sum of the lengths of the data elements in it, so that the payload bytes
  42768. // remaining after the adaptation field exactly accommodates the available PES packet
  42769. // data."
  42770. //
  42771. // If the offset is >= the length of the packet, then the packet contains no data
  42772. // and instead is just adaption field stuffing bytes
  42773. return null;
  42774. }
  42775. var pes = null;
  42776. var ptsDtsFlags; // PES packets may be annotated with a PTS value, or a PTS value
  42777. // and a DTS value. Determine what combination of values is
  42778. // available to work with.
  42779. ptsDtsFlags = packet[offset + 7]; // PTS and DTS are normally stored as a 33-bit number. Javascript
  42780. // performs all bitwise operations on 32-bit integers but javascript
  42781. // supports a much greater range (52-bits) of integer using standard
  42782. // mathematical operations.
  42783. // We construct a 31-bit value using bitwise operators over the 31
  42784. // most significant bits and then multiply by 4 (equal to a left-shift
  42785. // of 2) before we add the final 2 least significant bits of the
  42786. // timestamp (equal to an OR.)
  42787. if (ptsDtsFlags & 0xC0) {
  42788. pes = {}; // the PTS and DTS are not written out directly. For information
  42789. // on how they are encoded, see
  42790. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  42791. 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;
  42792. pes.pts *= 4; // Left shift by 2
  42793. pes.pts += (packet[offset + 13] & 0x06) >>> 1; // OR by the two LSBs
  42794. pes.dts = pes.pts;
  42795. if (ptsDtsFlags & 0x40) {
  42796. 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;
  42797. pes.dts *= 4; // Left shift by 2
  42798. pes.dts += (packet[offset + 18] & 0x06) >>> 1; // OR by the two LSBs
  42799. }
  42800. }
  42801. return pes;
  42802. };
  42803. var parseNalUnitType = function parseNalUnitType(type) {
  42804. switch (type) {
  42805. case 0x05:
  42806. return 'slice_layer_without_partitioning_rbsp_idr';
  42807. case 0x06:
  42808. return 'sei_rbsp';
  42809. case 0x07:
  42810. return 'seq_parameter_set_rbsp';
  42811. case 0x08:
  42812. return 'pic_parameter_set_rbsp';
  42813. case 0x09:
  42814. return 'access_unit_delimiter_rbsp';
  42815. default:
  42816. return null;
  42817. }
  42818. };
  42819. var videoPacketContainsKeyFrame = function videoPacketContainsKeyFrame(packet) {
  42820. var offset = 4 + parseAdaptionField(packet);
  42821. var frameBuffer = packet.subarray(offset);
  42822. var frameI = 0;
  42823. var frameSyncPoint = 0;
  42824. var foundKeyFrame = false;
  42825. var nalType; // advance the sync point to a NAL start, if necessary
  42826. for (; frameSyncPoint < frameBuffer.byteLength - 3; frameSyncPoint++) {
  42827. if (frameBuffer[frameSyncPoint + 2] === 1) {
  42828. // the sync point is properly aligned
  42829. frameI = frameSyncPoint + 5;
  42830. break;
  42831. }
  42832. }
  42833. while (frameI < frameBuffer.byteLength) {
  42834. // look at the current byte to determine if we've hit the end of
  42835. // a NAL unit boundary
  42836. switch (frameBuffer[frameI]) {
  42837. case 0:
  42838. // skip past non-sync sequences
  42839. if (frameBuffer[frameI - 1] !== 0) {
  42840. frameI += 2;
  42841. break;
  42842. } else if (frameBuffer[frameI - 2] !== 0) {
  42843. frameI++;
  42844. break;
  42845. }
  42846. if (frameSyncPoint + 3 !== frameI - 2) {
  42847. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  42848. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  42849. foundKeyFrame = true;
  42850. }
  42851. } // drop trailing zeroes
  42852. do {
  42853. frameI++;
  42854. } while (frameBuffer[frameI] !== 1 && frameI < frameBuffer.length);
  42855. frameSyncPoint = frameI - 2;
  42856. frameI += 3;
  42857. break;
  42858. case 1:
  42859. // skip past non-sync sequences
  42860. if (frameBuffer[frameI - 1] !== 0 || frameBuffer[frameI - 2] !== 0) {
  42861. frameI += 3;
  42862. break;
  42863. }
  42864. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  42865. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  42866. foundKeyFrame = true;
  42867. }
  42868. frameSyncPoint = frameI - 2;
  42869. frameI += 3;
  42870. break;
  42871. default:
  42872. // the current byte isn't a one or zero, so it cannot be part
  42873. // of a sync sequence
  42874. frameI += 3;
  42875. break;
  42876. }
  42877. }
  42878. frameBuffer = frameBuffer.subarray(frameSyncPoint);
  42879. frameI -= frameSyncPoint;
  42880. frameSyncPoint = 0; // parse the final nal
  42881. if (frameBuffer && frameBuffer.byteLength > 3) {
  42882. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  42883. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  42884. foundKeyFrame = true;
  42885. }
  42886. }
  42887. return foundKeyFrame;
  42888. };
  42889. var probe$1 = {
  42890. parseType: parseType,
  42891. parsePat: parsePat,
  42892. parsePmt: parsePmt,
  42893. parsePayloadUnitStartIndicator: parsePayloadUnitStartIndicator,
  42894. parsePesType: parsePesType,
  42895. parsePesTime: parsePesTime,
  42896. videoPacketContainsKeyFrame: videoPacketContainsKeyFrame
  42897. };
  42898. var handleRollover = timestampRolloverStream.handleRollover;
  42899. var probe = {};
  42900. probe.ts = probe$1;
  42901. probe.aac = utils;
  42902. var ONE_SECOND_IN_TS = clock.ONE_SECOND_IN_TS;
  42903. var MP2T_PACKET_LENGTH = 188,
  42904. // bytes
  42905. SYNC_BYTE = 0x47;
  42906. /**
  42907. * walks through segment data looking for pat and pmt packets to parse out
  42908. * program map table information
  42909. */
  42910. var parsePsi_ = function parsePsi_(bytes, pmt) {
  42911. var startIndex = 0,
  42912. endIndex = MP2T_PACKET_LENGTH,
  42913. packet,
  42914. type;
  42915. while (endIndex < bytes.byteLength) {
  42916. // Look for a pair of start and end sync bytes in the data..
  42917. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  42918. // We found a packet
  42919. packet = bytes.subarray(startIndex, endIndex);
  42920. type = probe.ts.parseType(packet, pmt.pid);
  42921. switch (type) {
  42922. case 'pat':
  42923. pmt.pid = probe.ts.parsePat(packet);
  42924. break;
  42925. case 'pmt':
  42926. var table = probe.ts.parsePmt(packet);
  42927. pmt.table = pmt.table || {};
  42928. Object.keys(table).forEach(function (key) {
  42929. pmt.table[key] = table[key];
  42930. });
  42931. break;
  42932. }
  42933. startIndex += MP2T_PACKET_LENGTH;
  42934. endIndex += MP2T_PACKET_LENGTH;
  42935. continue;
  42936. } // If we get here, we have somehow become de-synchronized and we need to step
  42937. // forward one byte at a time until we find a pair of sync bytes that denote
  42938. // a packet
  42939. startIndex++;
  42940. endIndex++;
  42941. }
  42942. };
  42943. /**
  42944. * walks through the segment data from the start and end to get timing information
  42945. * for the first and last audio pes packets
  42946. */
  42947. var parseAudioPes_ = function parseAudioPes_(bytes, pmt, result) {
  42948. var startIndex = 0,
  42949. endIndex = MP2T_PACKET_LENGTH,
  42950. packet,
  42951. type,
  42952. pesType,
  42953. pusi,
  42954. parsed;
  42955. var endLoop = false; // Start walking from start of segment to get first audio packet
  42956. while (endIndex <= bytes.byteLength) {
  42957. // Look for a pair of start and end sync bytes in the data..
  42958. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  42959. // We found a packet
  42960. packet = bytes.subarray(startIndex, endIndex);
  42961. type = probe.ts.parseType(packet, pmt.pid);
  42962. switch (type) {
  42963. case 'pes':
  42964. pesType = probe.ts.parsePesType(packet, pmt.table);
  42965. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  42966. if (pesType === 'audio' && pusi) {
  42967. parsed = probe.ts.parsePesTime(packet);
  42968. if (parsed) {
  42969. parsed.type = 'audio';
  42970. result.audio.push(parsed);
  42971. endLoop = true;
  42972. }
  42973. }
  42974. break;
  42975. }
  42976. if (endLoop) {
  42977. break;
  42978. }
  42979. startIndex += MP2T_PACKET_LENGTH;
  42980. endIndex += MP2T_PACKET_LENGTH;
  42981. continue;
  42982. } // If we get here, we have somehow become de-synchronized and we need to step
  42983. // forward one byte at a time until we find a pair of sync bytes that denote
  42984. // a packet
  42985. startIndex++;
  42986. endIndex++;
  42987. } // Start walking from end of segment to get last audio packet
  42988. endIndex = bytes.byteLength;
  42989. startIndex = endIndex - MP2T_PACKET_LENGTH;
  42990. endLoop = false;
  42991. while (startIndex >= 0) {
  42992. // Look for a pair of start and end sync bytes in the data..
  42993. if (bytes[startIndex] === SYNC_BYTE && (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  42994. // We found a packet
  42995. packet = bytes.subarray(startIndex, endIndex);
  42996. type = probe.ts.parseType(packet, pmt.pid);
  42997. switch (type) {
  42998. case 'pes':
  42999. pesType = probe.ts.parsePesType(packet, pmt.table);
  43000. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  43001. if (pesType === 'audio' && pusi) {
  43002. parsed = probe.ts.parsePesTime(packet);
  43003. if (parsed) {
  43004. parsed.type = 'audio';
  43005. result.audio.push(parsed);
  43006. endLoop = true;
  43007. }
  43008. }
  43009. break;
  43010. }
  43011. if (endLoop) {
  43012. break;
  43013. }
  43014. startIndex -= MP2T_PACKET_LENGTH;
  43015. endIndex -= MP2T_PACKET_LENGTH;
  43016. continue;
  43017. } // If we get here, we have somehow become de-synchronized and we need to step
  43018. // forward one byte at a time until we find a pair of sync bytes that denote
  43019. // a packet
  43020. startIndex--;
  43021. endIndex--;
  43022. }
  43023. };
  43024. /**
  43025. * walks through the segment data from the start and end to get timing information
  43026. * for the first and last video pes packets as well as timing information for the first
  43027. * key frame.
  43028. */
  43029. var parseVideoPes_ = function parseVideoPes_(bytes, pmt, result) {
  43030. var startIndex = 0,
  43031. endIndex = MP2T_PACKET_LENGTH,
  43032. packet,
  43033. type,
  43034. pesType,
  43035. pusi,
  43036. parsed,
  43037. frame,
  43038. i,
  43039. pes;
  43040. var endLoop = false;
  43041. var currentFrame = {
  43042. data: [],
  43043. size: 0
  43044. }; // Start walking from start of segment to get first video packet
  43045. while (endIndex < bytes.byteLength) {
  43046. // Look for a pair of start and end sync bytes in the data..
  43047. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  43048. // We found a packet
  43049. packet = bytes.subarray(startIndex, endIndex);
  43050. type = probe.ts.parseType(packet, pmt.pid);
  43051. switch (type) {
  43052. case 'pes':
  43053. pesType = probe.ts.parsePesType(packet, pmt.table);
  43054. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  43055. if (pesType === 'video') {
  43056. if (pusi && !endLoop) {
  43057. parsed = probe.ts.parsePesTime(packet);
  43058. if (parsed) {
  43059. parsed.type = 'video';
  43060. result.video.push(parsed);
  43061. endLoop = true;
  43062. }
  43063. }
  43064. if (!result.firstKeyFrame) {
  43065. if (pusi) {
  43066. if (currentFrame.size !== 0) {
  43067. frame = new Uint8Array(currentFrame.size);
  43068. i = 0;
  43069. while (currentFrame.data.length) {
  43070. pes = currentFrame.data.shift();
  43071. frame.set(pes, i);
  43072. i += pes.byteLength;
  43073. }
  43074. if (probe.ts.videoPacketContainsKeyFrame(frame)) {
  43075. var firstKeyFrame = probe.ts.parsePesTime(frame); // PTS/DTS may not be available. Simply *not* setting
  43076. // the keyframe seems to work fine with HLS playback
  43077. // and definitely preferable to a crash with TypeError...
  43078. if (firstKeyFrame) {
  43079. result.firstKeyFrame = firstKeyFrame;
  43080. result.firstKeyFrame.type = 'video';
  43081. } else {
  43082. // eslint-disable-next-line
  43083. 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.');
  43084. }
  43085. }
  43086. currentFrame.size = 0;
  43087. }
  43088. }
  43089. currentFrame.data.push(packet);
  43090. currentFrame.size += packet.byteLength;
  43091. }
  43092. }
  43093. break;
  43094. }
  43095. if (endLoop && result.firstKeyFrame) {
  43096. break;
  43097. }
  43098. startIndex += MP2T_PACKET_LENGTH;
  43099. endIndex += MP2T_PACKET_LENGTH;
  43100. continue;
  43101. } // If we get here, we have somehow become de-synchronized and we need to step
  43102. // forward one byte at a time until we find a pair of sync bytes that denote
  43103. // a packet
  43104. startIndex++;
  43105. endIndex++;
  43106. } // Start walking from end of segment to get last video packet
  43107. endIndex = bytes.byteLength;
  43108. startIndex = endIndex - MP2T_PACKET_LENGTH;
  43109. endLoop = false;
  43110. while (startIndex >= 0) {
  43111. // Look for a pair of start and end sync bytes in the data..
  43112. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  43113. // We found a packet
  43114. packet = bytes.subarray(startIndex, endIndex);
  43115. type = probe.ts.parseType(packet, pmt.pid);
  43116. switch (type) {
  43117. case 'pes':
  43118. pesType = probe.ts.parsePesType(packet, pmt.table);
  43119. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  43120. if (pesType === 'video' && pusi) {
  43121. parsed = probe.ts.parsePesTime(packet);
  43122. if (parsed) {
  43123. parsed.type = 'video';
  43124. result.video.push(parsed);
  43125. endLoop = true;
  43126. }
  43127. }
  43128. break;
  43129. }
  43130. if (endLoop) {
  43131. break;
  43132. }
  43133. startIndex -= MP2T_PACKET_LENGTH;
  43134. endIndex -= MP2T_PACKET_LENGTH;
  43135. continue;
  43136. } // If we get here, we have somehow become de-synchronized and we need to step
  43137. // forward one byte at a time until we find a pair of sync bytes that denote
  43138. // a packet
  43139. startIndex--;
  43140. endIndex--;
  43141. }
  43142. };
  43143. /**
  43144. * Adjusts the timestamp information for the segment to account for
  43145. * rollover and convert to seconds based on pes packet timescale (90khz clock)
  43146. */
  43147. var adjustTimestamp_ = function adjustTimestamp_(segmentInfo, baseTimestamp) {
  43148. if (segmentInfo.audio && segmentInfo.audio.length) {
  43149. var audioBaseTimestamp = baseTimestamp;
  43150. if (typeof audioBaseTimestamp === 'undefined' || isNaN(audioBaseTimestamp)) {
  43151. audioBaseTimestamp = segmentInfo.audio[0].dts;
  43152. }
  43153. segmentInfo.audio.forEach(function (info) {
  43154. info.dts = handleRollover(info.dts, audioBaseTimestamp);
  43155. info.pts = handleRollover(info.pts, audioBaseTimestamp); // time in seconds
  43156. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  43157. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  43158. });
  43159. }
  43160. if (segmentInfo.video && segmentInfo.video.length) {
  43161. var videoBaseTimestamp = baseTimestamp;
  43162. if (typeof videoBaseTimestamp === 'undefined' || isNaN(videoBaseTimestamp)) {
  43163. videoBaseTimestamp = segmentInfo.video[0].dts;
  43164. }
  43165. segmentInfo.video.forEach(function (info) {
  43166. info.dts = handleRollover(info.dts, videoBaseTimestamp);
  43167. info.pts = handleRollover(info.pts, videoBaseTimestamp); // time in seconds
  43168. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  43169. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  43170. });
  43171. if (segmentInfo.firstKeyFrame) {
  43172. var frame = segmentInfo.firstKeyFrame;
  43173. frame.dts = handleRollover(frame.dts, videoBaseTimestamp);
  43174. frame.pts = handleRollover(frame.pts, videoBaseTimestamp); // time in seconds
  43175. frame.dtsTime = frame.dts / ONE_SECOND_IN_TS;
  43176. frame.ptsTime = frame.pts / ONE_SECOND_IN_TS;
  43177. }
  43178. }
  43179. };
  43180. /**
  43181. * inspects the aac data stream for start and end time information
  43182. */
  43183. var inspectAac_ = function inspectAac_(bytes) {
  43184. var endLoop = false,
  43185. audioCount = 0,
  43186. sampleRate = null,
  43187. timestamp = null,
  43188. frameSize = 0,
  43189. byteIndex = 0,
  43190. packet;
  43191. while (bytes.length - byteIndex >= 3) {
  43192. var type = probe.aac.parseType(bytes, byteIndex);
  43193. switch (type) {
  43194. case 'timed-metadata':
  43195. // Exit early because we don't have enough to parse
  43196. // the ID3 tag header
  43197. if (bytes.length - byteIndex < 10) {
  43198. endLoop = true;
  43199. break;
  43200. }
  43201. frameSize = probe.aac.parseId3TagSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  43202. // to emit a full packet
  43203. if (frameSize > bytes.length) {
  43204. endLoop = true;
  43205. break;
  43206. }
  43207. if (timestamp === null) {
  43208. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  43209. timestamp = probe.aac.parseAacTimestamp(packet);
  43210. }
  43211. byteIndex += frameSize;
  43212. break;
  43213. case 'audio':
  43214. // Exit early because we don't have enough to parse
  43215. // the ADTS frame header
  43216. if (bytes.length - byteIndex < 7) {
  43217. endLoop = true;
  43218. break;
  43219. }
  43220. frameSize = probe.aac.parseAdtsSize(bytes, byteIndex); // Exit early if we don't have enough in the buffer
  43221. // to emit a full packet
  43222. if (frameSize > bytes.length) {
  43223. endLoop = true;
  43224. break;
  43225. }
  43226. if (sampleRate === null) {
  43227. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  43228. sampleRate = probe.aac.parseSampleRate(packet);
  43229. }
  43230. audioCount++;
  43231. byteIndex += frameSize;
  43232. break;
  43233. default:
  43234. byteIndex++;
  43235. break;
  43236. }
  43237. if (endLoop) {
  43238. return null;
  43239. }
  43240. }
  43241. if (sampleRate === null || timestamp === null) {
  43242. return null;
  43243. }
  43244. var audioTimescale = ONE_SECOND_IN_TS / sampleRate;
  43245. var result = {
  43246. audio: [{
  43247. type: 'audio',
  43248. dts: timestamp,
  43249. pts: timestamp
  43250. }, {
  43251. type: 'audio',
  43252. dts: timestamp + audioCount * 1024 * audioTimescale,
  43253. pts: timestamp + audioCount * 1024 * audioTimescale
  43254. }]
  43255. };
  43256. return result;
  43257. };
  43258. /**
  43259. * inspects the transport stream segment data for start and end time information
  43260. * of the audio and video tracks (when present) as well as the first key frame's
  43261. * start time.
  43262. */
  43263. var inspectTs_ = function inspectTs_(bytes) {
  43264. var pmt = {
  43265. pid: null,
  43266. table: null
  43267. };
  43268. var result = {};
  43269. parsePsi_(bytes, pmt);
  43270. for (var pid in pmt.table) {
  43271. if (pmt.table.hasOwnProperty(pid)) {
  43272. var type = pmt.table[pid];
  43273. switch (type) {
  43274. case streamTypes.H264_STREAM_TYPE:
  43275. result.video = [];
  43276. parseVideoPes_(bytes, pmt, result);
  43277. if (result.video.length === 0) {
  43278. delete result.video;
  43279. }
  43280. break;
  43281. case streamTypes.ADTS_STREAM_TYPE:
  43282. result.audio = [];
  43283. parseAudioPes_(bytes, pmt, result);
  43284. if (result.audio.length === 0) {
  43285. delete result.audio;
  43286. }
  43287. break;
  43288. }
  43289. }
  43290. }
  43291. return result;
  43292. };
  43293. /**
  43294. * Inspects segment byte data and returns an object with start and end timing information
  43295. *
  43296. * @param {Uint8Array} bytes The segment byte data
  43297. * @param {Number} baseTimestamp Relative reference timestamp used when adjusting frame
  43298. * timestamps for rollover. This value must be in 90khz clock.
  43299. * @return {Object} Object containing start and end frame timing info of segment.
  43300. */
  43301. var inspect = function inspect(bytes, baseTimestamp) {
  43302. var isAacData = probe.aac.isLikelyAacData(bytes);
  43303. var result;
  43304. if (isAacData) {
  43305. result = inspectAac_(bytes);
  43306. } else {
  43307. result = inspectTs_(bytes);
  43308. }
  43309. if (!result || !result.audio && !result.video) {
  43310. return null;
  43311. }
  43312. adjustTimestamp_(result, baseTimestamp);
  43313. return result;
  43314. };
  43315. var tsInspector = {
  43316. inspect: inspect,
  43317. parseAudioPes_: parseAudioPes_
  43318. };
  43319. /* global self */
  43320. /**
  43321. * Re-emits transmuxer events by converting them into messages to the
  43322. * world outside the worker.
  43323. *
  43324. * @param {Object} transmuxer the transmuxer to wire events on
  43325. * @private
  43326. */
  43327. var wireTransmuxerEvents = function wireTransmuxerEvents(self, transmuxer) {
  43328. transmuxer.on('data', function (segment) {
  43329. // transfer ownership of the underlying ArrayBuffer
  43330. // instead of doing a copy to save memory
  43331. // ArrayBuffers are transferable but generic TypedArrays are not
  43332. // @link https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers#Passing_data_by_transferring_ownership_(transferable_objects)
  43333. var initArray = segment.initSegment;
  43334. segment.initSegment = {
  43335. data: initArray.buffer,
  43336. byteOffset: initArray.byteOffset,
  43337. byteLength: initArray.byteLength
  43338. };
  43339. var typedArray = segment.data;
  43340. segment.data = typedArray.buffer;
  43341. self.postMessage({
  43342. action: 'data',
  43343. segment: segment,
  43344. byteOffset: typedArray.byteOffset,
  43345. byteLength: typedArray.byteLength
  43346. }, [segment.data]);
  43347. });
  43348. transmuxer.on('done', function (data) {
  43349. self.postMessage({
  43350. action: 'done'
  43351. });
  43352. });
  43353. transmuxer.on('gopInfo', function (gopInfo) {
  43354. self.postMessage({
  43355. action: 'gopInfo',
  43356. gopInfo: gopInfo
  43357. });
  43358. });
  43359. transmuxer.on('videoSegmentTimingInfo', function (timingInfo) {
  43360. var videoSegmentTimingInfo = {
  43361. start: {
  43362. decode: clock.videoTsToSeconds(timingInfo.start.dts),
  43363. presentation: clock.videoTsToSeconds(timingInfo.start.pts)
  43364. },
  43365. end: {
  43366. decode: clock.videoTsToSeconds(timingInfo.end.dts),
  43367. presentation: clock.videoTsToSeconds(timingInfo.end.pts)
  43368. },
  43369. baseMediaDecodeTime: clock.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  43370. };
  43371. if (timingInfo.prependedContentDuration) {
  43372. videoSegmentTimingInfo.prependedContentDuration = clock.videoTsToSeconds(timingInfo.prependedContentDuration);
  43373. }
  43374. self.postMessage({
  43375. action: 'videoSegmentTimingInfo',
  43376. videoSegmentTimingInfo: videoSegmentTimingInfo
  43377. });
  43378. });
  43379. transmuxer.on('audioSegmentTimingInfo', function (timingInfo) {
  43380. // Note that all times for [audio/video]SegmentTimingInfo events are in video clock
  43381. var audioSegmentTimingInfo = {
  43382. start: {
  43383. decode: clock.videoTsToSeconds(timingInfo.start.dts),
  43384. presentation: clock.videoTsToSeconds(timingInfo.start.pts)
  43385. },
  43386. end: {
  43387. decode: clock.videoTsToSeconds(timingInfo.end.dts),
  43388. presentation: clock.videoTsToSeconds(timingInfo.end.pts)
  43389. },
  43390. baseMediaDecodeTime: clock.videoTsToSeconds(timingInfo.baseMediaDecodeTime)
  43391. };
  43392. if (timingInfo.prependedContentDuration) {
  43393. audioSegmentTimingInfo.prependedContentDuration = clock.videoTsToSeconds(timingInfo.prependedContentDuration);
  43394. }
  43395. self.postMessage({
  43396. action: 'audioSegmentTimingInfo',
  43397. audioSegmentTimingInfo: audioSegmentTimingInfo
  43398. });
  43399. });
  43400. transmuxer.on('id3Frame', function (id3Frame) {
  43401. self.postMessage({
  43402. action: 'id3Frame',
  43403. id3Frame: id3Frame
  43404. });
  43405. });
  43406. transmuxer.on('caption', function (caption) {
  43407. self.postMessage({
  43408. action: 'caption',
  43409. caption: caption
  43410. });
  43411. });
  43412. transmuxer.on('trackinfo', function (trackInfo) {
  43413. self.postMessage({
  43414. action: 'trackinfo',
  43415. trackInfo: trackInfo
  43416. });
  43417. });
  43418. transmuxer.on('audioTimingInfo', function (audioTimingInfo) {
  43419. // convert to video TS since we prioritize video time over audio
  43420. self.postMessage({
  43421. action: 'audioTimingInfo',
  43422. audioTimingInfo: {
  43423. start: clock.videoTsToSeconds(audioTimingInfo.start),
  43424. end: clock.videoTsToSeconds(audioTimingInfo.end)
  43425. }
  43426. });
  43427. });
  43428. transmuxer.on('videoTimingInfo', function (videoTimingInfo) {
  43429. self.postMessage({
  43430. action: 'videoTimingInfo',
  43431. videoTimingInfo: {
  43432. start: clock.videoTsToSeconds(videoTimingInfo.start),
  43433. end: clock.videoTsToSeconds(videoTimingInfo.end)
  43434. }
  43435. });
  43436. });
  43437. transmuxer.on('log', function (log) {
  43438. self.postMessage({
  43439. action: 'log',
  43440. log: log
  43441. });
  43442. });
  43443. };
  43444. /**
  43445. * All incoming messages route through this hash. If no function exists
  43446. * to handle an incoming message, then we ignore the message.
  43447. *
  43448. * @class MessageHandlers
  43449. * @param {Object} options the options to initialize with
  43450. */
  43451. var MessageHandlers = /*#__PURE__*/function () {
  43452. function MessageHandlers(self, options) {
  43453. this.options = options || {};
  43454. this.self = self;
  43455. this.init();
  43456. }
  43457. /**
  43458. * initialize our web worker and wire all the events.
  43459. */
  43460. var _proto = MessageHandlers.prototype;
  43461. _proto.init = function init() {
  43462. if (this.transmuxer) {
  43463. this.transmuxer.dispose();
  43464. }
  43465. this.transmuxer = new transmuxer.Transmuxer(this.options);
  43466. wireTransmuxerEvents(this.self, this.transmuxer);
  43467. };
  43468. _proto.pushMp4Captions = function pushMp4Captions(data) {
  43469. if (!this.captionParser) {
  43470. this.captionParser = new captionParser();
  43471. this.captionParser.init();
  43472. }
  43473. var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  43474. var parsed = this.captionParser.parse(segment, data.trackIds, data.timescales);
  43475. this.self.postMessage({
  43476. action: 'mp4Captions',
  43477. captions: parsed && parsed.captions || [],
  43478. logs: parsed && parsed.logs || [],
  43479. data: segment.buffer
  43480. }, [segment.buffer]);
  43481. };
  43482. _proto.probeMp4StartTime = function probeMp4StartTime(_ref) {
  43483. var timescales = _ref.timescales,
  43484. data = _ref.data;
  43485. var startTime = probe$2.startTime(timescales, data);
  43486. this.self.postMessage({
  43487. action: 'probeMp4StartTime',
  43488. startTime: startTime,
  43489. data: data
  43490. }, [data.buffer]);
  43491. };
  43492. _proto.probeMp4Tracks = function probeMp4Tracks(_ref2) {
  43493. var data = _ref2.data;
  43494. var tracks = probe$2.tracks(data);
  43495. this.self.postMessage({
  43496. action: 'probeMp4Tracks',
  43497. tracks: tracks,
  43498. data: data
  43499. }, [data.buffer]);
  43500. }
  43501. /**
  43502. * Probe an mpeg2-ts segment to determine the start time of the segment in it's
  43503. * internal "media time," as well as whether it contains video and/or audio.
  43504. *
  43505. * @private
  43506. * @param {Uint8Array} bytes - segment bytes
  43507. * @param {number} baseStartTime
  43508. * Relative reference timestamp used when adjusting frame timestamps for rollover.
  43509. * This value should be in seconds, as it's converted to a 90khz clock within the
  43510. * function body.
  43511. * @return {Object} The start time of the current segment in "media time" as well as
  43512. * whether it contains video and/or audio
  43513. */
  43514. ;
  43515. _proto.probeTs = function probeTs(_ref3) {
  43516. var data = _ref3.data,
  43517. baseStartTime = _ref3.baseStartTime;
  43518. var tsStartTime = typeof baseStartTime === 'number' && !isNaN(baseStartTime) ? baseStartTime * clock.ONE_SECOND_IN_TS : void 0;
  43519. var timeInfo = tsInspector.inspect(data, tsStartTime);
  43520. var result = null;
  43521. if (timeInfo) {
  43522. result = {
  43523. // each type's time info comes back as an array of 2 times, start and end
  43524. hasVideo: timeInfo.video && timeInfo.video.length === 2 || false,
  43525. hasAudio: timeInfo.audio && timeInfo.audio.length === 2 || false
  43526. };
  43527. if (result.hasVideo) {
  43528. result.videoStart = timeInfo.video[0].ptsTime;
  43529. }
  43530. if (result.hasAudio) {
  43531. result.audioStart = timeInfo.audio[0].ptsTime;
  43532. }
  43533. }
  43534. this.self.postMessage({
  43535. action: 'probeTs',
  43536. result: result,
  43537. data: data
  43538. }, [data.buffer]);
  43539. };
  43540. _proto.clearAllMp4Captions = function clearAllMp4Captions() {
  43541. if (this.captionParser) {
  43542. this.captionParser.clearAllCaptions();
  43543. }
  43544. };
  43545. _proto.clearParsedMp4Captions = function clearParsedMp4Captions() {
  43546. if (this.captionParser) {
  43547. this.captionParser.clearParsedCaptions();
  43548. }
  43549. }
  43550. /**
  43551. * Adds data (a ts segment) to the start of the transmuxer pipeline for
  43552. * processing.
  43553. *
  43554. * @param {ArrayBuffer} data data to push into the muxer
  43555. */
  43556. ;
  43557. _proto.push = function push(data) {
  43558. // Cast array buffer to correct type for transmuxer
  43559. var segment = new Uint8Array(data.data, data.byteOffset, data.byteLength);
  43560. this.transmuxer.push(segment);
  43561. }
  43562. /**
  43563. * Recreate the transmuxer so that the next segment added via `push`
  43564. * start with a fresh transmuxer.
  43565. */
  43566. ;
  43567. _proto.reset = function reset() {
  43568. this.transmuxer.reset();
  43569. }
  43570. /**
  43571. * Set the value that will be used as the `baseMediaDecodeTime` time for the
  43572. * next segment pushed in. Subsequent segments will have their `baseMediaDecodeTime`
  43573. * set relative to the first based on the PTS values.
  43574. *
  43575. * @param {Object} data used to set the timestamp offset in the muxer
  43576. */
  43577. ;
  43578. _proto.setTimestampOffset = function setTimestampOffset(data) {
  43579. var timestampOffset = data.timestampOffset || 0;
  43580. this.transmuxer.setBaseMediaDecodeTime(Math.round(clock.secondsToVideoTs(timestampOffset)));
  43581. };
  43582. _proto.setAudioAppendStart = function setAudioAppendStart(data) {
  43583. this.transmuxer.setAudioAppendStart(Math.ceil(clock.secondsToVideoTs(data.appendStart)));
  43584. };
  43585. _proto.setRemux = function setRemux(data) {
  43586. this.transmuxer.setRemux(data.remux);
  43587. }
  43588. /**
  43589. * Forces the pipeline to finish processing the last segment and emit it's
  43590. * results.
  43591. *
  43592. * @param {Object} data event data, not really used
  43593. */
  43594. ;
  43595. _proto.flush = function flush(data) {
  43596. this.transmuxer.flush(); // transmuxed done action is fired after both audio/video pipelines are flushed
  43597. self.postMessage({
  43598. action: 'done',
  43599. type: 'transmuxed'
  43600. });
  43601. };
  43602. _proto.endTimeline = function endTimeline() {
  43603. this.transmuxer.endTimeline(); // transmuxed endedtimeline action is fired after both audio/video pipelines end their
  43604. // timelines
  43605. self.postMessage({
  43606. action: 'endedtimeline',
  43607. type: 'transmuxed'
  43608. });
  43609. };
  43610. _proto.alignGopsWith = function alignGopsWith(data) {
  43611. this.transmuxer.alignGopsWith(data.gopsToAlignWith.slice());
  43612. };
  43613. return MessageHandlers;
  43614. }();
  43615. /**
  43616. * Our web worker interface so that things can talk to mux.js
  43617. * that will be running in a web worker. the scope is passed to this by
  43618. * webworkify.
  43619. *
  43620. * @param {Object} self the scope for the web worker
  43621. */
  43622. self.onmessage = function (event) {
  43623. if (event.data.action === 'init' && event.data.options) {
  43624. this.messageHandlers = new MessageHandlers(self, event.data.options);
  43625. return;
  43626. }
  43627. if (!this.messageHandlers) {
  43628. this.messageHandlers = new MessageHandlers(self);
  43629. }
  43630. if (event.data && event.data.action && event.data.action !== 'init') {
  43631. if (this.messageHandlers[event.data.action]) {
  43632. this.messageHandlers[event.data.action](event.data);
  43633. }
  43634. }
  43635. };
  43636. }));
  43637. var TransmuxWorker = factory(workerCode$1);
  43638. /* rollup-plugin-worker-factory end for worker!/Users/ddashkevich/projects/http-streaming/src/transmuxer-worker.js */
  43639. var handleData_ = function handleData_(event, transmuxedData, callback) {
  43640. var _event$data$segment = event.data.segment,
  43641. type = _event$data$segment.type,
  43642. initSegment = _event$data$segment.initSegment,
  43643. captions = _event$data$segment.captions,
  43644. captionStreams = _event$data$segment.captionStreams,
  43645. metadata = _event$data$segment.metadata,
  43646. videoFrameDtsTime = _event$data$segment.videoFrameDtsTime,
  43647. videoFramePtsTime = _event$data$segment.videoFramePtsTime;
  43648. transmuxedData.buffer.push({
  43649. captions: captions,
  43650. captionStreams: captionStreams,
  43651. metadata: metadata
  43652. });
  43653. var boxes = event.data.segment.boxes || {
  43654. data: event.data.segment.data
  43655. };
  43656. var result = {
  43657. type: type,
  43658. // cast ArrayBuffer to TypedArray
  43659. data: new Uint8Array(boxes.data, boxes.data.byteOffset, boxes.data.byteLength),
  43660. initSegment: new Uint8Array(initSegment.data, initSegment.byteOffset, initSegment.byteLength)
  43661. };
  43662. if (typeof videoFrameDtsTime !== 'undefined') {
  43663. result.videoFrameDtsTime = videoFrameDtsTime;
  43664. }
  43665. if (typeof videoFramePtsTime !== 'undefined') {
  43666. result.videoFramePtsTime = videoFramePtsTime;
  43667. }
  43668. callback(result);
  43669. };
  43670. var handleDone_ = function handleDone_(_ref) {
  43671. var transmuxedData = _ref.transmuxedData,
  43672. callback = _ref.callback; // Previously we only returned data on data events,
  43673. // not on done events. Clear out the buffer to keep that consistent.
  43674. transmuxedData.buffer = []; // all buffers should have been flushed from the muxer, so start processing anything we
  43675. // have received
  43676. callback(transmuxedData);
  43677. };
  43678. var handleGopInfo_ = function handleGopInfo_(event, transmuxedData) {
  43679. transmuxedData.gopInfo = event.data.gopInfo;
  43680. };
  43681. var processTransmux = function processTransmux(options) {
  43682. var transmuxer = options.transmuxer,
  43683. bytes = options.bytes,
  43684. audioAppendStart = options.audioAppendStart,
  43685. gopsToAlignWith = options.gopsToAlignWith,
  43686. remux = options.remux,
  43687. onData = options.onData,
  43688. onTrackInfo = options.onTrackInfo,
  43689. onAudioTimingInfo = options.onAudioTimingInfo,
  43690. onVideoTimingInfo = options.onVideoTimingInfo,
  43691. onVideoSegmentTimingInfo = options.onVideoSegmentTimingInfo,
  43692. onAudioSegmentTimingInfo = options.onAudioSegmentTimingInfo,
  43693. onId3 = options.onId3,
  43694. onCaptions = options.onCaptions,
  43695. onDone = options.onDone,
  43696. onEndedTimeline = options.onEndedTimeline,
  43697. onTransmuxerLog = options.onTransmuxerLog,
  43698. isEndOfTimeline = options.isEndOfTimeline;
  43699. var transmuxedData = {
  43700. buffer: []
  43701. };
  43702. var waitForEndedTimelineEvent = isEndOfTimeline;
  43703. var handleMessage = function handleMessage(event) {
  43704. if (transmuxer.currentTransmux !== options) {
  43705. // disposed
  43706. return;
  43707. }
  43708. if (event.data.action === 'data') {
  43709. handleData_(event, transmuxedData, onData);
  43710. }
  43711. if (event.data.action === 'trackinfo') {
  43712. onTrackInfo(event.data.trackInfo);
  43713. }
  43714. if (event.data.action === 'gopInfo') {
  43715. handleGopInfo_(event, transmuxedData);
  43716. }
  43717. if (event.data.action === 'audioTimingInfo') {
  43718. onAudioTimingInfo(event.data.audioTimingInfo);
  43719. }
  43720. if (event.data.action === 'videoTimingInfo') {
  43721. onVideoTimingInfo(event.data.videoTimingInfo);
  43722. }
  43723. if (event.data.action === 'videoSegmentTimingInfo') {
  43724. onVideoSegmentTimingInfo(event.data.videoSegmentTimingInfo);
  43725. }
  43726. if (event.data.action === 'audioSegmentTimingInfo') {
  43727. onAudioSegmentTimingInfo(event.data.audioSegmentTimingInfo);
  43728. }
  43729. if (event.data.action === 'id3Frame') {
  43730. onId3([event.data.id3Frame], event.data.id3Frame.dispatchType);
  43731. }
  43732. if (event.data.action === 'caption') {
  43733. onCaptions(event.data.caption);
  43734. }
  43735. if (event.data.action === 'endedtimeline') {
  43736. waitForEndedTimelineEvent = false;
  43737. onEndedTimeline();
  43738. }
  43739. if (event.data.action === 'log') {
  43740. onTransmuxerLog(event.data.log);
  43741. } // wait for the transmuxed event since we may have audio and video
  43742. if (event.data.type !== 'transmuxed') {
  43743. return;
  43744. } // If the "endedtimeline" event has not yet fired, and this segment represents the end
  43745. // of a timeline, that means there may still be data events before the segment
  43746. // processing can be considerred complete. In that case, the final event should be
  43747. // an "endedtimeline" event with the type "transmuxed."
  43748. if (waitForEndedTimelineEvent) {
  43749. return;
  43750. }
  43751. transmuxer.onmessage = null;
  43752. handleDone_({
  43753. transmuxedData: transmuxedData,
  43754. callback: onDone
  43755. });
  43756. /* eslint-disable no-use-before-define */
  43757. dequeue(transmuxer);
  43758. /* eslint-enable */
  43759. };
  43760. transmuxer.onmessage = handleMessage;
  43761. if (audioAppendStart) {
  43762. transmuxer.postMessage({
  43763. action: 'setAudioAppendStart',
  43764. appendStart: audioAppendStart
  43765. });
  43766. } // allow empty arrays to be passed to clear out GOPs
  43767. if (Array.isArray(gopsToAlignWith)) {
  43768. transmuxer.postMessage({
  43769. action: 'alignGopsWith',
  43770. gopsToAlignWith: gopsToAlignWith
  43771. });
  43772. }
  43773. if (typeof remux !== 'undefined') {
  43774. transmuxer.postMessage({
  43775. action: 'setRemux',
  43776. remux: remux
  43777. });
  43778. }
  43779. if (bytes.byteLength) {
  43780. var buffer = bytes instanceof ArrayBuffer ? bytes : bytes.buffer;
  43781. var byteOffset = bytes instanceof ArrayBuffer ? 0 : bytes.byteOffset;
  43782. transmuxer.postMessage({
  43783. action: 'push',
  43784. // Send the typed-array of data as an ArrayBuffer so that
  43785. // it can be sent as a "Transferable" and avoid the costly
  43786. // memory copy
  43787. data: buffer,
  43788. // To recreate the original typed-array, we need information
  43789. // about what portion of the ArrayBuffer it was a view into
  43790. byteOffset: byteOffset,
  43791. byteLength: bytes.byteLength
  43792. }, [buffer]);
  43793. }
  43794. if (isEndOfTimeline) {
  43795. transmuxer.postMessage({
  43796. action: 'endTimeline'
  43797. });
  43798. } // even if we didn't push any bytes, we have to make sure we flush in case we reached
  43799. // the end of the segment
  43800. transmuxer.postMessage({
  43801. action: 'flush'
  43802. });
  43803. };
  43804. var dequeue = function dequeue(transmuxer) {
  43805. transmuxer.currentTransmux = null;
  43806. if (transmuxer.transmuxQueue.length) {
  43807. transmuxer.currentTransmux = transmuxer.transmuxQueue.shift();
  43808. if (typeof transmuxer.currentTransmux === 'function') {
  43809. transmuxer.currentTransmux();
  43810. } else {
  43811. processTransmux(transmuxer.currentTransmux);
  43812. }
  43813. }
  43814. };
  43815. var processAction = function processAction(transmuxer, action) {
  43816. transmuxer.postMessage({
  43817. action: action
  43818. });
  43819. dequeue(transmuxer);
  43820. };
  43821. var enqueueAction = function enqueueAction(action, transmuxer) {
  43822. if (!transmuxer.currentTransmux) {
  43823. transmuxer.currentTransmux = action;
  43824. processAction(transmuxer, action);
  43825. return;
  43826. }
  43827. transmuxer.transmuxQueue.push(processAction.bind(null, transmuxer, action));
  43828. };
  43829. var reset = function reset(transmuxer) {
  43830. enqueueAction('reset', transmuxer);
  43831. };
  43832. var endTimeline = function endTimeline(transmuxer) {
  43833. enqueueAction('endTimeline', transmuxer);
  43834. };
  43835. var transmux = function transmux(options) {
  43836. if (!options.transmuxer.currentTransmux) {
  43837. options.transmuxer.currentTransmux = options;
  43838. processTransmux(options);
  43839. return;
  43840. }
  43841. options.transmuxer.transmuxQueue.push(options);
  43842. };
  43843. var createTransmuxer = function createTransmuxer(options) {
  43844. var transmuxer = new TransmuxWorker();
  43845. transmuxer.currentTransmux = null;
  43846. transmuxer.transmuxQueue = [];
  43847. var term = transmuxer.terminate;
  43848. transmuxer.terminate = function () {
  43849. transmuxer.currentTransmux = null;
  43850. transmuxer.transmuxQueue.length = 0;
  43851. return term.call(transmuxer);
  43852. };
  43853. transmuxer.postMessage({
  43854. action: 'init',
  43855. options: options
  43856. });
  43857. return transmuxer;
  43858. };
  43859. var segmentTransmuxer = {
  43860. reset: reset,
  43861. endTimeline: endTimeline,
  43862. transmux: transmux,
  43863. createTransmuxer: createTransmuxer
  43864. };
  43865. var workerCallback = function workerCallback(options) {
  43866. var transmuxer = options.transmuxer;
  43867. var endAction = options.endAction || options.action;
  43868. var callback = options.callback;
  43869. var message = _extends_1({}, options, {
  43870. endAction: null,
  43871. transmuxer: null,
  43872. callback: null
  43873. });
  43874. var listenForEndEvent = function listenForEndEvent(event) {
  43875. if (event.data.action !== endAction) {
  43876. return;
  43877. }
  43878. transmuxer.removeEventListener('message', listenForEndEvent); // transfer ownership of bytes back to us.
  43879. if (event.data.data) {
  43880. event.data.data = new Uint8Array(event.data.data, options.byteOffset || 0, options.byteLength || event.data.data.byteLength);
  43881. if (options.data) {
  43882. options.data = event.data.data;
  43883. }
  43884. }
  43885. callback(event.data);
  43886. };
  43887. transmuxer.addEventListener('message', listenForEndEvent);
  43888. if (options.data) {
  43889. var isArrayBuffer = options.data instanceof ArrayBuffer;
  43890. message.byteOffset = isArrayBuffer ? 0 : options.data.byteOffset;
  43891. message.byteLength = options.data.byteLength;
  43892. var transfers = [isArrayBuffer ? options.data : options.data.buffer];
  43893. transmuxer.postMessage(message, transfers);
  43894. } else {
  43895. transmuxer.postMessage(message);
  43896. }
  43897. };
  43898. var REQUEST_ERRORS = {
  43899. FAILURE: 2,
  43900. TIMEOUT: -101,
  43901. ABORTED: -102
  43902. };
  43903. /**
  43904. * Abort all requests
  43905. *
  43906. * @param {Object} activeXhrs - an object that tracks all XHR requests
  43907. */
  43908. var abortAll = function abortAll(activeXhrs) {
  43909. activeXhrs.forEach(function (xhr) {
  43910. xhr.abort();
  43911. });
  43912. };
  43913. /**
  43914. * Gather important bandwidth stats once a request has completed
  43915. *
  43916. * @param {Object} request - the XHR request from which to gather stats
  43917. */
  43918. var getRequestStats = function getRequestStats(request) {
  43919. return {
  43920. bandwidth: request.bandwidth,
  43921. bytesReceived: request.bytesReceived || 0,
  43922. roundTripTime: request.roundTripTime || 0
  43923. };
  43924. };
  43925. /**
  43926. * If possible gather bandwidth stats as a request is in
  43927. * progress
  43928. *
  43929. * @param {Event} progressEvent - an event object from an XHR's progress event
  43930. */
  43931. var getProgressStats = function getProgressStats(progressEvent) {
  43932. var request = progressEvent.target;
  43933. var roundTripTime = Date.now() - request.requestTime;
  43934. var stats = {
  43935. bandwidth: Infinity,
  43936. bytesReceived: 0,
  43937. roundTripTime: roundTripTime || 0
  43938. };
  43939. stats.bytesReceived = progressEvent.loaded; // This can result in Infinity if stats.roundTripTime is 0 but that is ok
  43940. // because we should only use bandwidth stats on progress to determine when
  43941. // abort a request early due to insufficient bandwidth
  43942. stats.bandwidth = Math.floor(stats.bytesReceived / stats.roundTripTime * 8 * 1000);
  43943. return stats;
  43944. };
  43945. /**
  43946. * Handle all error conditions in one place and return an object
  43947. * with all the information
  43948. *
  43949. * @param {Error|null} error - if non-null signals an error occured with the XHR
  43950. * @param {Object} request - the XHR request that possibly generated the error
  43951. */
  43952. var handleErrors = function handleErrors(error, request) {
  43953. if (request.timedout) {
  43954. return {
  43955. status: request.status,
  43956. message: 'HLS request timed-out at URL: ' + request.uri,
  43957. code: REQUEST_ERRORS.TIMEOUT,
  43958. xhr: request
  43959. };
  43960. }
  43961. if (request.aborted) {
  43962. return {
  43963. status: request.status,
  43964. message: 'HLS request aborted at URL: ' + request.uri,
  43965. code: REQUEST_ERRORS.ABORTED,
  43966. xhr: request
  43967. };
  43968. }
  43969. if (error) {
  43970. return {
  43971. status: request.status,
  43972. message: 'HLS request errored at URL: ' + request.uri,
  43973. code: REQUEST_ERRORS.FAILURE,
  43974. xhr: request
  43975. };
  43976. }
  43977. if (request.responseType === 'arraybuffer' && request.response.byteLength === 0) {
  43978. return {
  43979. status: request.status,
  43980. message: 'Empty HLS response at URL: ' + request.uri,
  43981. code: REQUEST_ERRORS.FAILURE,
  43982. xhr: request
  43983. };
  43984. }
  43985. return null;
  43986. };
  43987. /**
  43988. * Handle responses for key data and convert the key data to the correct format
  43989. * for the decryption step later
  43990. *
  43991. * @param {Object} segment - a simplified copy of the segmentInfo object
  43992. * from SegmentLoader
  43993. * @param {Array} objects - objects to add the key bytes to.
  43994. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  43995. * this request
  43996. */
  43997. var handleKeyResponse = function handleKeyResponse(segment, objects, finishProcessingFn) {
  43998. return function (error, request) {
  43999. var response = request.response;
  44000. var errorObj = handleErrors(error, request);
  44001. if (errorObj) {
  44002. return finishProcessingFn(errorObj, segment);
  44003. }
  44004. if (response.byteLength !== 16) {
  44005. return finishProcessingFn({
  44006. status: request.status,
  44007. message: 'Invalid HLS key at URL: ' + request.uri,
  44008. code: REQUEST_ERRORS.FAILURE,
  44009. xhr: request
  44010. }, segment);
  44011. }
  44012. var view = new DataView(response);
  44013. var bytes = new Uint32Array([view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12)]);
  44014. for (var i = 0; i < objects.length; i++) {
  44015. objects[i].bytes = bytes;
  44016. }
  44017. return finishProcessingFn(null, segment);
  44018. };
  44019. };
  44020. var parseInitSegment = function parseInitSegment(segment, _callback) {
  44021. var type = detectContainerForBytes(segment.map.bytes); // TODO: We should also handle ts init segments here, but we
  44022. // only know how to parse mp4 init segments at the moment
  44023. if (type !== 'mp4') {
  44024. var uri = segment.map.resolvedUri || segment.map.uri;
  44025. return _callback({
  44026. internal: true,
  44027. message: "Found unsupported " + (type || 'unknown') + " container for initialization segment at URL: " + uri,
  44028. code: REQUEST_ERRORS.FAILURE
  44029. });
  44030. }
  44031. workerCallback({
  44032. action: 'probeMp4Tracks',
  44033. data: segment.map.bytes,
  44034. transmuxer: segment.transmuxer,
  44035. callback: function callback(_ref) {
  44036. var tracks = _ref.tracks,
  44037. data = _ref.data; // transfer bytes back to us
  44038. segment.map.bytes = data;
  44039. tracks.forEach(function (track) {
  44040. segment.map.tracks = segment.map.tracks || {}; // only support one track of each type for now
  44041. if (segment.map.tracks[track.type]) {
  44042. return;
  44043. }
  44044. segment.map.tracks[track.type] = track;
  44045. if (typeof track.id === 'number' && track.timescale) {
  44046. segment.map.timescales = segment.map.timescales || {};
  44047. segment.map.timescales[track.id] = track.timescale;
  44048. }
  44049. });
  44050. return _callback(null);
  44051. }
  44052. });
  44053. };
  44054. /**
  44055. * Handle init-segment responses
  44056. *
  44057. * @param {Object} segment - a simplified copy of the segmentInfo object
  44058. * from SegmentLoader
  44059. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  44060. * this request
  44061. */
  44062. var handleInitSegmentResponse = function handleInitSegmentResponse(_ref2) {
  44063. var segment = _ref2.segment,
  44064. finishProcessingFn = _ref2.finishProcessingFn;
  44065. return function (error, request) {
  44066. var errorObj = handleErrors(error, request);
  44067. if (errorObj) {
  44068. return finishProcessingFn(errorObj, segment);
  44069. }
  44070. var bytes = new Uint8Array(request.response); // init segment is encypted, we will have to wait
  44071. // until the key request is done to decrypt.
  44072. if (segment.map.key) {
  44073. segment.map.encryptedBytes = bytes;
  44074. return finishProcessingFn(null, segment);
  44075. }
  44076. segment.map.bytes = bytes;
  44077. parseInitSegment(segment, function (parseError) {
  44078. if (parseError) {
  44079. parseError.xhr = request;
  44080. parseError.status = request.status;
  44081. return finishProcessingFn(parseError, segment);
  44082. }
  44083. finishProcessingFn(null, segment);
  44084. });
  44085. };
  44086. };
  44087. /**
  44088. * Response handler for segment-requests being sure to set the correct
  44089. * property depending on whether the segment is encryped or not
  44090. * Also records and keeps track of stats that are used for ABR purposes
  44091. *
  44092. * @param {Object} segment - a simplified copy of the segmentInfo object
  44093. * from SegmentLoader
  44094. * @param {Function} finishProcessingFn - a callback to execute to continue processing
  44095. * this request
  44096. */
  44097. var handleSegmentResponse = function handleSegmentResponse(_ref3) {
  44098. var segment = _ref3.segment,
  44099. finishProcessingFn = _ref3.finishProcessingFn,
  44100. responseType = _ref3.responseType;
  44101. return function (error, request) {
  44102. var errorObj = handleErrors(error, request);
  44103. if (errorObj) {
  44104. return finishProcessingFn(errorObj, segment);
  44105. }
  44106. var newBytes = // although responseText "should" exist, this guard serves to prevent an error being
  44107. // thrown for two primary cases:
  44108. // 1. the mime type override stops working, or is not implemented for a specific
  44109. // browser
  44110. // 2. when using mock XHR libraries like sinon that do not allow the override behavior
  44111. responseType === 'arraybuffer' || !request.responseText ? request.response : stringToArrayBuffer(request.responseText.substring(segment.lastReachedChar || 0));
  44112. segment.stats = getRequestStats(request);
  44113. if (segment.key) {
  44114. segment.encryptedBytes = new Uint8Array(newBytes);
  44115. } else {
  44116. segment.bytes = new Uint8Array(newBytes);
  44117. }
  44118. return finishProcessingFn(null, segment);
  44119. };
  44120. };
  44121. var transmuxAndNotify = function transmuxAndNotify(_ref4) {
  44122. var segment = _ref4.segment,
  44123. bytes = _ref4.bytes,
  44124. trackInfoFn = _ref4.trackInfoFn,
  44125. timingInfoFn = _ref4.timingInfoFn,
  44126. videoSegmentTimingInfoFn = _ref4.videoSegmentTimingInfoFn,
  44127. audioSegmentTimingInfoFn = _ref4.audioSegmentTimingInfoFn,
  44128. id3Fn = _ref4.id3Fn,
  44129. captionsFn = _ref4.captionsFn,
  44130. isEndOfTimeline = _ref4.isEndOfTimeline,
  44131. endedTimelineFn = _ref4.endedTimelineFn,
  44132. dataFn = _ref4.dataFn,
  44133. doneFn = _ref4.doneFn,
  44134. onTransmuxerLog = _ref4.onTransmuxerLog;
  44135. var fmp4Tracks = segment.map && segment.map.tracks || {};
  44136. var isMuxed = Boolean(fmp4Tracks.audio && fmp4Tracks.video); // Keep references to each function so we can null them out after we're done with them.
  44137. // One reason for this is that in the case of full segments, we want to trust start
  44138. // times from the probe, rather than the transmuxer.
  44139. var audioStartFn = timingInfoFn.bind(null, segment, 'audio', 'start');
  44140. var audioEndFn = timingInfoFn.bind(null, segment, 'audio', 'end');
  44141. var videoStartFn = timingInfoFn.bind(null, segment, 'video', 'start');
  44142. var videoEndFn = timingInfoFn.bind(null, segment, 'video', 'end');
  44143. var finish = function finish() {
  44144. return transmux({
  44145. bytes: bytes,
  44146. transmuxer: segment.transmuxer,
  44147. audioAppendStart: segment.audioAppendStart,
  44148. gopsToAlignWith: segment.gopsToAlignWith,
  44149. remux: isMuxed,
  44150. onData: function onData(result) {
  44151. result.type = result.type === 'combined' ? 'video' : result.type;
  44152. dataFn(segment, result);
  44153. },
  44154. onTrackInfo: function onTrackInfo(trackInfo) {
  44155. if (trackInfoFn) {
  44156. if (isMuxed) {
  44157. trackInfo.isMuxed = true;
  44158. }
  44159. trackInfoFn(segment, trackInfo);
  44160. }
  44161. },
  44162. onAudioTimingInfo: function onAudioTimingInfo(audioTimingInfo) {
  44163. // we only want the first start value we encounter
  44164. if (audioStartFn && typeof audioTimingInfo.start !== 'undefined') {
  44165. audioStartFn(audioTimingInfo.start);
  44166. audioStartFn = null;
  44167. } // we want to continually update the end time
  44168. if (audioEndFn && typeof audioTimingInfo.end !== 'undefined') {
  44169. audioEndFn(audioTimingInfo.end);
  44170. }
  44171. },
  44172. onVideoTimingInfo: function onVideoTimingInfo(videoTimingInfo) {
  44173. // we only want the first start value we encounter
  44174. if (videoStartFn && typeof videoTimingInfo.start !== 'undefined') {
  44175. videoStartFn(videoTimingInfo.start);
  44176. videoStartFn = null;
  44177. } // we want to continually update the end time
  44178. if (videoEndFn && typeof videoTimingInfo.end !== 'undefined') {
  44179. videoEndFn(videoTimingInfo.end);
  44180. }
  44181. },
  44182. onVideoSegmentTimingInfo: function onVideoSegmentTimingInfo(videoSegmentTimingInfo) {
  44183. videoSegmentTimingInfoFn(videoSegmentTimingInfo);
  44184. },
  44185. onAudioSegmentTimingInfo: function onAudioSegmentTimingInfo(audioSegmentTimingInfo) {
  44186. audioSegmentTimingInfoFn(audioSegmentTimingInfo);
  44187. },
  44188. onId3: function onId3(id3Frames, dispatchType) {
  44189. id3Fn(segment, id3Frames, dispatchType);
  44190. },
  44191. onCaptions: function onCaptions(captions) {
  44192. captionsFn(segment, [captions]);
  44193. },
  44194. isEndOfTimeline: isEndOfTimeline,
  44195. onEndedTimeline: function onEndedTimeline() {
  44196. endedTimelineFn();
  44197. },
  44198. onTransmuxerLog: onTransmuxerLog,
  44199. onDone: function onDone(result) {
  44200. if (!doneFn) {
  44201. return;
  44202. }
  44203. result.type = result.type === 'combined' ? 'video' : result.type;
  44204. doneFn(null, segment, result);
  44205. }
  44206. });
  44207. }; // In the transmuxer, we don't yet have the ability to extract a "proper" start time.
  44208. // Meaning cached frame data may corrupt our notion of where this segment
  44209. // really starts. To get around this, probe for the info needed.
  44210. workerCallback({
  44211. action: 'probeTs',
  44212. transmuxer: segment.transmuxer,
  44213. data: bytes,
  44214. baseStartTime: segment.baseStartTime,
  44215. callback: function callback(data) {
  44216. segment.bytes = bytes = data.data;
  44217. var probeResult = data.result;
  44218. if (probeResult) {
  44219. trackInfoFn(segment, {
  44220. hasAudio: probeResult.hasAudio,
  44221. hasVideo: probeResult.hasVideo,
  44222. isMuxed: isMuxed
  44223. });
  44224. trackInfoFn = null;
  44225. if (probeResult.hasAudio && !isMuxed) {
  44226. audioStartFn(probeResult.audioStart);
  44227. }
  44228. if (probeResult.hasVideo) {
  44229. videoStartFn(probeResult.videoStart);
  44230. }
  44231. audioStartFn = null;
  44232. videoStartFn = null;
  44233. }
  44234. finish();
  44235. }
  44236. });
  44237. };
  44238. var handleSegmentBytes = function handleSegmentBytes(_ref5) {
  44239. var segment = _ref5.segment,
  44240. bytes = _ref5.bytes,
  44241. trackInfoFn = _ref5.trackInfoFn,
  44242. timingInfoFn = _ref5.timingInfoFn,
  44243. videoSegmentTimingInfoFn = _ref5.videoSegmentTimingInfoFn,
  44244. audioSegmentTimingInfoFn = _ref5.audioSegmentTimingInfoFn,
  44245. id3Fn = _ref5.id3Fn,
  44246. captionsFn = _ref5.captionsFn,
  44247. isEndOfTimeline = _ref5.isEndOfTimeline,
  44248. endedTimelineFn = _ref5.endedTimelineFn,
  44249. dataFn = _ref5.dataFn,
  44250. doneFn = _ref5.doneFn,
  44251. onTransmuxerLog = _ref5.onTransmuxerLog;
  44252. var bytesAsUint8Array = new Uint8Array(bytes); // TODO:
  44253. // We should have a handler that fetches the number of bytes required
  44254. // to check if something is fmp4. This will allow us to save bandwidth
  44255. // because we can only blacklist a playlist and abort requests
  44256. // by codec after trackinfo triggers.
  44257. if (isLikelyFmp4MediaSegment(bytesAsUint8Array)) {
  44258. segment.isFmp4 = true;
  44259. var tracks = segment.map.tracks;
  44260. var trackInfo = {
  44261. isFmp4: true,
  44262. hasVideo: !!tracks.video,
  44263. hasAudio: !!tracks.audio
  44264. }; // if we have a audio track, with a codec that is not set to
  44265. // encrypted audio
  44266. if (tracks.audio && tracks.audio.codec && tracks.audio.codec !== 'enca') {
  44267. trackInfo.audioCodec = tracks.audio.codec;
  44268. } // if we have a video track, with a codec that is not set to
  44269. // encrypted video
  44270. if (tracks.video && tracks.video.codec && tracks.video.codec !== 'encv') {
  44271. trackInfo.videoCodec = tracks.video.codec;
  44272. }
  44273. if (tracks.video && tracks.audio) {
  44274. trackInfo.isMuxed = true;
  44275. } // since we don't support appending fmp4 data on progress, we know we have the full
  44276. // segment here
  44277. trackInfoFn(segment, trackInfo); // The probe doesn't provide the segment end time, so only callback with the start
  44278. // time. The end time can be roughly calculated by the receiver using the duration.
  44279. //
  44280. // Note that the start time returned by the probe reflects the baseMediaDecodeTime, as
  44281. // that is the true start of the segment (where the playback engine should begin
  44282. // decoding).
  44283. var finishLoading = function finishLoading(captions) {
  44284. // if the track still has audio at this point it is only possible
  44285. // for it to be audio only. See `tracks.video && tracks.audio` if statement
  44286. // above.
  44287. // we make sure to use segment.bytes here as that
  44288. dataFn(segment, {
  44289. data: bytesAsUint8Array,
  44290. type: trackInfo.hasAudio && !trackInfo.isMuxed ? 'audio' : 'video'
  44291. });
  44292. if (captions && captions.length) {
  44293. captionsFn(segment, captions);
  44294. }
  44295. doneFn(null, segment, {});
  44296. };
  44297. workerCallback({
  44298. action: 'probeMp4StartTime',
  44299. timescales: segment.map.timescales,
  44300. data: bytesAsUint8Array,
  44301. transmuxer: segment.transmuxer,
  44302. callback: function callback(_ref6) {
  44303. var data = _ref6.data,
  44304. startTime = _ref6.startTime; // transfer bytes back to us
  44305. bytes = data.buffer;
  44306. segment.bytes = bytesAsUint8Array = data;
  44307. if (trackInfo.hasAudio && !trackInfo.isMuxed) {
  44308. timingInfoFn(segment, 'audio', 'start', startTime);
  44309. }
  44310. if (trackInfo.hasVideo) {
  44311. timingInfoFn(segment, 'video', 'start', startTime);
  44312. } // Run through the CaptionParser in case there are captions.
  44313. // Initialize CaptionParser if it hasn't been yet
  44314. if (!tracks.video || !data.byteLength || !segment.transmuxer) {
  44315. finishLoading();
  44316. return;
  44317. }
  44318. workerCallback({
  44319. action: 'pushMp4Captions',
  44320. endAction: 'mp4Captions',
  44321. transmuxer: segment.transmuxer,
  44322. data: bytesAsUint8Array,
  44323. timescales: segment.map.timescales,
  44324. trackIds: [tracks.video.id],
  44325. callback: function callback(message) {
  44326. // transfer bytes back to us
  44327. bytes = message.data.buffer;
  44328. segment.bytes = bytesAsUint8Array = message.data;
  44329. message.logs.forEach(function (log) {
  44330. onTransmuxerLog(videojs.mergeOptions(log, {
  44331. stream: 'mp4CaptionParser'
  44332. }));
  44333. });
  44334. finishLoading(message.captions);
  44335. }
  44336. });
  44337. }
  44338. });
  44339. return;
  44340. } // VTT or other segments that don't need processing
  44341. if (!segment.transmuxer) {
  44342. doneFn(null, segment, {});
  44343. return;
  44344. }
  44345. if (typeof segment.container === 'undefined') {
  44346. segment.container = detectContainerForBytes(bytesAsUint8Array);
  44347. }
  44348. if (segment.container !== 'ts' && segment.container !== 'aac') {
  44349. trackInfoFn(segment, {
  44350. hasAudio: false,
  44351. hasVideo: false
  44352. });
  44353. doneFn(null, segment, {});
  44354. return;
  44355. } // ts or aac
  44356. transmuxAndNotify({
  44357. segment: segment,
  44358. bytes: bytes,
  44359. trackInfoFn: trackInfoFn,
  44360. timingInfoFn: timingInfoFn,
  44361. videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
  44362. audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
  44363. id3Fn: id3Fn,
  44364. captionsFn: captionsFn,
  44365. isEndOfTimeline: isEndOfTimeline,
  44366. endedTimelineFn: endedTimelineFn,
  44367. dataFn: dataFn,
  44368. doneFn: doneFn,
  44369. onTransmuxerLog: onTransmuxerLog
  44370. });
  44371. };
  44372. var decrypt = function decrypt(_ref7, callback) {
  44373. var id = _ref7.id,
  44374. key = _ref7.key,
  44375. encryptedBytes = _ref7.encryptedBytes,
  44376. decryptionWorker = _ref7.decryptionWorker;
  44377. var decryptionHandler = function decryptionHandler(event) {
  44378. if (event.data.source === id) {
  44379. decryptionWorker.removeEventListener('message', decryptionHandler);
  44380. var decrypted = event.data.decrypted;
  44381. callback(new Uint8Array(decrypted.bytes, decrypted.byteOffset, decrypted.byteLength));
  44382. }
  44383. };
  44384. decryptionWorker.addEventListener('message', decryptionHandler);
  44385. var keyBytes;
  44386. if (key.bytes.slice) {
  44387. keyBytes = key.bytes.slice();
  44388. } else {
  44389. keyBytes = new Uint32Array(Array.prototype.slice.call(key.bytes));
  44390. } // incrementally decrypt the bytes
  44391. decryptionWorker.postMessage(createTransferableMessage({
  44392. source: id,
  44393. encrypted: encryptedBytes,
  44394. key: keyBytes,
  44395. iv: key.iv
  44396. }), [encryptedBytes.buffer, keyBytes.buffer]);
  44397. };
  44398. /**
  44399. * Decrypt the segment via the decryption web worker
  44400. *
  44401. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  44402. * routines
  44403. * @param {Object} segment - a simplified copy of the segmentInfo object
  44404. * from SegmentLoader
  44405. * @param {Function} trackInfoFn - a callback that receives track info
  44406. * @param {Function} timingInfoFn - a callback that receives timing info
  44407. * @param {Function} videoSegmentTimingInfoFn
  44408. * a callback that receives video timing info based on media times and
  44409. * any adjustments made by the transmuxer
  44410. * @param {Function} audioSegmentTimingInfoFn
  44411. * a callback that receives audio timing info based on media times and
  44412. * any adjustments made by the transmuxer
  44413. * @param {boolean} isEndOfTimeline
  44414. * true if this segment represents the last segment in a timeline
  44415. * @param {Function} endedTimelineFn
  44416. * a callback made when a timeline is ended, will only be called if
  44417. * isEndOfTimeline is true
  44418. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  44419. * and ready to use
  44420. * @param {Function} doneFn - a callback that is executed after decryption has completed
  44421. */
  44422. var decryptSegment = function decryptSegment(_ref8) {
  44423. var decryptionWorker = _ref8.decryptionWorker,
  44424. segment = _ref8.segment,
  44425. trackInfoFn = _ref8.trackInfoFn,
  44426. timingInfoFn = _ref8.timingInfoFn,
  44427. videoSegmentTimingInfoFn = _ref8.videoSegmentTimingInfoFn,
  44428. audioSegmentTimingInfoFn = _ref8.audioSegmentTimingInfoFn,
  44429. id3Fn = _ref8.id3Fn,
  44430. captionsFn = _ref8.captionsFn,
  44431. isEndOfTimeline = _ref8.isEndOfTimeline,
  44432. endedTimelineFn = _ref8.endedTimelineFn,
  44433. dataFn = _ref8.dataFn,
  44434. doneFn = _ref8.doneFn,
  44435. onTransmuxerLog = _ref8.onTransmuxerLog;
  44436. decrypt({
  44437. id: segment.requestId,
  44438. key: segment.key,
  44439. encryptedBytes: segment.encryptedBytes,
  44440. decryptionWorker: decryptionWorker
  44441. }, function (decryptedBytes) {
  44442. segment.bytes = decryptedBytes;
  44443. handleSegmentBytes({
  44444. segment: segment,
  44445. bytes: segment.bytes,
  44446. trackInfoFn: trackInfoFn,
  44447. timingInfoFn: timingInfoFn,
  44448. videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
  44449. audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
  44450. id3Fn: id3Fn,
  44451. captionsFn: captionsFn,
  44452. isEndOfTimeline: isEndOfTimeline,
  44453. endedTimelineFn: endedTimelineFn,
  44454. dataFn: dataFn,
  44455. doneFn: doneFn,
  44456. onTransmuxerLog: onTransmuxerLog
  44457. });
  44458. });
  44459. };
  44460. /**
  44461. * This function waits for all XHRs to finish (with either success or failure)
  44462. * before continueing processing via it's callback. The function gathers errors
  44463. * from each request into a single errors array so that the error status for
  44464. * each request can be examined later.
  44465. *
  44466. * @param {Object} activeXhrs - an object that tracks all XHR requests
  44467. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128 decryption
  44468. * routines
  44469. * @param {Function} trackInfoFn - a callback that receives track info
  44470. * @param {Function} timingInfoFn - a callback that receives timing info
  44471. * @param {Function} videoSegmentTimingInfoFn
  44472. * a callback that receives video timing info based on media times and
  44473. * any adjustments made by the transmuxer
  44474. * @param {Function} audioSegmentTimingInfoFn
  44475. * a callback that receives audio timing info based on media times and
  44476. * any adjustments made by the transmuxer
  44477. * @param {Function} id3Fn - a callback that receives ID3 metadata
  44478. * @param {Function} captionsFn - a callback that receives captions
  44479. * @param {boolean} isEndOfTimeline
  44480. * true if this segment represents the last segment in a timeline
  44481. * @param {Function} endedTimelineFn
  44482. * a callback made when a timeline is ended, will only be called if
  44483. * isEndOfTimeline is true
  44484. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  44485. * and ready to use
  44486. * @param {Function} doneFn - a callback that is executed after all resources have been
  44487. * downloaded and any decryption completed
  44488. */
  44489. var waitForCompletion = function waitForCompletion(_ref9) {
  44490. var activeXhrs = _ref9.activeXhrs,
  44491. decryptionWorker = _ref9.decryptionWorker,
  44492. trackInfoFn = _ref9.trackInfoFn,
  44493. timingInfoFn = _ref9.timingInfoFn,
  44494. videoSegmentTimingInfoFn = _ref9.videoSegmentTimingInfoFn,
  44495. audioSegmentTimingInfoFn = _ref9.audioSegmentTimingInfoFn,
  44496. id3Fn = _ref9.id3Fn,
  44497. captionsFn = _ref9.captionsFn,
  44498. isEndOfTimeline = _ref9.isEndOfTimeline,
  44499. endedTimelineFn = _ref9.endedTimelineFn,
  44500. dataFn = _ref9.dataFn,
  44501. doneFn = _ref9.doneFn,
  44502. onTransmuxerLog = _ref9.onTransmuxerLog;
  44503. var count = 0;
  44504. var didError = false;
  44505. return function (error, segment) {
  44506. if (didError) {
  44507. return;
  44508. }
  44509. if (error) {
  44510. didError = true; // If there are errors, we have to abort any outstanding requests
  44511. abortAll(activeXhrs); // Even though the requests above are aborted, and in theory we could wait until we
  44512. // handle the aborted events from those requests, there are some cases where we may
  44513. // never get an aborted event. For instance, if the network connection is lost and
  44514. // there were two requests, the first may have triggered an error immediately, while
  44515. // the second request remains unsent. In that case, the aborted algorithm will not
  44516. // trigger an abort: see https://xhr.spec.whatwg.org/#the-abort()-method
  44517. //
  44518. // We also can't rely on the ready state of the XHR, since the request that
  44519. // triggered the connection error may also show as a ready state of 0 (unsent).
  44520. // Therefore, we have to finish this group of requests immediately after the first
  44521. // seen error.
  44522. return doneFn(error, segment);
  44523. }
  44524. count += 1;
  44525. if (count === activeXhrs.length) {
  44526. var segmentFinish = function segmentFinish() {
  44527. if (segment.encryptedBytes) {
  44528. return decryptSegment({
  44529. decryptionWorker: decryptionWorker,
  44530. segment: segment,
  44531. trackInfoFn: trackInfoFn,
  44532. timingInfoFn: timingInfoFn,
  44533. videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
  44534. audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
  44535. id3Fn: id3Fn,
  44536. captionsFn: captionsFn,
  44537. isEndOfTimeline: isEndOfTimeline,
  44538. endedTimelineFn: endedTimelineFn,
  44539. dataFn: dataFn,
  44540. doneFn: doneFn,
  44541. onTransmuxerLog: onTransmuxerLog
  44542. });
  44543. } // Otherwise, everything is ready just continue
  44544. handleSegmentBytes({
  44545. segment: segment,
  44546. bytes: segment.bytes,
  44547. trackInfoFn: trackInfoFn,
  44548. timingInfoFn: timingInfoFn,
  44549. videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
  44550. audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
  44551. id3Fn: id3Fn,
  44552. captionsFn: captionsFn,
  44553. isEndOfTimeline: isEndOfTimeline,
  44554. endedTimelineFn: endedTimelineFn,
  44555. dataFn: dataFn,
  44556. doneFn: doneFn,
  44557. onTransmuxerLog: onTransmuxerLog
  44558. });
  44559. }; // Keep track of when *all* of the requests have completed
  44560. segment.endOfAllRequests = Date.now();
  44561. if (segment.map && segment.map.encryptedBytes && !segment.map.bytes) {
  44562. return decrypt({
  44563. decryptionWorker: decryptionWorker,
  44564. // add -init to the "id" to differentiate between segment
  44565. // and init segment decryption, just in case they happen
  44566. // at the same time at some point in the future.
  44567. id: segment.requestId + '-init',
  44568. encryptedBytes: segment.map.encryptedBytes,
  44569. key: segment.map.key
  44570. }, function (decryptedBytes) {
  44571. segment.map.bytes = decryptedBytes;
  44572. parseInitSegment(segment, function (parseError) {
  44573. if (parseError) {
  44574. abortAll(activeXhrs);
  44575. return doneFn(parseError, segment);
  44576. }
  44577. segmentFinish();
  44578. });
  44579. });
  44580. }
  44581. segmentFinish();
  44582. }
  44583. };
  44584. };
  44585. /**
  44586. * Calls the abort callback if any request within the batch was aborted. Will only call
  44587. * the callback once per batch of requests, even if multiple were aborted.
  44588. *
  44589. * @param {Object} loadendState - state to check to see if the abort function was called
  44590. * @param {Function} abortFn - callback to call for abort
  44591. */
  44592. var handleLoadEnd = function handleLoadEnd(_ref10) {
  44593. var loadendState = _ref10.loadendState,
  44594. abortFn = _ref10.abortFn;
  44595. return function (event) {
  44596. var request = event.target;
  44597. if (request.aborted && abortFn && !loadendState.calledAbortFn) {
  44598. abortFn();
  44599. loadendState.calledAbortFn = true;
  44600. }
  44601. };
  44602. };
  44603. /**
  44604. * Simple progress event callback handler that gathers some stats before
  44605. * executing a provided callback with the `segment` object
  44606. *
  44607. * @param {Object} segment - a simplified copy of the segmentInfo object
  44608. * from SegmentLoader
  44609. * @param {Function} progressFn - a callback that is executed each time a progress event
  44610. * is received
  44611. * @param {Function} trackInfoFn - a callback that receives track info
  44612. * @param {Function} timingInfoFn - a callback that receives timing info
  44613. * @param {Function} videoSegmentTimingInfoFn
  44614. * a callback that receives video timing info based on media times and
  44615. * any adjustments made by the transmuxer
  44616. * @param {Function} audioSegmentTimingInfoFn
  44617. * a callback that receives audio timing info based on media times and
  44618. * any adjustments made by the transmuxer
  44619. * @param {boolean} isEndOfTimeline
  44620. * true if this segment represents the last segment in a timeline
  44621. * @param {Function} endedTimelineFn
  44622. * a callback made when a timeline is ended, will only be called if
  44623. * isEndOfTimeline is true
  44624. * @param {Function} dataFn - a callback that is executed when segment bytes are available
  44625. * and ready to use
  44626. * @param {Event} event - the progress event object from XMLHttpRequest
  44627. */
  44628. var handleProgress = function handleProgress(_ref11) {
  44629. var segment = _ref11.segment,
  44630. progressFn = _ref11.progressFn;
  44631. _ref11.trackInfoFn;
  44632. _ref11.timingInfoFn;
  44633. _ref11.videoSegmentTimingInfoFn;
  44634. _ref11.audioSegmentTimingInfoFn;
  44635. _ref11.id3Fn;
  44636. _ref11.captionsFn;
  44637. _ref11.isEndOfTimeline;
  44638. _ref11.endedTimelineFn;
  44639. _ref11.dataFn;
  44640. return function (event) {
  44641. var request = event.target;
  44642. if (request.aborted) {
  44643. return;
  44644. }
  44645. segment.stats = videojs.mergeOptions(segment.stats, getProgressStats(event)); // record the time that we receive the first byte of data
  44646. if (!segment.stats.firstBytesReceivedAt && segment.stats.bytesReceived) {
  44647. segment.stats.firstBytesReceivedAt = Date.now();
  44648. }
  44649. return progressFn(event, segment);
  44650. };
  44651. };
  44652. /**
  44653. * Load all resources and does any processing necessary for a media-segment
  44654. *
  44655. * Features:
  44656. * decrypts the media-segment if it has a key uri and an iv
  44657. * aborts *all* requests if *any* one request fails
  44658. *
  44659. * The segment object, at minimum, has the following format:
  44660. * {
  44661. * resolvedUri: String,
  44662. * [transmuxer]: Object,
  44663. * [byterange]: {
  44664. * offset: Number,
  44665. * length: Number
  44666. * },
  44667. * [key]: {
  44668. * resolvedUri: String
  44669. * [byterange]: {
  44670. * offset: Number,
  44671. * length: Number
  44672. * },
  44673. * iv: {
  44674. * bytes: Uint32Array
  44675. * }
  44676. * },
  44677. * [map]: {
  44678. * resolvedUri: String,
  44679. * [byterange]: {
  44680. * offset: Number,
  44681. * length: Number
  44682. * },
  44683. * [bytes]: Uint8Array
  44684. * }
  44685. * }
  44686. * ...where [name] denotes optional properties
  44687. *
  44688. * @param {Function} xhr - an instance of the xhr wrapper in xhr.js
  44689. * @param {Object} xhrOptions - the base options to provide to all xhr requests
  44690. * @param {WebWorker} decryptionWorker - a WebWorker interface to AES-128
  44691. * decryption routines
  44692. * @param {Object} segment - a simplified copy of the segmentInfo object
  44693. * from SegmentLoader
  44694. * @param {Function} abortFn - a callback called (only once) if any piece of a request was
  44695. * aborted
  44696. * @param {Function} progressFn - a callback that receives progress events from the main
  44697. * segment's xhr request
  44698. * @param {Function} trackInfoFn - a callback that receives track info
  44699. * @param {Function} timingInfoFn - a callback that receives timing info
  44700. * @param {Function} videoSegmentTimingInfoFn
  44701. * a callback that receives video timing info based on media times and
  44702. * any adjustments made by the transmuxer
  44703. * @param {Function} audioSegmentTimingInfoFn
  44704. * a callback that receives audio timing info based on media times and
  44705. * any adjustments made by the transmuxer
  44706. * @param {Function} id3Fn - a callback that receives ID3 metadata
  44707. * @param {Function} captionsFn - a callback that receives captions
  44708. * @param {boolean} isEndOfTimeline
  44709. * true if this segment represents the last segment in a timeline
  44710. * @param {Function} endedTimelineFn
  44711. * a callback made when a timeline is ended, will only be called if
  44712. * isEndOfTimeline is true
  44713. * @param {Function} dataFn - a callback that receives data from the main segment's xhr
  44714. * request, transmuxed if needed
  44715. * @param {Function} doneFn - a callback that is executed only once all requests have
  44716. * succeeded or failed
  44717. * @return {Function} a function that, when invoked, immediately aborts all
  44718. * outstanding requests
  44719. */
  44720. var mediaSegmentRequest = function mediaSegmentRequest(_ref12) {
  44721. var xhr = _ref12.xhr,
  44722. xhrOptions = _ref12.xhrOptions,
  44723. decryptionWorker = _ref12.decryptionWorker,
  44724. segment = _ref12.segment,
  44725. abortFn = _ref12.abortFn,
  44726. progressFn = _ref12.progressFn,
  44727. trackInfoFn = _ref12.trackInfoFn,
  44728. timingInfoFn = _ref12.timingInfoFn,
  44729. videoSegmentTimingInfoFn = _ref12.videoSegmentTimingInfoFn,
  44730. audioSegmentTimingInfoFn = _ref12.audioSegmentTimingInfoFn,
  44731. id3Fn = _ref12.id3Fn,
  44732. captionsFn = _ref12.captionsFn,
  44733. isEndOfTimeline = _ref12.isEndOfTimeline,
  44734. endedTimelineFn = _ref12.endedTimelineFn,
  44735. dataFn = _ref12.dataFn,
  44736. doneFn = _ref12.doneFn,
  44737. onTransmuxerLog = _ref12.onTransmuxerLog;
  44738. var activeXhrs = [];
  44739. var finishProcessingFn = waitForCompletion({
  44740. activeXhrs: activeXhrs,
  44741. decryptionWorker: decryptionWorker,
  44742. trackInfoFn: trackInfoFn,
  44743. timingInfoFn: timingInfoFn,
  44744. videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
  44745. audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
  44746. id3Fn: id3Fn,
  44747. captionsFn: captionsFn,
  44748. isEndOfTimeline: isEndOfTimeline,
  44749. endedTimelineFn: endedTimelineFn,
  44750. dataFn: dataFn,
  44751. doneFn: doneFn,
  44752. onTransmuxerLog: onTransmuxerLog
  44753. }); // optionally, request the decryption key
  44754. if (segment.key && !segment.key.bytes) {
  44755. var objects = [segment.key];
  44756. if (segment.map && !segment.map.bytes && segment.map.key && segment.map.key.resolvedUri === segment.key.resolvedUri) {
  44757. objects.push(segment.map.key);
  44758. }
  44759. var keyRequestOptions = videojs.mergeOptions(xhrOptions, {
  44760. uri: segment.key.resolvedUri,
  44761. responseType: 'arraybuffer'
  44762. });
  44763. var keyRequestCallback = handleKeyResponse(segment, objects, finishProcessingFn);
  44764. var keyXhr = xhr(keyRequestOptions, keyRequestCallback);
  44765. activeXhrs.push(keyXhr);
  44766. } // optionally, request the associated media init segment
  44767. if (segment.map && !segment.map.bytes) {
  44768. var differentMapKey = segment.map.key && (!segment.key || segment.key.resolvedUri !== segment.map.key.resolvedUri);
  44769. if (differentMapKey) {
  44770. var mapKeyRequestOptions = videojs.mergeOptions(xhrOptions, {
  44771. uri: segment.map.key.resolvedUri,
  44772. responseType: 'arraybuffer'
  44773. });
  44774. var mapKeyRequestCallback = handleKeyResponse(segment, [segment.map.key], finishProcessingFn);
  44775. var mapKeyXhr = xhr(mapKeyRequestOptions, mapKeyRequestCallback);
  44776. activeXhrs.push(mapKeyXhr);
  44777. }
  44778. var initSegmentOptions = videojs.mergeOptions(xhrOptions, {
  44779. uri: segment.map.resolvedUri,
  44780. responseType: 'arraybuffer',
  44781. headers: segmentXhrHeaders(segment.map)
  44782. });
  44783. var initSegmentRequestCallback = handleInitSegmentResponse({
  44784. segment: segment,
  44785. finishProcessingFn: finishProcessingFn
  44786. });
  44787. var initSegmentXhr = xhr(initSegmentOptions, initSegmentRequestCallback);
  44788. activeXhrs.push(initSegmentXhr);
  44789. }
  44790. var segmentRequestOptions = videojs.mergeOptions(xhrOptions, {
  44791. uri: segment.part && segment.part.resolvedUri || segment.resolvedUri,
  44792. responseType: 'arraybuffer',
  44793. headers: segmentXhrHeaders(segment)
  44794. });
  44795. var segmentRequestCallback = handleSegmentResponse({
  44796. segment: segment,
  44797. finishProcessingFn: finishProcessingFn,
  44798. responseType: segmentRequestOptions.responseType
  44799. });
  44800. var segmentXhr = xhr(segmentRequestOptions, segmentRequestCallback);
  44801. segmentXhr.addEventListener('progress', handleProgress({
  44802. segment: segment,
  44803. progressFn: progressFn,
  44804. trackInfoFn: trackInfoFn,
  44805. timingInfoFn: timingInfoFn,
  44806. videoSegmentTimingInfoFn: videoSegmentTimingInfoFn,
  44807. audioSegmentTimingInfoFn: audioSegmentTimingInfoFn,
  44808. id3Fn: id3Fn,
  44809. captionsFn: captionsFn,
  44810. isEndOfTimeline: isEndOfTimeline,
  44811. endedTimelineFn: endedTimelineFn,
  44812. dataFn: dataFn
  44813. }));
  44814. activeXhrs.push(segmentXhr); // since all parts of the request must be considered, but should not make callbacks
  44815. // multiple times, provide a shared state object
  44816. var loadendState = {};
  44817. activeXhrs.forEach(function (activeXhr) {
  44818. activeXhr.addEventListener('loadend', handleLoadEnd({
  44819. loadendState: loadendState,
  44820. abortFn: abortFn
  44821. }));
  44822. });
  44823. return function () {
  44824. return abortAll(activeXhrs);
  44825. };
  44826. };
  44827. /**
  44828. * @file - codecs.js - Handles tasks regarding codec strings such as translating them to
  44829. * codec strings, or translating codec strings into objects that can be examined.
  44830. */
  44831. var logFn$1 = logger('CodecUtils');
  44832. /**
  44833. * Returns a set of codec strings parsed from the playlist or the default
  44834. * codec strings if no codecs were specified in the playlist
  44835. *
  44836. * @param {Playlist} media the current media playlist
  44837. * @return {Object} an object with the video and audio codecs
  44838. */
  44839. var getCodecs = function getCodecs(media) {
  44840. // if the codecs were explicitly specified, use them instead of the
  44841. // defaults
  44842. var mediaAttributes = media.attributes || {};
  44843. if (mediaAttributes.CODECS) {
  44844. return parseCodecs(mediaAttributes.CODECS);
  44845. }
  44846. };
  44847. var isMaat = function isMaat(master, media) {
  44848. var mediaAttributes = media.attributes || {};
  44849. return master && master.mediaGroups && master.mediaGroups.AUDIO && mediaAttributes.AUDIO && master.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  44850. };
  44851. var isMuxed = function isMuxed(master, media) {
  44852. if (!isMaat(master, media)) {
  44853. return true;
  44854. }
  44855. var mediaAttributes = media.attributes || {};
  44856. var audioGroup = master.mediaGroups.AUDIO[mediaAttributes.AUDIO];
  44857. for (var groupId in audioGroup) {
  44858. // If an audio group has a URI (the case for HLS, as HLS will use external playlists),
  44859. // or there are listed playlists (the case for DASH, as the manifest will have already
  44860. // provided all of the details necessary to generate the audio playlist, as opposed to
  44861. // HLS' externally requested playlists), then the content is demuxed.
  44862. if (!audioGroup[groupId].uri && !audioGroup[groupId].playlists) {
  44863. return true;
  44864. }
  44865. }
  44866. return false;
  44867. };
  44868. var unwrapCodecList = function unwrapCodecList(codecList) {
  44869. var codecs = {};
  44870. codecList.forEach(function (_ref) {
  44871. var mediaType = _ref.mediaType,
  44872. type = _ref.type,
  44873. details = _ref.details;
  44874. codecs[mediaType] = codecs[mediaType] || [];
  44875. codecs[mediaType].push(translateLegacyCodec("" + type + details));
  44876. });
  44877. Object.keys(codecs).forEach(function (mediaType) {
  44878. if (codecs[mediaType].length > 1) {
  44879. 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.");
  44880. codecs[mediaType] = null;
  44881. return;
  44882. }
  44883. codecs[mediaType] = codecs[mediaType][0];
  44884. });
  44885. return codecs;
  44886. };
  44887. var codecCount = function codecCount(codecObj) {
  44888. var count = 0;
  44889. if (codecObj.audio) {
  44890. count++;
  44891. }
  44892. if (codecObj.video) {
  44893. count++;
  44894. }
  44895. return count;
  44896. };
  44897. /**
  44898. * Calculates the codec strings for a working configuration of
  44899. * SourceBuffers to play variant streams in a master playlist. If
  44900. * there is no possible working configuration, an empty object will be
  44901. * returned.
  44902. *
  44903. * @param master {Object} the m3u8 object for the master playlist
  44904. * @param media {Object} the m3u8 object for the variant playlist
  44905. * @return {Object} the codec strings.
  44906. *
  44907. * @private
  44908. */
  44909. var codecsForPlaylist = function codecsForPlaylist(master, media) {
  44910. var mediaAttributes = media.attributes || {};
  44911. var codecInfo = unwrapCodecList(getCodecs(media) || []); // HLS with multiple-audio tracks must always get an audio codec.
  44912. // Put another way, there is no way to have a video-only multiple-audio HLS!
  44913. if (isMaat(master, media) && !codecInfo.audio) {
  44914. if (!isMuxed(master, media)) {
  44915. // It is possible for codecs to be specified on the audio media group playlist but
  44916. // not on the rendition playlist. This is mostly the case for DASH, where audio and
  44917. // video are always separate (and separately specified).
  44918. var defaultCodecs = unwrapCodecList(codecsFromDefault(master, mediaAttributes.AUDIO) || []);
  44919. if (defaultCodecs.audio) {
  44920. codecInfo.audio = defaultCodecs.audio;
  44921. }
  44922. }
  44923. }
  44924. return codecInfo;
  44925. };
  44926. var logFn = logger('PlaylistSelector');
  44927. var representationToString = function representationToString(representation) {
  44928. if (!representation || !representation.playlist) {
  44929. return;
  44930. }
  44931. var playlist = representation.playlist;
  44932. return JSON.stringify({
  44933. id: playlist.id,
  44934. bandwidth: representation.bandwidth,
  44935. width: representation.width,
  44936. height: representation.height,
  44937. codecs: playlist.attributes && playlist.attributes.CODECS || ''
  44938. });
  44939. }; // Utilities
  44940. /**
  44941. * Returns the CSS value for the specified property on an element
  44942. * using `getComputedStyle`. Firefox has a long-standing issue where
  44943. * getComputedStyle() may return null when running in an iframe with
  44944. * `display: none`.
  44945. *
  44946. * @see https://bugzilla.mozilla.org/show_bug.cgi?id=548397
  44947. * @param {HTMLElement} el the htmlelement to work on
  44948. * @param {string} the proprety to get the style for
  44949. */
  44950. var safeGetComputedStyle = function safeGetComputedStyle(el, property) {
  44951. if (!el) {
  44952. return '';
  44953. }
  44954. var result = window.getComputedStyle(el);
  44955. if (!result) {
  44956. return '';
  44957. }
  44958. return result[property];
  44959. };
  44960. /**
  44961. * Resuable stable sort function
  44962. *
  44963. * @param {Playlists} array
  44964. * @param {Function} sortFn Different comparators
  44965. * @function stableSort
  44966. */
  44967. var stableSort = function stableSort(array, sortFn) {
  44968. var newArray = array.slice();
  44969. array.sort(function (left, right) {
  44970. var cmp = sortFn(left, right);
  44971. if (cmp === 0) {
  44972. return newArray.indexOf(left) - newArray.indexOf(right);
  44973. }
  44974. return cmp;
  44975. });
  44976. };
  44977. /**
  44978. * A comparator function to sort two playlist object by bandwidth.
  44979. *
  44980. * @param {Object} left a media playlist object
  44981. * @param {Object} right a media playlist object
  44982. * @return {number} Greater than zero if the bandwidth attribute of
  44983. * left is greater than the corresponding attribute of right. Less
  44984. * than zero if the bandwidth of right is greater than left and
  44985. * exactly zero if the two are equal.
  44986. */
  44987. var comparePlaylistBandwidth = function comparePlaylistBandwidth(left, right) {
  44988. var leftBandwidth;
  44989. var rightBandwidth;
  44990. if (left.attributes.BANDWIDTH) {
  44991. leftBandwidth = left.attributes.BANDWIDTH;
  44992. }
  44993. leftBandwidth = leftBandwidth || window.Number.MAX_VALUE;
  44994. if (right.attributes.BANDWIDTH) {
  44995. rightBandwidth = right.attributes.BANDWIDTH;
  44996. }
  44997. rightBandwidth = rightBandwidth || window.Number.MAX_VALUE;
  44998. return leftBandwidth - rightBandwidth;
  44999. };
  45000. /**
  45001. * A comparator function to sort two playlist object by resolution (width).
  45002. *
  45003. * @param {Object} left a media playlist object
  45004. * @param {Object} right a media playlist object
  45005. * @return {number} Greater than zero if the resolution.width attribute of
  45006. * left is greater than the corresponding attribute of right. Less
  45007. * than zero if the resolution.width of right is greater than left and
  45008. * exactly zero if the two are equal.
  45009. */
  45010. var comparePlaylistResolution = function comparePlaylistResolution(left, right) {
  45011. var leftWidth;
  45012. var rightWidth;
  45013. if (left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {
  45014. leftWidth = left.attributes.RESOLUTION.width;
  45015. }
  45016. leftWidth = leftWidth || window.Number.MAX_VALUE;
  45017. if (right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {
  45018. rightWidth = right.attributes.RESOLUTION.width;
  45019. }
  45020. rightWidth = rightWidth || window.Number.MAX_VALUE; // NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions
  45021. // have the same media dimensions/ resolution
  45022. if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {
  45023. return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
  45024. }
  45025. return leftWidth - rightWidth;
  45026. };
  45027. /**
  45028. * Chooses the appropriate media playlist based on bandwidth and player size
  45029. *
  45030. * @param {Object} master
  45031. * Object representation of the master manifest
  45032. * @param {number} playerBandwidth
  45033. * Current calculated bandwidth of the player
  45034. * @param {number} playerWidth
  45035. * Current width of the player element (should account for the device pixel ratio)
  45036. * @param {number} playerHeight
  45037. * Current height of the player element (should account for the device pixel ratio)
  45038. * @param {boolean} limitRenditionByPlayerDimensions
  45039. * True if the player width and height should be used during the selection, false otherwise
  45040. * @param {Object} masterPlaylistController
  45041. * the current masterPlaylistController object
  45042. * @return {Playlist} the highest bitrate playlist less than the
  45043. * currently detected bandwidth, accounting for some amount of
  45044. * bandwidth variance
  45045. */
  45046. var simpleSelector = function simpleSelector(master, playerBandwidth, playerWidth, playerHeight, limitRenditionByPlayerDimensions, masterPlaylistController) {
  45047. // If we end up getting called before `master` is available, exit early
  45048. if (!master) {
  45049. return;
  45050. }
  45051. var options = {
  45052. bandwidth: playerBandwidth,
  45053. width: playerWidth,
  45054. height: playerHeight,
  45055. limitRenditionByPlayerDimensions: limitRenditionByPlayerDimensions
  45056. };
  45057. var playlists = master.playlists; // if playlist is audio only, select between currently active audio group playlists.
  45058. if (Playlist.isAudioOnly(master)) {
  45059. playlists = masterPlaylistController.getAudioTrackPlaylists_(); // add audioOnly to options so that we log audioOnly: true
  45060. // at the buttom of this function for debugging.
  45061. options.audioOnly = true;
  45062. } // convert the playlists to an intermediary representation to make comparisons easier
  45063. var sortedPlaylistReps = playlists.map(function (playlist) {
  45064. var bandwidth;
  45065. var width = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.width;
  45066. var height = playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height;
  45067. bandwidth = playlist.attributes && playlist.attributes.BANDWIDTH;
  45068. bandwidth = bandwidth || window.Number.MAX_VALUE;
  45069. return {
  45070. bandwidth: bandwidth,
  45071. width: width,
  45072. height: height,
  45073. playlist: playlist
  45074. };
  45075. });
  45076. stableSort(sortedPlaylistReps, function (left, right) {
  45077. return left.bandwidth - right.bandwidth;
  45078. }); // filter out any playlists that have been excluded due to
  45079. // incompatible configurations
  45080. sortedPlaylistReps = sortedPlaylistReps.filter(function (rep) {
  45081. return !Playlist.isIncompatible(rep.playlist);
  45082. }); // filter out any playlists that have been disabled manually through the representations
  45083. // api or blacklisted temporarily due to playback errors.
  45084. var enabledPlaylistReps = sortedPlaylistReps.filter(function (rep) {
  45085. return Playlist.isEnabled(rep.playlist);
  45086. });
  45087. if (!enabledPlaylistReps.length) {
  45088. // if there are no enabled playlists, then they have all been blacklisted or disabled
  45089. // by the user through the representations api. In this case, ignore blacklisting and
  45090. // fallback to what the user wants by using playlists the user has not disabled.
  45091. enabledPlaylistReps = sortedPlaylistReps.filter(function (rep) {
  45092. return !Playlist.isDisabled(rep.playlist);
  45093. });
  45094. } // filter out any variant that has greater effective bitrate
  45095. // than the current estimated bandwidth
  45096. var bandwidthPlaylistReps = enabledPlaylistReps.filter(function (rep) {
  45097. return rep.bandwidth * Config.BANDWIDTH_VARIANCE < playerBandwidth;
  45098. });
  45099. var highestRemainingBandwidthRep = bandwidthPlaylistReps[bandwidthPlaylistReps.length - 1]; // get all of the renditions with the same (highest) bandwidth
  45100. // and then taking the very first element
  45101. var bandwidthBestRep = bandwidthPlaylistReps.filter(function (rep) {
  45102. return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
  45103. })[0]; // if we're not going to limit renditions by player size, make an early decision.
  45104. if (limitRenditionByPlayerDimensions === false) {
  45105. var _chosenRep = bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  45106. if (_chosenRep && _chosenRep.playlist) {
  45107. var type = 'sortedPlaylistReps';
  45108. if (bandwidthBestRep) {
  45109. type = 'bandwidthBestRep';
  45110. }
  45111. if (enabledPlaylistReps[0]) {
  45112. type = 'enabledPlaylistReps';
  45113. }
  45114. logFn("choosing " + representationToString(_chosenRep) + " using " + type + " with options", options);
  45115. return _chosenRep.playlist;
  45116. }
  45117. logFn('could not choose a playlist with options', options);
  45118. return null;
  45119. } // filter out playlists without resolution information
  45120. var haveResolution = bandwidthPlaylistReps.filter(function (rep) {
  45121. return rep.width && rep.height;
  45122. }); // sort variants by resolution
  45123. stableSort(haveResolution, function (left, right) {
  45124. return left.width - right.width;
  45125. }); // if we have the exact resolution as the player use it
  45126. var resolutionBestRepList = haveResolution.filter(function (rep) {
  45127. return rep.width === playerWidth && rep.height === playerHeight;
  45128. });
  45129. highestRemainingBandwidthRep = resolutionBestRepList[resolutionBestRepList.length - 1]; // ensure that we pick the highest bandwidth variant that have exact resolution
  45130. var resolutionBestRep = resolutionBestRepList.filter(function (rep) {
  45131. return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
  45132. })[0];
  45133. var resolutionPlusOneList;
  45134. var resolutionPlusOneSmallest;
  45135. var resolutionPlusOneRep; // find the smallest variant that is larger than the player
  45136. // if there is no match of exact resolution
  45137. if (!resolutionBestRep) {
  45138. resolutionPlusOneList = haveResolution.filter(function (rep) {
  45139. return rep.width > playerWidth || rep.height > playerHeight;
  45140. }); // find all the variants have the same smallest resolution
  45141. resolutionPlusOneSmallest = resolutionPlusOneList.filter(function (rep) {
  45142. return rep.width === resolutionPlusOneList[0].width && rep.height === resolutionPlusOneList[0].height;
  45143. }); // ensure that we also pick the highest bandwidth variant that
  45144. // is just-larger-than the video player
  45145. highestRemainingBandwidthRep = resolutionPlusOneSmallest[resolutionPlusOneSmallest.length - 1];
  45146. resolutionPlusOneRep = resolutionPlusOneSmallest.filter(function (rep) {
  45147. return rep.bandwidth === highestRemainingBandwidthRep.bandwidth;
  45148. })[0];
  45149. }
  45150. var leastPixelDiffRep; // If this selector proves to be better than others,
  45151. // resolutionPlusOneRep and resolutionBestRep and all
  45152. // the code involving them should be removed.
  45153. if (masterPlaylistController.experimentalLeastPixelDiffSelector) {
  45154. // find the variant that is closest to the player's pixel size
  45155. var leastPixelDiffList = haveResolution.map(function (rep) {
  45156. rep.pixelDiff = Math.abs(rep.width - playerWidth) + Math.abs(rep.height - playerHeight);
  45157. return rep;
  45158. }); // get the highest bandwidth, closest resolution playlist
  45159. stableSort(leastPixelDiffList, function (left, right) {
  45160. // sort by highest bandwidth if pixelDiff is the same
  45161. if (left.pixelDiff === right.pixelDiff) {
  45162. return right.bandwidth - left.bandwidth;
  45163. }
  45164. return left.pixelDiff - right.pixelDiff;
  45165. });
  45166. leastPixelDiffRep = leastPixelDiffList[0];
  45167. } // fallback chain of variants
  45168. var chosenRep = leastPixelDiffRep || resolutionPlusOneRep || resolutionBestRep || bandwidthBestRep || enabledPlaylistReps[0] || sortedPlaylistReps[0];
  45169. if (chosenRep && chosenRep.playlist) {
  45170. var _type = 'sortedPlaylistReps';
  45171. if (leastPixelDiffRep) {
  45172. _type = 'leastPixelDiffRep';
  45173. } else if (resolutionPlusOneRep) {
  45174. _type = 'resolutionPlusOneRep';
  45175. } else if (resolutionBestRep) {
  45176. _type = 'resolutionBestRep';
  45177. } else if (bandwidthBestRep) {
  45178. _type = 'bandwidthBestRep';
  45179. } else if (enabledPlaylistReps[0]) {
  45180. _type = 'enabledPlaylistReps';
  45181. }
  45182. logFn("choosing " + representationToString(chosenRep) + " using " + _type + " with options", options);
  45183. return chosenRep.playlist;
  45184. }
  45185. logFn('could not choose a playlist with options', options);
  45186. return null;
  45187. };
  45188. /**
  45189. * Chooses the appropriate media playlist based on the most recent
  45190. * bandwidth estimate and the player size.
  45191. *
  45192. * Expects to be called within the context of an instance of VhsHandler
  45193. *
  45194. * @return {Playlist} the highest bitrate playlist less than the
  45195. * currently detected bandwidth, accounting for some amount of
  45196. * bandwidth variance
  45197. */
  45198. var lastBandwidthSelector = function lastBandwidthSelector() {
  45199. var pixelRatio = this.useDevicePixelRatio ? window.devicePixelRatio || 1 : 1;
  45200. 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_);
  45201. };
  45202. /**
  45203. * Chooses the appropriate media playlist based on an
  45204. * exponential-weighted moving average of the bandwidth after
  45205. * filtering for player size.
  45206. *
  45207. * Expects to be called within the context of an instance of VhsHandler
  45208. *
  45209. * @param {number} decay - a number between 0 and 1. Higher values of
  45210. * this parameter will cause previous bandwidth estimates to lose
  45211. * significance more quickly.
  45212. * @return {Function} a function which can be invoked to create a new
  45213. * playlist selector function.
  45214. * @see https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  45215. */
  45216. var movingAverageBandwidthSelector = function movingAverageBandwidthSelector(decay) {
  45217. var average = -1;
  45218. var lastSystemBandwidth = -1;
  45219. if (decay < 0 || decay > 1) {
  45220. throw new Error('Moving average bandwidth decay must be between 0 and 1.');
  45221. }
  45222. return function () {
  45223. var pixelRatio = this.useDevicePixelRatio ? window.devicePixelRatio || 1 : 1;
  45224. if (average < 0) {
  45225. average = this.systemBandwidth;
  45226. lastSystemBandwidth = this.systemBandwidth;
  45227. } // stop the average value from decaying for every 250ms
  45228. // when the systemBandwidth is constant
  45229. // and
  45230. // stop average from setting to a very low value when the
  45231. // systemBandwidth becomes 0 in case of chunk cancellation
  45232. if (this.systemBandwidth > 0 && this.systemBandwidth !== lastSystemBandwidth) {
  45233. average = decay * this.systemBandwidth + (1 - decay) * average;
  45234. lastSystemBandwidth = this.systemBandwidth;
  45235. }
  45236. 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_);
  45237. };
  45238. };
  45239. /**
  45240. * Chooses the appropriate media playlist based on the potential to rebuffer
  45241. *
  45242. * @param {Object} settings
  45243. * Object of information required to use this selector
  45244. * @param {Object} settings.master
  45245. * Object representation of the master manifest
  45246. * @param {number} settings.currentTime
  45247. * The current time of the player
  45248. * @param {number} settings.bandwidth
  45249. * Current measured bandwidth
  45250. * @param {number} settings.duration
  45251. * Duration of the media
  45252. * @param {number} settings.segmentDuration
  45253. * Segment duration to be used in round trip time calculations
  45254. * @param {number} settings.timeUntilRebuffer
  45255. * Time left in seconds until the player has to rebuffer
  45256. * @param {number} settings.currentTimeline
  45257. * The current timeline segments are being loaded from
  45258. * @param {SyncController} settings.syncController
  45259. * SyncController for determining if we have a sync point for a given playlist
  45260. * @return {Object|null}
  45261. * {Object} return.playlist
  45262. * The highest bandwidth playlist with the least amount of rebuffering
  45263. * {Number} return.rebufferingImpact
  45264. * The amount of time in seconds switching to this playlist will rebuffer. A
  45265. * negative value means that switching will cause zero rebuffering.
  45266. */
  45267. var minRebufferMaxBandwidthSelector = function minRebufferMaxBandwidthSelector(settings) {
  45268. var master = settings.master,
  45269. currentTime = settings.currentTime,
  45270. bandwidth = settings.bandwidth,
  45271. duration = settings.duration,
  45272. segmentDuration = settings.segmentDuration,
  45273. timeUntilRebuffer = settings.timeUntilRebuffer,
  45274. currentTimeline = settings.currentTimeline,
  45275. syncController = settings.syncController; // filter out any playlists that have been excluded due to
  45276. // incompatible configurations
  45277. var compatiblePlaylists = master.playlists.filter(function (playlist) {
  45278. return !Playlist.isIncompatible(playlist);
  45279. }); // filter out any playlists that have been disabled manually through the representations
  45280. // api or blacklisted temporarily due to playback errors.
  45281. var enabledPlaylists = compatiblePlaylists.filter(Playlist.isEnabled);
  45282. if (!enabledPlaylists.length) {
  45283. // if there are no enabled playlists, then they have all been blacklisted or disabled
  45284. // by the user through the representations api. In this case, ignore blacklisting and
  45285. // fallback to what the user wants by using playlists the user has not disabled.
  45286. enabledPlaylists = compatiblePlaylists.filter(function (playlist) {
  45287. return !Playlist.isDisabled(playlist);
  45288. });
  45289. }
  45290. var bandwidthPlaylists = enabledPlaylists.filter(Playlist.hasAttribute.bind(null, 'BANDWIDTH'));
  45291. var rebufferingEstimates = bandwidthPlaylists.map(function (playlist) {
  45292. var syncPoint = syncController.getSyncPoint(playlist, duration, currentTimeline, currentTime); // If there is no sync point for this playlist, switching to it will require a
  45293. // sync request first. This will double the request time
  45294. var numRequests = syncPoint ? 1 : 2;
  45295. var requestTimeEstimate = Playlist.estimateSegmentRequestTime(segmentDuration, bandwidth, playlist);
  45296. var rebufferingImpact = requestTimeEstimate * numRequests - timeUntilRebuffer;
  45297. return {
  45298. playlist: playlist,
  45299. rebufferingImpact: rebufferingImpact
  45300. };
  45301. });
  45302. var noRebufferingPlaylists = rebufferingEstimates.filter(function (estimate) {
  45303. return estimate.rebufferingImpact <= 0;
  45304. }); // Sort by bandwidth DESC
  45305. stableSort(noRebufferingPlaylists, function (a, b) {
  45306. return comparePlaylistBandwidth(b.playlist, a.playlist);
  45307. });
  45308. if (noRebufferingPlaylists.length) {
  45309. return noRebufferingPlaylists[0];
  45310. }
  45311. stableSort(rebufferingEstimates, function (a, b) {
  45312. return a.rebufferingImpact - b.rebufferingImpact;
  45313. });
  45314. return rebufferingEstimates[0] || null;
  45315. };
  45316. /**
  45317. * Chooses the appropriate media playlist, which in this case is the lowest bitrate
  45318. * one with video. If no renditions with video exist, return the lowest audio rendition.
  45319. *
  45320. * Expects to be called within the context of an instance of VhsHandler
  45321. *
  45322. * @return {Object|null}
  45323. * {Object} return.playlist
  45324. * The lowest bitrate playlist that contains a video codec. If no such rendition
  45325. * exists pick the lowest audio rendition.
  45326. */
  45327. var lowestBitrateCompatibleVariantSelector = function lowestBitrateCompatibleVariantSelector() {
  45328. var _this = this; // filter out any playlists that have been excluded due to
  45329. // incompatible configurations or playback errors
  45330. var playlists = this.playlists.master.playlists.filter(Playlist.isEnabled); // Sort ascending by bitrate
  45331. stableSort(playlists, function (a, b) {
  45332. return comparePlaylistBandwidth(a, b);
  45333. }); // Parse and assume that playlists with no video codec have no video
  45334. // (this is not necessarily true, although it is generally true).
  45335. //
  45336. // If an entire manifest has no valid videos everything will get filtered
  45337. // out.
  45338. var playlistsWithVideo = playlists.filter(function (playlist) {
  45339. return !!codecsForPlaylist(_this.playlists.master, playlist).video;
  45340. });
  45341. return playlistsWithVideo[0] || null;
  45342. };
  45343. /**
  45344. * Combine all segments into a single Uint8Array
  45345. *
  45346. * @param {Object} segmentObj
  45347. * @return {Uint8Array} concatenated bytes
  45348. * @private
  45349. */
  45350. var concatSegments = function concatSegments(segmentObj) {
  45351. var offset = 0;
  45352. var tempBuffer;
  45353. if (segmentObj.bytes) {
  45354. tempBuffer = new Uint8Array(segmentObj.bytes); // combine the individual segments into one large typed-array
  45355. segmentObj.segments.forEach(function (segment) {
  45356. tempBuffer.set(segment, offset);
  45357. offset += segment.byteLength;
  45358. });
  45359. }
  45360. return tempBuffer;
  45361. };
  45362. /**
  45363. * @file text-tracks.js
  45364. */
  45365. /**
  45366. * Create captions text tracks on video.js if they do not exist
  45367. *
  45368. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  45369. * @param {Object} tech the video.js tech
  45370. * @param {Object} captionStream the caption stream to create
  45371. * @private
  45372. */
  45373. var createCaptionsTrackIfNotExists = function createCaptionsTrackIfNotExists(inbandTextTracks, tech, captionStream) {
  45374. if (!inbandTextTracks[captionStream]) {
  45375. tech.trigger({
  45376. type: 'usage',
  45377. name: 'vhs-608'
  45378. });
  45379. tech.trigger({
  45380. type: 'usage',
  45381. name: 'hls-608'
  45382. });
  45383. var instreamId = captionStream; // we need to translate SERVICEn for 708 to how mux.js currently labels them
  45384. if (/^cc708_/.test(captionStream)) {
  45385. instreamId = 'SERVICE' + captionStream.split('_')[1];
  45386. }
  45387. var track = tech.textTracks().getTrackById(instreamId);
  45388. if (track) {
  45389. // Resuse an existing track with a CC# id because this was
  45390. // very likely created by videojs-contrib-hls from information
  45391. // in the m3u8 for us to use
  45392. inbandTextTracks[captionStream] = track;
  45393. } else {
  45394. // This section gets called when we have caption services that aren't specified in the manifest.
  45395. // Manifest level caption services are handled in media-groups.js under CLOSED-CAPTIONS.
  45396. var captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  45397. var label = captionStream;
  45398. var language = captionStream;
  45399. var def = false;
  45400. var captionService = captionServices[instreamId];
  45401. if (captionService) {
  45402. label = captionService.label;
  45403. language = captionService.language;
  45404. def = captionService["default"];
  45405. } // Otherwise, create a track with the default `CC#` label and
  45406. // without a language
  45407. inbandTextTracks[captionStream] = tech.addRemoteTextTrack({
  45408. kind: 'captions',
  45409. id: instreamId,
  45410. // TODO: investigate why this doesn't seem to turn the caption on by default
  45411. "default": def,
  45412. label: label,
  45413. language: language
  45414. }, false).track;
  45415. }
  45416. }
  45417. };
  45418. /**
  45419. * Add caption text track data to a source handler given an array of captions
  45420. *
  45421. * @param {Object}
  45422. * @param {Object} inbandTextTracks the inband text tracks
  45423. * @param {number} timestampOffset the timestamp offset of the source buffer
  45424. * @param {Array} captionArray an array of caption data
  45425. * @private
  45426. */
  45427. var addCaptionData = function addCaptionData(_ref) {
  45428. var inbandTextTracks = _ref.inbandTextTracks,
  45429. captionArray = _ref.captionArray,
  45430. timestampOffset = _ref.timestampOffset;
  45431. if (!captionArray) {
  45432. return;
  45433. }
  45434. var Cue = window.WebKitDataCue || window.VTTCue;
  45435. captionArray.forEach(function (caption) {
  45436. var track = caption.stream;
  45437. inbandTextTracks[track].addCue(new Cue(caption.startTime + timestampOffset, caption.endTime + timestampOffset, caption.text));
  45438. });
  45439. };
  45440. /**
  45441. * Define properties on a cue for backwards compatability,
  45442. * but warn the user that the way that they are using it
  45443. * is depricated and will be removed at a later date.
  45444. *
  45445. * @param {Cue} cue the cue to add the properties on
  45446. * @private
  45447. */
  45448. var deprecateOldCue = function deprecateOldCue(cue) {
  45449. Object.defineProperties(cue.frame, {
  45450. id: {
  45451. get: function get() {
  45452. videojs.log.warn('cue.frame.id is deprecated. Use cue.value.key instead.');
  45453. return cue.value.key;
  45454. }
  45455. },
  45456. value: {
  45457. get: function get() {
  45458. videojs.log.warn('cue.frame.value is deprecated. Use cue.value.data instead.');
  45459. return cue.value.data;
  45460. }
  45461. },
  45462. privateData: {
  45463. get: function get() {
  45464. videojs.log.warn('cue.frame.privateData is deprecated. Use cue.value.data instead.');
  45465. return cue.value.data;
  45466. }
  45467. }
  45468. });
  45469. };
  45470. /**
  45471. * Add metadata text track data to a source handler given an array of metadata
  45472. *
  45473. * @param {Object}
  45474. * @param {Object} inbandTextTracks the inband text tracks
  45475. * @param {Array} metadataArray an array of meta data
  45476. * @param {number} timestampOffset the timestamp offset of the source buffer
  45477. * @param {number} videoDuration the duration of the video
  45478. * @private
  45479. */
  45480. var addMetadata = function addMetadata(_ref2) {
  45481. var inbandTextTracks = _ref2.inbandTextTracks,
  45482. metadataArray = _ref2.metadataArray,
  45483. timestampOffset = _ref2.timestampOffset,
  45484. videoDuration = _ref2.videoDuration;
  45485. if (!metadataArray) {
  45486. return;
  45487. }
  45488. var Cue = window.WebKitDataCue || window.VTTCue;
  45489. var metadataTrack = inbandTextTracks.metadataTrack_;
  45490. if (!metadataTrack) {
  45491. return;
  45492. }
  45493. metadataArray.forEach(function (metadata) {
  45494. var time = metadata.cueTime + timestampOffset; // if time isn't a finite number between 0 and Infinity, like NaN,
  45495. // ignore this bit of metadata.
  45496. // This likely occurs when you have an non-timed ID3 tag like TIT2,
  45497. // which is the "Title/Songname/Content description" frame
  45498. if (typeof time !== 'number' || window.isNaN(time) || time < 0 || !(time < Infinity)) {
  45499. return;
  45500. }
  45501. metadata.frames.forEach(function (frame) {
  45502. var cue = new Cue(time, time, frame.value || frame.url || frame.data || '');
  45503. cue.frame = frame;
  45504. cue.value = frame;
  45505. deprecateOldCue(cue);
  45506. metadataTrack.addCue(cue);
  45507. });
  45508. });
  45509. if (!metadataTrack.cues || !metadataTrack.cues.length) {
  45510. return;
  45511. } // Updating the metadeta cues so that
  45512. // the endTime of each cue is the startTime of the next cue
  45513. // the endTime of last cue is the duration of the video
  45514. var cues = metadataTrack.cues;
  45515. var cuesArray = []; // Create a copy of the TextTrackCueList...
  45516. // ...disregarding cues with a falsey value
  45517. for (var i = 0; i < cues.length; i++) {
  45518. if (cues[i]) {
  45519. cuesArray.push(cues[i]);
  45520. }
  45521. } // Group cues by their startTime value
  45522. var cuesGroupedByStartTime = cuesArray.reduce(function (obj, cue) {
  45523. var timeSlot = obj[cue.startTime] || [];
  45524. timeSlot.push(cue);
  45525. obj[cue.startTime] = timeSlot;
  45526. return obj;
  45527. }, {}); // Sort startTimes by ascending order
  45528. var sortedStartTimes = Object.keys(cuesGroupedByStartTime).sort(function (a, b) {
  45529. return Number(a) - Number(b);
  45530. }); // Map each cue group's endTime to the next group's startTime
  45531. sortedStartTimes.forEach(function (startTime, idx) {
  45532. var cueGroup = cuesGroupedByStartTime[startTime];
  45533. var nextTime = Number(sortedStartTimes[idx + 1]) || videoDuration; // Map each cue's endTime the next group's startTime
  45534. cueGroup.forEach(function (cue) {
  45535. cue.endTime = nextTime;
  45536. });
  45537. });
  45538. };
  45539. /**
  45540. * Create metadata text track on video.js if it does not exist
  45541. *
  45542. * @param {Object} inbandTextTracks a reference to current inbandTextTracks
  45543. * @param {string} dispatchType the inband metadata track dispatch type
  45544. * @param {Object} tech the video.js tech
  45545. * @private
  45546. */
  45547. var createMetadataTrackIfNotExists = function createMetadataTrackIfNotExists(inbandTextTracks, dispatchType, tech) {
  45548. if (inbandTextTracks.metadataTrack_) {
  45549. return;
  45550. }
  45551. inbandTextTracks.metadataTrack_ = tech.addRemoteTextTrack({
  45552. kind: 'metadata',
  45553. label: 'Timed Metadata'
  45554. }, false).track;
  45555. inbandTextTracks.metadataTrack_.inBandMetadataTrackDispatchType = dispatchType;
  45556. };
  45557. /**
  45558. * Remove cues from a track on video.js.
  45559. *
  45560. * @param {Double} start start of where we should remove the cue
  45561. * @param {Double} end end of where the we should remove the cue
  45562. * @param {Object} track the text track to remove the cues from
  45563. * @private
  45564. */
  45565. var removeCuesFromTrack = function removeCuesFromTrack(start, end, track) {
  45566. var i;
  45567. var cue;
  45568. if (!track) {
  45569. return;
  45570. }
  45571. if (!track.cues) {
  45572. return;
  45573. }
  45574. i = track.cues.length;
  45575. while (i--) {
  45576. cue = track.cues[i]; // Remove any cue within the provided start and end time
  45577. if (cue.startTime >= start && cue.endTime <= end) {
  45578. track.removeCue(cue);
  45579. }
  45580. }
  45581. };
  45582. /**
  45583. * Remove duplicate cues from a track on video.js (a cue is considered a
  45584. * duplicate if it has the same time interval and text as another)
  45585. *
  45586. * @param {Object} track the text track to remove the duplicate cues from
  45587. * @private
  45588. */
  45589. var removeDuplicateCuesFromTrack = function removeDuplicateCuesFromTrack(track) {
  45590. var cues = track.cues;
  45591. if (!cues) {
  45592. return;
  45593. }
  45594. for (var i = 0; i < cues.length; i++) {
  45595. var duplicates = [];
  45596. var occurrences = 0;
  45597. for (var j = 0; j < cues.length; j++) {
  45598. if (cues[i].startTime === cues[j].startTime && cues[i].endTime === cues[j].endTime && cues[i].text === cues[j].text) {
  45599. occurrences++;
  45600. if (occurrences > 1) {
  45601. duplicates.push(cues[j]);
  45602. }
  45603. }
  45604. }
  45605. if (duplicates.length) {
  45606. duplicates.forEach(function (dupe) {
  45607. return track.removeCue(dupe);
  45608. });
  45609. }
  45610. }
  45611. };
  45612. /**
  45613. * Returns a list of gops in the buffer that have a pts value of 3 seconds or more in
  45614. * front of current time.
  45615. *
  45616. * @param {Array} buffer
  45617. * The current buffer of gop information
  45618. * @param {number} currentTime
  45619. * The current time
  45620. * @param {Double} mapping
  45621. * Offset to map display time to stream presentation time
  45622. * @return {Array}
  45623. * List of gops considered safe to append over
  45624. */
  45625. var gopsSafeToAlignWith = function gopsSafeToAlignWith(buffer, currentTime, mapping) {
  45626. if (typeof currentTime === 'undefined' || currentTime === null || !buffer.length) {
  45627. return [];
  45628. } // pts value for current time + 3 seconds to give a bit more wiggle room
  45629. var currentTimePts = Math.ceil((currentTime - mapping + 3) * clock_1);
  45630. var i;
  45631. for (i = 0; i < buffer.length; i++) {
  45632. if (buffer[i].pts > currentTimePts) {
  45633. break;
  45634. }
  45635. }
  45636. return buffer.slice(i);
  45637. };
  45638. /**
  45639. * Appends gop information (timing and byteLength) received by the transmuxer for the
  45640. * gops appended in the last call to appendBuffer
  45641. *
  45642. * @param {Array} buffer
  45643. * The current buffer of gop information
  45644. * @param {Array} gops
  45645. * List of new gop information
  45646. * @param {boolean} replace
  45647. * If true, replace the buffer with the new gop information. If false, append the
  45648. * new gop information to the buffer in the right location of time.
  45649. * @return {Array}
  45650. * Updated list of gop information
  45651. */
  45652. var updateGopBuffer = function updateGopBuffer(buffer, gops, replace) {
  45653. if (!gops.length) {
  45654. return buffer;
  45655. }
  45656. if (replace) {
  45657. // If we are in safe append mode, then completely overwrite the gop buffer
  45658. // with the most recent appeneded data. This will make sure that when appending
  45659. // future segments, we only try to align with gops that are both ahead of current
  45660. // time and in the last segment appended.
  45661. return gops.slice();
  45662. }
  45663. var start = gops[0].pts;
  45664. var i = 0;
  45665. for (i; i < buffer.length; i++) {
  45666. if (buffer[i].pts >= start) {
  45667. break;
  45668. }
  45669. }
  45670. return buffer.slice(0, i).concat(gops);
  45671. };
  45672. /**
  45673. * Removes gop information in buffer that overlaps with provided start and end
  45674. *
  45675. * @param {Array} buffer
  45676. * The current buffer of gop information
  45677. * @param {Double} start
  45678. * position to start the remove at
  45679. * @param {Double} end
  45680. * position to end the remove at
  45681. * @param {Double} mapping
  45682. * Offset to map display time to stream presentation time
  45683. */
  45684. var removeGopBuffer = function removeGopBuffer(buffer, start, end, mapping) {
  45685. var startPts = Math.ceil((start - mapping) * clock_1);
  45686. var endPts = Math.ceil((end - mapping) * clock_1);
  45687. var updatedBuffer = buffer.slice();
  45688. var i = buffer.length;
  45689. while (i--) {
  45690. if (buffer[i].pts <= endPts) {
  45691. break;
  45692. }
  45693. }
  45694. if (i === -1) {
  45695. // no removal because end of remove range is before start of buffer
  45696. return updatedBuffer;
  45697. }
  45698. var j = i + 1;
  45699. while (j--) {
  45700. if (buffer[j].pts <= startPts) {
  45701. break;
  45702. }
  45703. } // clamp remove range start to 0 index
  45704. j = Math.max(j, 0);
  45705. updatedBuffer.splice(j, i - j + 1);
  45706. return updatedBuffer;
  45707. };
  45708. var shallowEqual = function shallowEqual(a, b) {
  45709. // if both are undefined
  45710. // or one or the other is undefined
  45711. // they are not equal
  45712. if (!a && !b || !a && b || a && !b) {
  45713. return false;
  45714. } // they are the same object and thus, equal
  45715. if (a === b) {
  45716. return true;
  45717. } // sort keys so we can make sure they have
  45718. // all the same keys later.
  45719. var akeys = Object.keys(a).sort();
  45720. var bkeys = Object.keys(b).sort(); // different number of keys, not equal
  45721. if (akeys.length !== bkeys.length) {
  45722. return false;
  45723. }
  45724. for (var i = 0; i < akeys.length; i++) {
  45725. var key = akeys[i]; // different sorted keys, not equal
  45726. if (key !== bkeys[i]) {
  45727. return false;
  45728. } // different values, not equal
  45729. if (a[key] !== b[key]) {
  45730. return false;
  45731. }
  45732. }
  45733. return true;
  45734. }; // https://www.w3.org/TR/WebIDL-1/#quotaexceedederror
  45735. var QUOTA_EXCEEDED_ERR = 22;
  45736. /**
  45737. * The segment loader has no recourse except to fetch a segment in the
  45738. * current playlist and use the internal timestamps in that segment to
  45739. * generate a syncPoint. This function returns a good candidate index
  45740. * for that process.
  45741. *
  45742. * @param {Array} segments - the segments array from a playlist.
  45743. * @return {number} An index of a segment from the playlist to load
  45744. */
  45745. var getSyncSegmentCandidate = function getSyncSegmentCandidate(currentTimeline, segments, targetTime) {
  45746. segments = segments || [];
  45747. var timelineSegments = [];
  45748. var time = 0;
  45749. for (var i = 0; i < segments.length; i++) {
  45750. var segment = segments[i];
  45751. if (currentTimeline === segment.timeline) {
  45752. timelineSegments.push(i);
  45753. time += segment.duration;
  45754. if (time > targetTime) {
  45755. return i;
  45756. }
  45757. }
  45758. }
  45759. if (timelineSegments.length === 0) {
  45760. return 0;
  45761. } // default to the last timeline segment
  45762. return timelineSegments[timelineSegments.length - 1];
  45763. }; // In the event of a quota exceeded error, keep at least one second of back buffer. This
  45764. // number was arbitrarily chosen and may be updated in the future, but seemed reasonable
  45765. // as a start to prevent any potential issues with removing content too close to the
  45766. // playhead.
  45767. var MIN_BACK_BUFFER = 1; // in ms
  45768. var CHECK_BUFFER_DELAY = 500;
  45769. var finite = function finite(num) {
  45770. return typeof num === 'number' && isFinite(num);
  45771. }; // With most content hovering around 30fps, if a segment has a duration less than a half
  45772. // frame at 30fps or one frame at 60fps, the bandwidth and throughput calculations will
  45773. // not accurately reflect the rest of the content.
  45774. var MIN_SEGMENT_DURATION_TO_SAVE_STATS = 1 / 60;
  45775. var illegalMediaSwitch = function illegalMediaSwitch(loaderType, startingMedia, trackInfo) {
  45776. // Although these checks should most likely cover non 'main' types, for now it narrows
  45777. // the scope of our checks.
  45778. if (loaderType !== 'main' || !startingMedia || !trackInfo) {
  45779. return null;
  45780. }
  45781. if (!trackInfo.hasAudio && !trackInfo.hasVideo) {
  45782. return 'Neither audio nor video found in segment.';
  45783. }
  45784. if (startingMedia.hasVideo && !trackInfo.hasVideo) {
  45785. 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.';
  45786. }
  45787. if (!startingMedia.hasVideo && trackInfo.hasVideo) {
  45788. 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.';
  45789. }
  45790. return null;
  45791. };
  45792. /**
  45793. * Calculates a time value that is safe to remove from the back buffer without interrupting
  45794. * playback.
  45795. *
  45796. * @param {TimeRange} seekable
  45797. * The current seekable range
  45798. * @param {number} currentTime
  45799. * The current time of the player
  45800. * @param {number} targetDuration
  45801. * The target duration of the current playlist
  45802. * @return {number}
  45803. * Time that is safe to remove from the back buffer without interrupting playback
  45804. */
  45805. var safeBackBufferTrimTime = function safeBackBufferTrimTime(seekable, currentTime, targetDuration) {
  45806. // 30 seconds before the playhead provides a safe default for trimming.
  45807. //
  45808. // Choosing a reasonable default is particularly important for high bitrate content and
  45809. // VOD videos/live streams with large windows, as the buffer may end up overfilled and
  45810. // throw an APPEND_BUFFER_ERR.
  45811. var trimTime = currentTime - Config.BACK_BUFFER_LENGTH;
  45812. if (seekable.length) {
  45813. // Some live playlists may have a shorter window of content than the full allowed back
  45814. // buffer. For these playlists, don't save content that's no longer within the window.
  45815. trimTime = Math.max(trimTime, seekable.start(0));
  45816. } // Don't remove within target duration of the current time to avoid the possibility of
  45817. // removing the GOP currently being played, as removing it can cause playback stalls.
  45818. var maxTrimTime = currentTime - targetDuration;
  45819. return Math.min(maxTrimTime, trimTime);
  45820. };
  45821. var segmentInfoString = function segmentInfoString(segmentInfo) {
  45822. var startOfSegment = segmentInfo.startOfSegment,
  45823. duration = segmentInfo.duration,
  45824. segment = segmentInfo.segment,
  45825. part = segmentInfo.part,
  45826. _segmentInfo$playlist = segmentInfo.playlist,
  45827. seq = _segmentInfo$playlist.mediaSequence,
  45828. id = _segmentInfo$playlist.id,
  45829. _segmentInfo$playlist2 = _segmentInfo$playlist.segments,
  45830. segments = _segmentInfo$playlist2 === void 0 ? [] : _segmentInfo$playlist2,
  45831. index = segmentInfo.mediaIndex,
  45832. partIndex = segmentInfo.partIndex,
  45833. timeline = segmentInfo.timeline;
  45834. var segmentLen = segments.length - 1;
  45835. var selection = 'mediaIndex/partIndex increment';
  45836. if (segmentInfo.getMediaInfoForTime) {
  45837. selection = "getMediaInfoForTime (" + segmentInfo.getMediaInfoForTime + ")";
  45838. } else if (segmentInfo.isSyncRequest) {
  45839. selection = 'getSyncSegmentCandidate (isSyncRequest)';
  45840. }
  45841. if (segmentInfo.independent) {
  45842. selection += " with independent " + segmentInfo.independent;
  45843. }
  45844. var hasPartIndex = typeof partIndex === 'number';
  45845. var name = segmentInfo.segment.uri ? 'segment' : 'pre-segment';
  45846. var zeroBasedPartCount = hasPartIndex ? getKnownPartCount({
  45847. preloadSegment: segment
  45848. }) - 1 : 0;
  45849. 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 + "]");
  45850. };
  45851. var timingInfoPropertyForMedia = function timingInfoPropertyForMedia(mediaType) {
  45852. return mediaType + "TimingInfo";
  45853. };
  45854. /**
  45855. * Returns the timestamp offset to use for the segment.
  45856. *
  45857. * @param {number} segmentTimeline
  45858. * The timeline of the segment
  45859. * @param {number} currentTimeline
  45860. * The timeline currently being followed by the loader
  45861. * @param {number} startOfSegment
  45862. * The estimated segment start
  45863. * @param {TimeRange[]} buffered
  45864. * The loader's buffer
  45865. * @param {boolean} overrideCheck
  45866. * If true, no checks are made to see if the timestamp offset value should be set,
  45867. * but sets it directly to a value.
  45868. *
  45869. * @return {number|null}
  45870. * Either a number representing a new timestamp offset, or null if the segment is
  45871. * part of the same timeline
  45872. */
  45873. var timestampOffsetForSegment = function timestampOffsetForSegment(_ref) {
  45874. var segmentTimeline = _ref.segmentTimeline,
  45875. currentTimeline = _ref.currentTimeline,
  45876. startOfSegment = _ref.startOfSegment,
  45877. buffered = _ref.buffered,
  45878. overrideCheck = _ref.overrideCheck; // Check to see if we are crossing a discontinuity to see if we need to set the
  45879. // timestamp offset on the transmuxer and source buffer.
  45880. //
  45881. // Previously, we changed the timestampOffset if the start of this segment was less than
  45882. // the currently set timestampOffset, but this isn't desirable as it can produce bad
  45883. // behavior, especially around long running live streams.
  45884. if (!overrideCheck && segmentTimeline === currentTimeline) {
  45885. return null;
  45886. } // When changing renditions, it's possible to request a segment on an older timeline. For
  45887. // instance, given two renditions with the following:
  45888. //
  45889. // #EXTINF:10
  45890. // segment1
  45891. // #EXT-X-DISCONTINUITY
  45892. // #EXTINF:10
  45893. // segment2
  45894. // #EXTINF:10
  45895. // segment3
  45896. //
  45897. // And the current player state:
  45898. //
  45899. // current time: 8
  45900. // buffer: 0 => 20
  45901. //
  45902. // The next segment on the current rendition would be segment3, filling the buffer from
  45903. // 20s onwards. However, if a rendition switch happens after segment2 was requested,
  45904. // then the next segment to be requested will be segment1 from the new rendition in
  45905. // order to fill time 8 and onwards. Using the buffered end would result in repeated
  45906. // content (since it would position segment1 of the new rendition starting at 20s). This
  45907. // case can be identified when the new segment's timeline is a prior value. Instead of
  45908. // using the buffered end, the startOfSegment can be used, which, hopefully, will be
  45909. // more accurate to the actual start time of the segment.
  45910. if (segmentTimeline < currentTimeline) {
  45911. return startOfSegment;
  45912. } // segmentInfo.startOfSegment used to be used as the timestamp offset, however, that
  45913. // value uses the end of the last segment if it is available. While this value
  45914. // should often be correct, it's better to rely on the buffered end, as the new
  45915. // content post discontinuity should line up with the buffered end as if it were
  45916. // time 0 for the new content.
  45917. return buffered.length ? buffered.end(buffered.length - 1) : startOfSegment;
  45918. };
  45919. /**
  45920. * Returns whether or not the loader should wait for a timeline change from the timeline
  45921. * change controller before processing the segment.
  45922. *
  45923. * Primary timing in VHS goes by video. This is different from most media players, as
  45924. * audio is more often used as the primary timing source. For the foreseeable future, VHS
  45925. * will continue to use video as the primary timing source, due to the current logic and
  45926. * expectations built around it.
  45927. * Since the timing follows video, in order to maintain sync, the video loader is
  45928. * responsible for setting both audio and video source buffer timestamp offsets.
  45929. *
  45930. * Setting different values for audio and video source buffers could lead to
  45931. * desyncing. The following examples demonstrate some of the situations where this
  45932. * distinction is important. Note that all of these cases involve demuxed content. When
  45933. * content is muxed, the audio and video are packaged together, therefore syncing
  45934. * separate media playlists is not an issue.
  45935. *
  45936. * CASE 1: Audio prepares to load a new timeline before video:
  45937. *
  45938. * Timeline: 0 1
  45939. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  45940. * Audio Loader: ^
  45941. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  45942. * Video Loader ^
  45943. *
  45944. * In the above example, the audio loader is preparing to load the 6th segment, the first
  45945. * after a discontinuity, while the video loader is still loading the 5th segment, before
  45946. * the discontinuity.
  45947. *
  45948. * If the audio loader goes ahead and loads and appends the 6th segment before the video
  45949. * loader crosses the discontinuity, then when appended, the 6th audio segment will use
  45950. * the timestamp offset from timeline 0. This will likely lead to desyncing. In addition,
  45951. * the audio loader must provide the audioAppendStart value to trim the content in the
  45952. * transmuxer, and that value relies on the audio timestamp offset. Since the audio
  45953. * timestamp offset is set by the video (main) loader, the audio loader shouldn't load the
  45954. * segment until that value is provided.
  45955. *
  45956. * CASE 2: Video prepares to load a new timeline before audio:
  45957. *
  45958. * Timeline: 0 1
  45959. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  45960. * Audio Loader: ^
  45961. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  45962. * Video Loader ^
  45963. *
  45964. * In the above example, the video loader is preparing to load the 6th segment, the first
  45965. * after a discontinuity, while the audio loader is still loading the 5th segment, before
  45966. * the discontinuity.
  45967. *
  45968. * If the video loader goes ahead and loads and appends the 6th segment, then once the
  45969. * segment is loaded and processed, both the video and audio timestamp offsets will be
  45970. * set, since video is used as the primary timing source. This is to ensure content lines
  45971. * up appropriately, as any modifications to the video timing are reflected by audio when
  45972. * the video loader sets the audio and video timestamp offsets to the same value. However,
  45973. * setting the timestamp offset for audio before audio has had a chance to change
  45974. * timelines will likely lead to desyncing, as the audio loader will append segment 5 with
  45975. * a timestamp intended to apply to segments from timeline 1 rather than timeline 0.
  45976. *
  45977. * CASE 3: When seeking, audio prepares to load a new timeline before video
  45978. *
  45979. * Timeline: 0 1
  45980. * Audio Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  45981. * Audio Loader: ^
  45982. * Video Segments: 0 1 2 3 4 5 DISCO 6 7 8 9
  45983. * Video Loader ^
  45984. *
  45985. * In the above example, both audio and video loaders are loading segments from timeline
  45986. * 0, but imagine that the seek originated from timeline 1.
  45987. *
  45988. * When seeking to a new timeline, the timestamp offset will be set based on the expected
  45989. * segment start of the loaded video segment. In order to maintain sync, the audio loader
  45990. * must wait for the video loader to load its segment and update both the audio and video
  45991. * timestamp offsets before it may load and append its own segment. This is the case
  45992. * whether the seek results in a mismatched segment request (e.g., the audio loader
  45993. * chooses to load segment 3 and the video loader chooses to load segment 4) or the
  45994. * loaders choose to load the same segment index from each playlist, as the segments may
  45995. * not be aligned perfectly, even for matching segment indexes.
  45996. *
  45997. * @param {Object} timelinechangeController
  45998. * @param {number} currentTimeline
  45999. * The timeline currently being followed by the loader
  46000. * @param {number} segmentTimeline
  46001. * The timeline of the segment being loaded
  46002. * @param {('main'|'audio')} loaderType
  46003. * The loader type
  46004. * @param {boolean} audioDisabled
  46005. * Whether the audio is disabled for the loader. This should only be true when the
  46006. * loader may have muxed audio in its segment, but should not append it, e.g., for
  46007. * the main loader when an alternate audio playlist is active.
  46008. *
  46009. * @return {boolean}
  46010. * Whether the loader should wait for a timeline change from the timeline change
  46011. * controller before processing the segment
  46012. */
  46013. var shouldWaitForTimelineChange = function shouldWaitForTimelineChange(_ref2) {
  46014. var timelineChangeController = _ref2.timelineChangeController,
  46015. currentTimeline = _ref2.currentTimeline,
  46016. segmentTimeline = _ref2.segmentTimeline,
  46017. loaderType = _ref2.loaderType,
  46018. audioDisabled = _ref2.audioDisabled;
  46019. if (currentTimeline === segmentTimeline) {
  46020. return false;
  46021. }
  46022. if (loaderType === 'audio') {
  46023. var lastMainTimelineChange = timelineChangeController.lastTimelineChange({
  46024. type: 'main'
  46025. }); // Audio loader should wait if:
  46026. //
  46027. // * main hasn't had a timeline change yet (thus has not loaded its first segment)
  46028. // * main hasn't yet changed to the timeline audio is looking to load
  46029. return !lastMainTimelineChange || lastMainTimelineChange.to !== segmentTimeline;
  46030. } // The main loader only needs to wait for timeline changes if there's demuxed audio.
  46031. // Otherwise, there's nothing to wait for, since audio would be muxed into the main
  46032. // loader's segments (or the content is audio/video only and handled by the main
  46033. // loader).
  46034. if (loaderType === 'main' && audioDisabled) {
  46035. var pendingAudioTimelineChange = timelineChangeController.pendingTimelineChange({
  46036. type: 'audio'
  46037. }); // Main loader should wait for the audio loader if audio is not pending a timeline
  46038. // change to the current timeline.
  46039. //
  46040. // Since the main loader is responsible for setting the timestamp offset for both
  46041. // audio and video, the main loader must wait for audio to be about to change to its
  46042. // timeline before setting the offset, otherwise, if audio is behind in loading,
  46043. // segments from the previous timeline would be adjusted by the new timestamp offset.
  46044. //
  46045. // This requirement means that video will not cross a timeline until the audio is
  46046. // about to cross to it, so that way audio and video will always cross the timeline
  46047. // together.
  46048. //
  46049. // In addition to normal timeline changes, these rules also apply to the start of a
  46050. // stream (going from a non-existent timeline, -1, to timeline 0). It's important
  46051. // that these rules apply to the first timeline change because if they did not, it's
  46052. // possible that the main loader will cross two timelines before the audio loader has
  46053. // crossed one. Logic may be implemented to handle the startup as a special case, but
  46054. // it's easier to simply treat all timeline changes the same.
  46055. if (pendingAudioTimelineChange && pendingAudioTimelineChange.to === segmentTimeline) {
  46056. return false;
  46057. }
  46058. return true;
  46059. }
  46060. return false;
  46061. };
  46062. var mediaDuration = function mediaDuration(timingInfos) {
  46063. var maxDuration = 0;
  46064. ['video', 'audio'].forEach(function (type) {
  46065. var typeTimingInfo = timingInfos[type + "TimingInfo"];
  46066. if (!typeTimingInfo) {
  46067. return;
  46068. }
  46069. var start = typeTimingInfo.start,
  46070. end = typeTimingInfo.end;
  46071. var duration;
  46072. if (typeof start === 'bigint' || typeof end === 'bigint') {
  46073. duration = window.BigInt(end) - window.BigInt(start);
  46074. } else if (typeof start === 'number' && typeof end === 'number') {
  46075. duration = end - start;
  46076. }
  46077. if (typeof duration !== 'undefined' && duration > maxDuration) {
  46078. maxDuration = duration;
  46079. }
  46080. }); // convert back to a number if it is lower than MAX_SAFE_INTEGER
  46081. // as we only need BigInt when we are above that.
  46082. if (typeof maxDuration === 'bigint' && maxDuration < Number.MAX_SAFE_INTEGER) {
  46083. maxDuration = Number(maxDuration);
  46084. }
  46085. return maxDuration;
  46086. };
  46087. var segmentTooLong = function segmentTooLong(_ref3) {
  46088. var segmentDuration = _ref3.segmentDuration,
  46089. maxDuration = _ref3.maxDuration; // 0 duration segments are most likely due to metadata only segments or a lack of
  46090. // information.
  46091. if (!segmentDuration) {
  46092. return false;
  46093. } // For HLS:
  46094. //
  46095. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.3.1
  46096. // The EXTINF duration of each Media Segment in the Playlist
  46097. // file, when rounded to the nearest integer, MUST be less than or equal
  46098. // to the target duration; longer segments can trigger playback stalls
  46099. // or other errors.
  46100. //
  46101. // For DASH, the mpd-parser uses the largest reported segment duration as the target
  46102. // duration. Although that reported duration is occasionally approximate (i.e., not
  46103. // exact), a strict check may report that a segment is too long more often in DASH.
  46104. return Math.round(segmentDuration) > maxDuration + TIME_FUDGE_FACTOR;
  46105. };
  46106. var getTroublesomeSegmentDurationMessage = function getTroublesomeSegmentDurationMessage(segmentInfo, sourceType) {
  46107. // Right now we aren't following DASH's timing model exactly, so only perform
  46108. // this check for HLS content.
  46109. if (sourceType !== 'hls') {
  46110. return null;
  46111. }
  46112. var segmentDuration = mediaDuration({
  46113. audioTimingInfo: segmentInfo.audioTimingInfo,
  46114. videoTimingInfo: segmentInfo.videoTimingInfo
  46115. }); // Don't report if we lack information.
  46116. //
  46117. // If the segment has a duration of 0 it is either a lack of information or a
  46118. // metadata only segment and shouldn't be reported here.
  46119. if (!segmentDuration) {
  46120. return null;
  46121. }
  46122. var targetDuration = segmentInfo.playlist.targetDuration;
  46123. var isSegmentWayTooLong = segmentTooLong({
  46124. segmentDuration: segmentDuration,
  46125. maxDuration: targetDuration * 2
  46126. });
  46127. var isSegmentSlightlyTooLong = segmentTooLong({
  46128. segmentDuration: segmentDuration,
  46129. maxDuration: targetDuration
  46130. });
  46131. 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';
  46132. if (isSegmentWayTooLong || isSegmentSlightlyTooLong) {
  46133. return {
  46134. severity: isSegmentWayTooLong ? 'warn' : 'info',
  46135. message: segmentTooLongMessage
  46136. };
  46137. }
  46138. return null;
  46139. };
  46140. /**
  46141. * An object that manages segment loading and appending.
  46142. *
  46143. * @class SegmentLoader
  46144. * @param {Object} options required and optional options
  46145. * @extends videojs.EventTarget
  46146. */
  46147. var SegmentLoader = /*#__PURE__*/function (_videojs$EventTarget) {
  46148. inheritsLoose(SegmentLoader, _videojs$EventTarget);
  46149. function SegmentLoader(settings, options) {
  46150. var _this;
  46151. _this = _videojs$EventTarget.call(this) || this; // check pre-conditions
  46152. if (!settings) {
  46153. throw new TypeError('Initialization settings are required');
  46154. }
  46155. if (typeof settings.currentTime !== 'function') {
  46156. throw new TypeError('No currentTime getter specified');
  46157. }
  46158. if (!settings.mediaSource) {
  46159. throw new TypeError('No MediaSource specified');
  46160. } // public properties
  46161. _this.bandwidth = settings.bandwidth;
  46162. _this.throughput = {
  46163. rate: 0,
  46164. count: 0
  46165. };
  46166. _this.roundTrip = NaN;
  46167. _this.resetStats_();
  46168. _this.mediaIndex = null;
  46169. _this.partIndex = null; // private settings
  46170. _this.hasPlayed_ = settings.hasPlayed;
  46171. _this.currentTime_ = settings.currentTime;
  46172. _this.seekable_ = settings.seekable;
  46173. _this.seeking_ = settings.seeking;
  46174. _this.duration_ = settings.duration;
  46175. _this.mediaSource_ = settings.mediaSource;
  46176. _this.vhs_ = settings.vhs;
  46177. _this.loaderType_ = settings.loaderType;
  46178. _this.currentMediaInfo_ = void 0;
  46179. _this.startingMediaInfo_ = void 0;
  46180. _this.segmentMetadataTrack_ = settings.segmentMetadataTrack;
  46181. _this.goalBufferLength_ = settings.goalBufferLength;
  46182. _this.sourceType_ = settings.sourceType;
  46183. _this.sourceUpdater_ = settings.sourceUpdater;
  46184. _this.inbandTextTracks_ = settings.inbandTextTracks;
  46185. _this.state_ = 'INIT';
  46186. _this.timelineChangeController_ = settings.timelineChangeController;
  46187. _this.shouldSaveSegmentTimingInfo_ = true;
  46188. _this.parse708captions_ = settings.parse708captions;
  46189. _this.useDtsForTimestampOffset_ = settings.useDtsForTimestampOffset;
  46190. _this.captionServices_ = settings.captionServices;
  46191. _this.experimentalExactManifestTimings = settings.experimentalExactManifestTimings; // private instance variables
  46192. _this.checkBufferTimeout_ = null;
  46193. _this.error_ = void 0;
  46194. _this.currentTimeline_ = -1;
  46195. _this.pendingSegment_ = null;
  46196. _this.xhrOptions_ = null;
  46197. _this.pendingSegments_ = [];
  46198. _this.audioDisabled_ = false;
  46199. _this.isPendingTimestampOffset_ = false; // TODO possibly move gopBuffer and timeMapping info to a separate controller
  46200. _this.gopBuffer_ = [];
  46201. _this.timeMapping_ = 0;
  46202. _this.safeAppend_ = videojs.browser.IE_VERSION >= 11;
  46203. _this.appendInitSegment_ = {
  46204. audio: true,
  46205. video: true
  46206. };
  46207. _this.playlistOfLastInitSegment_ = {
  46208. audio: null,
  46209. video: null
  46210. };
  46211. _this.callQueue_ = []; // If the segment loader prepares to load a segment, but does not have enough
  46212. // information yet to start the loading process (e.g., if the audio loader wants to
  46213. // load a segment from the next timeline but the main loader hasn't yet crossed that
  46214. // timeline), then the load call will be added to the queue until it is ready to be
  46215. // processed.
  46216. _this.loadQueue_ = [];
  46217. _this.metadataQueue_ = {
  46218. id3: [],
  46219. caption: []
  46220. };
  46221. _this.waitingOnRemove_ = false;
  46222. _this.quotaExceededErrorRetryTimeout_ = null; // Fragmented mp4 playback
  46223. _this.activeInitSegmentId_ = null;
  46224. _this.initSegments_ = {}; // HLSe playback
  46225. _this.cacheEncryptionKeys_ = settings.cacheEncryptionKeys;
  46226. _this.keyCache_ = {};
  46227. _this.decrypter_ = settings.decrypter; // Manages the tracking and generation of sync-points, mappings
  46228. // between a time in the display time and a segment index within
  46229. // a playlist
  46230. _this.syncController_ = settings.syncController;
  46231. _this.syncPoint_ = {
  46232. segmentIndex: 0,
  46233. time: 0
  46234. };
  46235. _this.transmuxer_ = _this.createTransmuxer_();
  46236. _this.triggerSyncInfoUpdate_ = function () {
  46237. return _this.trigger('syncinfoupdate');
  46238. };
  46239. _this.syncController_.on('syncinfoupdate', _this.triggerSyncInfoUpdate_);
  46240. _this.mediaSource_.addEventListener('sourceopen', function () {
  46241. if (!_this.isEndOfStream_()) {
  46242. _this.ended_ = false;
  46243. }
  46244. }); // ...for determining the fetch location
  46245. _this.fetchAtBuffer_ = false;
  46246. _this.logger_ = logger("SegmentLoader[" + _this.loaderType_ + "]");
  46247. Object.defineProperty(assertThisInitialized(_this), 'state', {
  46248. get: function get() {
  46249. return this.state_;
  46250. },
  46251. set: function set(newState) {
  46252. if (newState !== this.state_) {
  46253. this.logger_(this.state_ + " -> " + newState);
  46254. this.state_ = newState;
  46255. this.trigger('statechange');
  46256. }
  46257. }
  46258. });
  46259. _this.sourceUpdater_.on('ready', function () {
  46260. if (_this.hasEnoughInfoToAppend_()) {
  46261. _this.processCallQueue_();
  46262. }
  46263. }); // Only the main loader needs to listen for pending timeline changes, as the main
  46264. // loader should wait for audio to be ready to change its timeline so that both main
  46265. // and audio timelines change together. For more details, see the
  46266. // shouldWaitForTimelineChange function.
  46267. if (_this.loaderType_ === 'main') {
  46268. _this.timelineChangeController_.on('pendingtimelinechange', function () {
  46269. if (_this.hasEnoughInfoToAppend_()) {
  46270. _this.processCallQueue_();
  46271. }
  46272. });
  46273. } // The main loader only listens on pending timeline changes, but the audio loader,
  46274. // since its loads follow main, needs to listen on timeline changes. For more details,
  46275. // see the shouldWaitForTimelineChange function.
  46276. if (_this.loaderType_ === 'audio') {
  46277. _this.timelineChangeController_.on('timelinechange', function () {
  46278. if (_this.hasEnoughInfoToLoad_()) {
  46279. _this.processLoadQueue_();
  46280. }
  46281. if (_this.hasEnoughInfoToAppend_()) {
  46282. _this.processCallQueue_();
  46283. }
  46284. });
  46285. }
  46286. return _this;
  46287. }
  46288. var _proto = SegmentLoader.prototype;
  46289. _proto.createTransmuxer_ = function createTransmuxer_() {
  46290. return segmentTransmuxer.createTransmuxer({
  46291. remux: false,
  46292. alignGopsAtEnd: this.safeAppend_,
  46293. keepOriginalTimestamps: true,
  46294. parse708captions: this.parse708captions_,
  46295. captionServices: this.captionServices_
  46296. });
  46297. }
  46298. /**
  46299. * reset all of our media stats
  46300. *
  46301. * @private
  46302. */
  46303. ;
  46304. _proto.resetStats_ = function resetStats_() {
  46305. this.mediaBytesTransferred = 0;
  46306. this.mediaRequests = 0;
  46307. this.mediaRequestsAborted = 0;
  46308. this.mediaRequestsTimedout = 0;
  46309. this.mediaRequestsErrored = 0;
  46310. this.mediaTransferDuration = 0;
  46311. this.mediaSecondsLoaded = 0;
  46312. this.mediaAppends = 0;
  46313. }
  46314. /**
  46315. * dispose of the SegmentLoader and reset to the default state
  46316. */
  46317. ;
  46318. _proto.dispose = function dispose() {
  46319. this.trigger('dispose');
  46320. this.state = 'DISPOSED';
  46321. this.pause();
  46322. this.abort_();
  46323. if (this.transmuxer_) {
  46324. this.transmuxer_.terminate();
  46325. }
  46326. this.resetStats_();
  46327. if (this.checkBufferTimeout_) {
  46328. window.clearTimeout(this.checkBufferTimeout_);
  46329. }
  46330. if (this.syncController_ && this.triggerSyncInfoUpdate_) {
  46331. this.syncController_.off('syncinfoupdate', this.triggerSyncInfoUpdate_);
  46332. }
  46333. this.off();
  46334. };
  46335. _proto.setAudio = function setAudio(enable) {
  46336. this.audioDisabled_ = !enable;
  46337. if (enable) {
  46338. this.appendInitSegment_.audio = true;
  46339. } else {
  46340. // remove current track audio if it gets disabled
  46341. this.sourceUpdater_.removeAudio(0, this.duration_());
  46342. }
  46343. }
  46344. /**
  46345. * abort anything that is currently doing on with the SegmentLoader
  46346. * and reset to a default state
  46347. */
  46348. ;
  46349. _proto.abort = function abort() {
  46350. if (this.state !== 'WAITING') {
  46351. if (this.pendingSegment_) {
  46352. this.pendingSegment_ = null;
  46353. }
  46354. return;
  46355. }
  46356. this.abort_(); // We aborted the requests we were waiting on, so reset the loader's state to READY
  46357. // since we are no longer "waiting" on any requests. XHR callback is not always run
  46358. // when the request is aborted. This will prevent the loader from being stuck in the
  46359. // WAITING state indefinitely.
  46360. this.state = 'READY'; // don't wait for buffer check timeouts to begin fetching the
  46361. // next segment
  46362. if (!this.paused()) {
  46363. this.monitorBuffer_();
  46364. }
  46365. }
  46366. /**
  46367. * abort all pending xhr requests and null any pending segements
  46368. *
  46369. * @private
  46370. */
  46371. ;
  46372. _proto.abort_ = function abort_() {
  46373. if (this.pendingSegment_ && this.pendingSegment_.abortRequests) {
  46374. this.pendingSegment_.abortRequests();
  46375. } // clear out the segment being processed
  46376. this.pendingSegment_ = null;
  46377. this.callQueue_ = [];
  46378. this.loadQueue_ = [];
  46379. this.metadataQueue_.id3 = [];
  46380. this.metadataQueue_.caption = [];
  46381. this.timelineChangeController_.clearPendingTimelineChange(this.loaderType_);
  46382. this.waitingOnRemove_ = false;
  46383. window.clearTimeout(this.quotaExceededErrorRetryTimeout_);
  46384. this.quotaExceededErrorRetryTimeout_ = null;
  46385. };
  46386. _proto.checkForAbort_ = function checkForAbort_(requestId) {
  46387. // If the state is APPENDING, then aborts will not modify the state, meaning the first
  46388. // callback that happens should reset the state to READY so that loading can continue.
  46389. if (this.state === 'APPENDING' && !this.pendingSegment_) {
  46390. this.state = 'READY';
  46391. return true;
  46392. }
  46393. if (!this.pendingSegment_ || this.pendingSegment_.requestId !== requestId) {
  46394. return true;
  46395. }
  46396. return false;
  46397. }
  46398. /**
  46399. * set an error on the segment loader and null out any pending segements
  46400. *
  46401. * @param {Error} error the error to set on the SegmentLoader
  46402. * @return {Error} the error that was set or that is currently set
  46403. */
  46404. ;
  46405. _proto.error = function error(_error) {
  46406. if (typeof _error !== 'undefined') {
  46407. this.logger_('error occurred:', _error);
  46408. this.error_ = _error;
  46409. }
  46410. this.pendingSegment_ = null;
  46411. return this.error_;
  46412. };
  46413. _proto.endOfStream = function endOfStream() {
  46414. this.ended_ = true;
  46415. if (this.transmuxer_) {
  46416. // need to clear out any cached data to prepare for the new segment
  46417. segmentTransmuxer.reset(this.transmuxer_);
  46418. }
  46419. this.gopBuffer_.length = 0;
  46420. this.pause();
  46421. this.trigger('ended');
  46422. }
  46423. /**
  46424. * Indicates which time ranges are buffered
  46425. *
  46426. * @return {TimeRange}
  46427. * TimeRange object representing the current buffered ranges
  46428. */
  46429. ;
  46430. _proto.buffered_ = function buffered_() {
  46431. var trackInfo = this.getMediaInfo_();
  46432. if (!this.sourceUpdater_ || !trackInfo) {
  46433. return videojs.createTimeRanges();
  46434. }
  46435. if (this.loaderType_ === 'main') {
  46436. var hasAudio = trackInfo.hasAudio,
  46437. hasVideo = trackInfo.hasVideo,
  46438. isMuxed = trackInfo.isMuxed;
  46439. if (hasVideo && hasAudio && !this.audioDisabled_ && !isMuxed) {
  46440. return this.sourceUpdater_.buffered();
  46441. }
  46442. if (hasVideo) {
  46443. return this.sourceUpdater_.videoBuffered();
  46444. }
  46445. } // One case that can be ignored for now is audio only with alt audio,
  46446. // as we don't yet have proper support for that.
  46447. return this.sourceUpdater_.audioBuffered();
  46448. }
  46449. /**
  46450. * Gets and sets init segment for the provided map
  46451. *
  46452. * @param {Object} map
  46453. * The map object representing the init segment to get or set
  46454. * @param {boolean=} set
  46455. * If true, the init segment for the provided map should be saved
  46456. * @return {Object}
  46457. * map object for desired init segment
  46458. */
  46459. ;
  46460. _proto.initSegmentForMap = function initSegmentForMap(map, set) {
  46461. if (set === void 0) {
  46462. set = false;
  46463. }
  46464. if (!map) {
  46465. return null;
  46466. }
  46467. var id = initSegmentId(map);
  46468. var storedMap = this.initSegments_[id];
  46469. if (set && !storedMap && map.bytes) {
  46470. this.initSegments_[id] = storedMap = {
  46471. resolvedUri: map.resolvedUri,
  46472. byterange: map.byterange,
  46473. bytes: map.bytes,
  46474. tracks: map.tracks,
  46475. timescales: map.timescales
  46476. };
  46477. }
  46478. return storedMap || map;
  46479. }
  46480. /**
  46481. * Gets and sets key for the provided key
  46482. *
  46483. * @param {Object} key
  46484. * The key object representing the key to get or set
  46485. * @param {boolean=} set
  46486. * If true, the key for the provided key should be saved
  46487. * @return {Object}
  46488. * Key object for desired key
  46489. */
  46490. ;
  46491. _proto.segmentKey = function segmentKey(key, set) {
  46492. if (set === void 0) {
  46493. set = false;
  46494. }
  46495. if (!key) {
  46496. return null;
  46497. }
  46498. var id = segmentKeyId(key);
  46499. var storedKey = this.keyCache_[id]; // TODO: We should use the HTTP Expires header to invalidate our cache per
  46500. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-6.2.3
  46501. if (this.cacheEncryptionKeys_ && set && !storedKey && key.bytes) {
  46502. this.keyCache_[id] = storedKey = {
  46503. resolvedUri: key.resolvedUri,
  46504. bytes: key.bytes
  46505. };
  46506. }
  46507. var result = {
  46508. resolvedUri: (storedKey || key).resolvedUri
  46509. };
  46510. if (storedKey) {
  46511. result.bytes = storedKey.bytes;
  46512. }
  46513. return result;
  46514. }
  46515. /**
  46516. * Returns true if all configuration required for loading is present, otherwise false.
  46517. *
  46518. * @return {boolean} True if the all configuration is ready for loading
  46519. * @private
  46520. */
  46521. ;
  46522. _proto.couldBeginLoading_ = function couldBeginLoading_() {
  46523. return this.playlist_ && !this.paused();
  46524. }
  46525. /**
  46526. * load a playlist and start to fill the buffer
  46527. */
  46528. ;
  46529. _proto.load = function load() {
  46530. // un-pause
  46531. this.monitorBuffer_(); // if we don't have a playlist yet, keep waiting for one to be
  46532. // specified
  46533. if (!this.playlist_) {
  46534. return;
  46535. } // if all the configuration is ready, initialize and begin loading
  46536. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  46537. return this.init_();
  46538. } // if we're in the middle of processing a segment already, don't
  46539. // kick off an additional segment request
  46540. if (!this.couldBeginLoading_() || this.state !== 'READY' && this.state !== 'INIT') {
  46541. return;
  46542. }
  46543. this.state = 'READY';
  46544. }
  46545. /**
  46546. * Once all the starting parameters have been specified, begin
  46547. * operation. This method should only be invoked from the INIT
  46548. * state.
  46549. *
  46550. * @private
  46551. */
  46552. ;
  46553. _proto.init_ = function init_() {
  46554. this.state = 'READY'; // if this is the audio segment loader, and it hasn't been inited before, then any old
  46555. // audio data from the muxed content should be removed
  46556. this.resetEverything();
  46557. return this.monitorBuffer_();
  46558. }
  46559. /**
  46560. * set a playlist on the segment loader
  46561. *
  46562. * @param {PlaylistLoader} media the playlist to set on the segment loader
  46563. */
  46564. ;
  46565. _proto.playlist = function playlist(newPlaylist, options) {
  46566. if (options === void 0) {
  46567. options = {};
  46568. }
  46569. if (!newPlaylist) {
  46570. return;
  46571. }
  46572. var oldPlaylist = this.playlist_;
  46573. var segmentInfo = this.pendingSegment_;
  46574. this.playlist_ = newPlaylist;
  46575. this.xhrOptions_ = options; // when we haven't started playing yet, the start of a live playlist
  46576. // is always our zero-time so force a sync update each time the playlist
  46577. // is refreshed from the server
  46578. //
  46579. // Use the INIT state to determine if playback has started, as the playlist sync info
  46580. // should be fixed once requests begin (as sync points are generated based on sync
  46581. // info), but not before then.
  46582. if (this.state === 'INIT') {
  46583. newPlaylist.syncInfo = {
  46584. mediaSequence: newPlaylist.mediaSequence,
  46585. time: 0
  46586. }; // Setting the date time mapping means mapping the program date time (if available)
  46587. // to time 0 on the player's timeline. The playlist's syncInfo serves a similar
  46588. // purpose, mapping the initial mediaSequence to time zero. Since the syncInfo can
  46589. // be updated as the playlist is refreshed before the loader starts loading, the
  46590. // program date time mapping needs to be updated as well.
  46591. //
  46592. // This mapping is only done for the main loader because a program date time should
  46593. // map equivalently between playlists.
  46594. if (this.loaderType_ === 'main') {
  46595. this.syncController_.setDateTimeMappingForStart(newPlaylist);
  46596. }
  46597. }
  46598. var oldId = null;
  46599. if (oldPlaylist) {
  46600. if (oldPlaylist.id) {
  46601. oldId = oldPlaylist.id;
  46602. } else if (oldPlaylist.uri) {
  46603. oldId = oldPlaylist.uri;
  46604. }
  46605. }
  46606. this.logger_("playlist update [" + oldId + " => " + (newPlaylist.id || newPlaylist.uri) + "]"); // in VOD, this is always a rendition switch (or we updated our syncInfo above)
  46607. // in LIVE, we always want to update with new playlists (including refreshes)
  46608. this.trigger('syncinfoupdate'); // if we were unpaused but waiting for a playlist, start
  46609. // buffering now
  46610. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  46611. return this.init_();
  46612. }
  46613. if (!oldPlaylist || oldPlaylist.uri !== newPlaylist.uri) {
  46614. if (this.mediaIndex !== null) {
  46615. // we must reset/resync the segment loader when we switch renditions and
  46616. // the segment loader is already synced to the previous rendition
  46617. // on playlist changes we want it to be possible to fetch
  46618. // at the buffer for vod but not for live. So we use resetLoader
  46619. // for live and resyncLoader for vod. We want this because
  46620. // if a playlist uses independent and non-independent segments/parts the
  46621. // buffer may not accurately reflect the next segment that we should try
  46622. // downloading.
  46623. if (!newPlaylist.endList) {
  46624. this.resetLoader();
  46625. } else {
  46626. this.resyncLoader();
  46627. }
  46628. }
  46629. this.currentMediaInfo_ = void 0;
  46630. this.trigger('playlistupdate'); // the rest of this function depends on `oldPlaylist` being defined
  46631. return;
  46632. } // we reloaded the same playlist so we are in a live scenario
  46633. // and we will likely need to adjust the mediaIndex
  46634. var mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence;
  46635. this.logger_("live window shift [" + mediaSequenceDiff + "]"); // update the mediaIndex on the SegmentLoader
  46636. // this is important because we can abort a request and this value must be
  46637. // equal to the last appended mediaIndex
  46638. if (this.mediaIndex !== null) {
  46639. this.mediaIndex -= mediaSequenceDiff; // this can happen if we are going to load the first segment, but get a playlist
  46640. // update during that. mediaIndex would go from 0 to -1 if mediaSequence in the
  46641. // new playlist was incremented by 1.
  46642. if (this.mediaIndex < 0) {
  46643. this.mediaIndex = null;
  46644. this.partIndex = null;
  46645. } else {
  46646. var segment = this.playlist_.segments[this.mediaIndex]; // partIndex should remain the same for the same segment
  46647. // unless parts fell off of the playlist for this segment.
  46648. // In that case we need to reset partIndex and resync
  46649. if (this.partIndex && (!segment.parts || !segment.parts.length || !segment.parts[this.partIndex])) {
  46650. var mediaIndex = this.mediaIndex;
  46651. this.logger_("currently processing part (index " + this.partIndex + ") no longer exists.");
  46652. this.resetLoader(); // We want to throw away the partIndex and the data associated with it,
  46653. // as the part was dropped from our current playlists segment.
  46654. // The mediaIndex will still be valid so keep that around.
  46655. this.mediaIndex = mediaIndex;
  46656. }
  46657. }
  46658. } // update the mediaIndex on the SegmentInfo object
  46659. // this is important because we will update this.mediaIndex with this value
  46660. // in `handleAppendsDone_` after the segment has been successfully appended
  46661. if (segmentInfo) {
  46662. segmentInfo.mediaIndex -= mediaSequenceDiff;
  46663. if (segmentInfo.mediaIndex < 0) {
  46664. segmentInfo.mediaIndex = null;
  46665. segmentInfo.partIndex = null;
  46666. } else {
  46667. // we need to update the referenced segment so that timing information is
  46668. // saved for the new playlist's segment, however, if the segment fell off the
  46669. // playlist, we can leave the old reference and just lose the timing info
  46670. if (segmentInfo.mediaIndex >= 0) {
  46671. segmentInfo.segment = newPlaylist.segments[segmentInfo.mediaIndex];
  46672. }
  46673. if (segmentInfo.partIndex >= 0 && segmentInfo.segment.parts) {
  46674. segmentInfo.part = segmentInfo.segment.parts[segmentInfo.partIndex];
  46675. }
  46676. }
  46677. }
  46678. this.syncController_.saveExpiredSegmentInfo(oldPlaylist, newPlaylist);
  46679. }
  46680. /**
  46681. * Prevent the loader from fetching additional segments. If there
  46682. * is a segment request outstanding, it will finish processing
  46683. * before the loader halts. A segment loader can be unpaused by
  46684. * calling load().
  46685. */
  46686. ;
  46687. _proto.pause = function pause() {
  46688. if (this.checkBufferTimeout_) {
  46689. window.clearTimeout(this.checkBufferTimeout_);
  46690. this.checkBufferTimeout_ = null;
  46691. }
  46692. }
  46693. /**
  46694. * Returns whether the segment loader is fetching additional
  46695. * segments when given the opportunity. This property can be
  46696. * modified through calls to pause() and load().
  46697. */
  46698. ;
  46699. _proto.paused = function paused() {
  46700. return this.checkBufferTimeout_ === null;
  46701. }
  46702. /**
  46703. * Delete all the buffered data and reset the SegmentLoader
  46704. *
  46705. * @param {Function} [done] an optional callback to be executed when the remove
  46706. * operation is complete
  46707. */
  46708. ;
  46709. _proto.resetEverything = function resetEverything(done) {
  46710. this.ended_ = false;
  46711. this.activeInitSegmentId_ = null;
  46712. this.appendInitSegment_ = {
  46713. audio: true,
  46714. video: true
  46715. };
  46716. this.resetLoader(); // remove from 0, the earliest point, to Infinity, to signify removal of everything.
  46717. // VTT Segment Loader doesn't need to do anything but in the regular SegmentLoader,
  46718. // we then clamp the value to duration if necessary.
  46719. this.remove(0, Infinity, done); // clears fmp4 captions
  46720. if (this.transmuxer_) {
  46721. this.transmuxer_.postMessage({
  46722. action: 'clearAllMp4Captions'
  46723. }); // reset the cache in the transmuxer
  46724. this.transmuxer_.postMessage({
  46725. action: 'reset'
  46726. });
  46727. }
  46728. }
  46729. /**
  46730. * Force the SegmentLoader to resync and start loading around the currentTime instead
  46731. * of starting at the end of the buffer
  46732. *
  46733. * Useful for fast quality changes
  46734. */
  46735. ;
  46736. _proto.resetLoader = function resetLoader() {
  46737. this.fetchAtBuffer_ = false;
  46738. this.resyncLoader();
  46739. }
  46740. /**
  46741. * Force the SegmentLoader to restart synchronization and make a conservative guess
  46742. * before returning to the simple walk-forward method
  46743. */
  46744. ;
  46745. _proto.resyncLoader = function resyncLoader() {
  46746. if (this.transmuxer_) {
  46747. // need to clear out any cached data to prepare for the new segment
  46748. segmentTransmuxer.reset(this.transmuxer_);
  46749. }
  46750. this.mediaIndex = null;
  46751. this.partIndex = null;
  46752. this.syncPoint_ = null;
  46753. this.isPendingTimestampOffset_ = false;
  46754. this.callQueue_ = [];
  46755. this.loadQueue_ = [];
  46756. this.metadataQueue_.id3 = [];
  46757. this.metadataQueue_.caption = [];
  46758. this.abort();
  46759. if (this.transmuxer_) {
  46760. this.transmuxer_.postMessage({
  46761. action: 'clearParsedMp4Captions'
  46762. });
  46763. }
  46764. }
  46765. /**
  46766. * Remove any data in the source buffer between start and end times
  46767. *
  46768. * @param {number} start - the start time of the region to remove from the buffer
  46769. * @param {number} end - the end time of the region to remove from the buffer
  46770. * @param {Function} [done] - an optional callback to be executed when the remove
  46771. * @param {boolean} force - force all remove operations to happen
  46772. * operation is complete
  46773. */
  46774. ;
  46775. _proto.remove = function remove(start, end, done, force) {
  46776. if (done === void 0) {
  46777. done = function done() {};
  46778. }
  46779. if (force === void 0) {
  46780. force = false;
  46781. } // clamp end to duration if we need to remove everything.
  46782. // This is due to a browser bug that causes issues if we remove to Infinity.
  46783. // videojs/videojs-contrib-hls#1225
  46784. if (end === Infinity) {
  46785. end = this.duration_();
  46786. } // skip removes that would throw an error
  46787. // commonly happens during a rendition switch at the start of a video
  46788. // from start 0 to end 0
  46789. if (end <= start) {
  46790. this.logger_('skipping remove because end ${end} is <= start ${start}');
  46791. return;
  46792. }
  46793. if (!this.sourceUpdater_ || !this.getMediaInfo_()) {
  46794. this.logger_('skipping remove because no source updater or starting media info'); // nothing to remove if we haven't processed any media
  46795. return;
  46796. } // set it to one to complete this function's removes
  46797. var removesRemaining = 1;
  46798. var removeFinished = function removeFinished() {
  46799. removesRemaining--;
  46800. if (removesRemaining === 0) {
  46801. done();
  46802. }
  46803. };
  46804. if (force || !this.audioDisabled_) {
  46805. removesRemaining++;
  46806. this.sourceUpdater_.removeAudio(start, end, removeFinished);
  46807. } // While it would be better to only remove video if the main loader has video, this
  46808. // should be safe with audio only as removeVideo will call back even if there's no
  46809. // video buffer.
  46810. //
  46811. // In theory we can check to see if there's video before calling the remove, but in
  46812. // the event that we're switching between renditions and from video to audio only
  46813. // (when we add support for that), we may need to clear the video contents despite
  46814. // what the new media will contain.
  46815. if (force || this.loaderType_ === 'main') {
  46816. this.gopBuffer_ = removeGopBuffer(this.gopBuffer_, start, end, this.timeMapping_);
  46817. removesRemaining++;
  46818. this.sourceUpdater_.removeVideo(start, end, removeFinished);
  46819. } // remove any captions and ID3 tags
  46820. for (var track in this.inbandTextTracks_) {
  46821. removeCuesFromTrack(start, end, this.inbandTextTracks_[track]);
  46822. }
  46823. removeCuesFromTrack(start, end, this.segmentMetadataTrack_); // finished this function's removes
  46824. removeFinished();
  46825. }
  46826. /**
  46827. * (re-)schedule monitorBufferTick_ to run as soon as possible
  46828. *
  46829. * @private
  46830. */
  46831. ;
  46832. _proto.monitorBuffer_ = function monitorBuffer_() {
  46833. if (this.checkBufferTimeout_) {
  46834. window.clearTimeout(this.checkBufferTimeout_);
  46835. }
  46836. this.checkBufferTimeout_ = window.setTimeout(this.monitorBufferTick_.bind(this), 1);
  46837. }
  46838. /**
  46839. * As long as the SegmentLoader is in the READY state, periodically
  46840. * invoke fillBuffer_().
  46841. *
  46842. * @private
  46843. */
  46844. ;
  46845. _proto.monitorBufferTick_ = function monitorBufferTick_() {
  46846. if (this.state === 'READY') {
  46847. this.fillBuffer_();
  46848. }
  46849. if (this.checkBufferTimeout_) {
  46850. window.clearTimeout(this.checkBufferTimeout_);
  46851. }
  46852. this.checkBufferTimeout_ = window.setTimeout(this.monitorBufferTick_.bind(this), CHECK_BUFFER_DELAY);
  46853. }
  46854. /**
  46855. * fill the buffer with segements unless the sourceBuffers are
  46856. * currently updating
  46857. *
  46858. * Note: this function should only ever be called by monitorBuffer_
  46859. * and never directly
  46860. *
  46861. * @private
  46862. */
  46863. ;
  46864. _proto.fillBuffer_ = function fillBuffer_() {
  46865. // TODO since the source buffer maintains a queue, and we shouldn't call this function
  46866. // except when we're ready for the next segment, this check can most likely be removed
  46867. if (this.sourceUpdater_.updating()) {
  46868. return;
  46869. } // see if we need to begin loading immediately
  46870. var segmentInfo = this.chooseNextRequest_();
  46871. if (!segmentInfo) {
  46872. return;
  46873. }
  46874. if (typeof segmentInfo.timestampOffset === 'number') {
  46875. this.isPendingTimestampOffset_ = false;
  46876. this.timelineChangeController_.pendingTimelineChange({
  46877. type: this.loaderType_,
  46878. from: this.currentTimeline_,
  46879. to: segmentInfo.timeline
  46880. });
  46881. }
  46882. this.loadSegment_(segmentInfo);
  46883. }
  46884. /**
  46885. * Determines if we should call endOfStream on the media source based
  46886. * on the state of the buffer or if appened segment was the final
  46887. * segment in the playlist.
  46888. *
  46889. * @param {number} [mediaIndex] the media index of segment we last appended
  46890. * @param {Object} [playlist] a media playlist object
  46891. * @return {boolean} do we need to call endOfStream on the MediaSource
  46892. */
  46893. ;
  46894. _proto.isEndOfStream_ = function isEndOfStream_(mediaIndex, playlist, partIndex) {
  46895. if (mediaIndex === void 0) {
  46896. mediaIndex = this.mediaIndex;
  46897. }
  46898. if (playlist === void 0) {
  46899. playlist = this.playlist_;
  46900. }
  46901. if (partIndex === void 0) {
  46902. partIndex = this.partIndex;
  46903. }
  46904. if (!playlist || !this.mediaSource_) {
  46905. return false;
  46906. }
  46907. var segment = typeof mediaIndex === 'number' && playlist.segments[mediaIndex]; // mediaIndex is zero based but length is 1 based
  46908. var appendedLastSegment = mediaIndex + 1 === playlist.segments.length; // true if there are no parts, or this is the last part.
  46909. 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
  46910. // so that MediaSources can trigger the `ended` event when it runs out of
  46911. // buffered data instead of waiting for me
  46912. return playlist.endList && this.mediaSource_.readyState === 'open' && appendedLastSegment && appendedLastPart;
  46913. }
  46914. /**
  46915. * Determines what request should be made given current segment loader state.
  46916. *
  46917. * @return {Object} a request object that describes the segment/part to load
  46918. */
  46919. ;
  46920. _proto.chooseNextRequest_ = function chooseNextRequest_() {
  46921. var buffered = this.buffered_();
  46922. var bufferedEnd = lastBufferedEnd(buffered) || 0;
  46923. var bufferedTime = timeAheadOf(buffered, this.currentTime_());
  46924. var preloaded = !this.hasPlayed_() && bufferedTime >= 1;
  46925. var haveEnoughBuffer = bufferedTime >= this.goalBufferLength_();
  46926. var segments = this.playlist_.segments; // return no segment if:
  46927. // 1. we don't have segments
  46928. // 2. The video has not yet played and we already downloaded a segment
  46929. // 3. we already have enough buffered time
  46930. if (!segments.length || preloaded || haveEnoughBuffer) {
  46931. return null;
  46932. }
  46933. this.syncPoint_ = this.syncPoint_ || this.syncController_.getSyncPoint(this.playlist_, this.duration_(), this.currentTimeline_, this.currentTime_());
  46934. var next = {
  46935. partIndex: null,
  46936. mediaIndex: null,
  46937. startOfSegment: null,
  46938. playlist: this.playlist_,
  46939. isSyncRequest: Boolean(!this.syncPoint_)
  46940. };
  46941. if (next.isSyncRequest) {
  46942. next.mediaIndex = getSyncSegmentCandidate(this.currentTimeline_, segments, bufferedEnd);
  46943. } else if (this.mediaIndex !== null) {
  46944. var segment = segments[this.mediaIndex];
  46945. var partIndex = typeof this.partIndex === 'number' ? this.partIndex : -1;
  46946. next.startOfSegment = segment.end ? segment.end : bufferedEnd;
  46947. if (segment.parts && segment.parts[partIndex + 1]) {
  46948. next.mediaIndex = this.mediaIndex;
  46949. next.partIndex = partIndex + 1;
  46950. } else {
  46951. next.mediaIndex = this.mediaIndex + 1;
  46952. }
  46953. } else {
  46954. // Find the segment containing the end of the buffer or current time.
  46955. var _Playlist$getMediaInf = Playlist.getMediaInfoForTime({
  46956. experimentalExactManifestTimings: this.experimentalExactManifestTimings,
  46957. playlist: this.playlist_,
  46958. currentTime: this.fetchAtBuffer_ ? bufferedEnd : this.currentTime_(),
  46959. startingPartIndex: this.syncPoint_.partIndex,
  46960. startingSegmentIndex: this.syncPoint_.segmentIndex,
  46961. startTime: this.syncPoint_.time
  46962. }),
  46963. segmentIndex = _Playlist$getMediaInf.segmentIndex,
  46964. startTime = _Playlist$getMediaInf.startTime,
  46965. _partIndex = _Playlist$getMediaInf.partIndex;
  46966. next.getMediaInfoForTime = this.fetchAtBuffer_ ? "bufferedEnd " + bufferedEnd : "currentTime " + this.currentTime_();
  46967. next.mediaIndex = segmentIndex;
  46968. next.startOfSegment = startTime;
  46969. next.partIndex = _partIndex;
  46970. }
  46971. var nextSegment = segments[next.mediaIndex];
  46972. var nextPart = nextSegment && typeof next.partIndex === 'number' && nextSegment.parts && nextSegment.parts[next.partIndex]; // if the next segment index is invalid or
  46973. // the next partIndex is invalid do not choose a next segment.
  46974. if (!nextSegment || typeof next.partIndex === 'number' && !nextPart) {
  46975. return null;
  46976. } // if the next segment has parts, and we don't have a partIndex.
  46977. // Set partIndex to 0
  46978. if (typeof next.partIndex !== 'number' && nextSegment.parts) {
  46979. next.partIndex = 0;
  46980. nextPart = nextSegment.parts[0];
  46981. } // if we have no buffered data then we need to make sure
  46982. // that the next part we append is "independent" if possible.
  46983. // So we check if the previous part is independent, and request
  46984. // it if it is.
  46985. if (!bufferedTime && nextPart && !nextPart.independent) {
  46986. if (next.partIndex === 0) {
  46987. var lastSegment = segments[next.mediaIndex - 1];
  46988. var lastSegmentLastPart = lastSegment.parts && lastSegment.parts.length && lastSegment.parts[lastSegment.parts.length - 1];
  46989. if (lastSegmentLastPart && lastSegmentLastPart.independent) {
  46990. next.mediaIndex -= 1;
  46991. next.partIndex = lastSegment.parts.length - 1;
  46992. next.independent = 'previous segment';
  46993. }
  46994. } else if (nextSegment.parts[next.partIndex - 1].independent) {
  46995. next.partIndex -= 1;
  46996. next.independent = 'previous part';
  46997. }
  46998. }
  46999. var ended = this.mediaSource_ && this.mediaSource_.readyState === 'ended'; // do not choose a next segment if all of the following:
  47000. // 1. this is the last segment in the playlist
  47001. // 2. end of stream has been called on the media source already
  47002. // 3. the player is not seeking
  47003. if (next.mediaIndex >= segments.length - 1 && ended && !this.seeking_()) {
  47004. return null;
  47005. }
  47006. return this.generateSegmentInfo_(next);
  47007. };
  47008. _proto.generateSegmentInfo_ = function generateSegmentInfo_(options) {
  47009. var independent = options.independent,
  47010. playlist = options.playlist,
  47011. mediaIndex = options.mediaIndex,
  47012. startOfSegment = options.startOfSegment,
  47013. isSyncRequest = options.isSyncRequest,
  47014. partIndex = options.partIndex,
  47015. forceTimestampOffset = options.forceTimestampOffset,
  47016. getMediaInfoForTime = options.getMediaInfoForTime;
  47017. var segment = playlist.segments[mediaIndex];
  47018. var part = typeof partIndex === 'number' && segment.parts[partIndex];
  47019. var segmentInfo = {
  47020. requestId: 'segment-loader-' + Math.random(),
  47021. // resolve the segment URL relative to the playlist
  47022. uri: part && part.resolvedUri || segment.resolvedUri,
  47023. // the segment's mediaIndex at the time it was requested
  47024. mediaIndex: mediaIndex,
  47025. partIndex: part ? partIndex : null,
  47026. // whether or not to update the SegmentLoader's state with this
  47027. // segment's mediaIndex
  47028. isSyncRequest: isSyncRequest,
  47029. startOfSegment: startOfSegment,
  47030. // the segment's playlist
  47031. playlist: playlist,
  47032. // unencrypted bytes of the segment
  47033. bytes: null,
  47034. // when a key is defined for this segment, the encrypted bytes
  47035. encryptedBytes: null,
  47036. // The target timestampOffset for this segment when we append it
  47037. // to the source buffer
  47038. timestampOffset: null,
  47039. // The timeline that the segment is in
  47040. timeline: segment.timeline,
  47041. // The expected duration of the segment in seconds
  47042. duration: part && part.duration || segment.duration,
  47043. // retain the segment in case the playlist updates while doing an async process
  47044. segment: segment,
  47045. part: part,
  47046. byteLength: 0,
  47047. transmuxer: this.transmuxer_,
  47048. // type of getMediaInfoForTime that was used to get this segment
  47049. getMediaInfoForTime: getMediaInfoForTime,
  47050. independent: independent
  47051. };
  47052. var overrideCheck = typeof forceTimestampOffset !== 'undefined' ? forceTimestampOffset : this.isPendingTimestampOffset_;
  47053. segmentInfo.timestampOffset = this.timestampOffsetForSegment_({
  47054. segmentTimeline: segment.timeline,
  47055. currentTimeline: this.currentTimeline_,
  47056. startOfSegment: startOfSegment,
  47057. buffered: this.buffered_(),
  47058. overrideCheck: overrideCheck
  47059. });
  47060. var audioBufferedEnd = lastBufferedEnd(this.sourceUpdater_.audioBuffered());
  47061. if (typeof audioBufferedEnd === 'number') {
  47062. // since the transmuxer is using the actual timing values, but the buffer is
  47063. // adjusted by the timestamp offset, we must adjust the value here
  47064. segmentInfo.audioAppendStart = audioBufferedEnd - this.sourceUpdater_.audioTimestampOffset();
  47065. }
  47066. if (this.sourceUpdater_.videoBuffered().length) {
  47067. segmentInfo.gopsToAlignWith = gopsSafeToAlignWith(this.gopBuffer_, // since the transmuxer is using the actual timing values, but the time is
  47068. // adjusted by the timestmap offset, we must adjust the value here
  47069. this.currentTime_() - this.sourceUpdater_.videoTimestampOffset(), this.timeMapping_);
  47070. }
  47071. return segmentInfo;
  47072. } // get the timestampoffset for a segment,
  47073. // added so that vtt segment loader can override and prevent
  47074. // adding timestamp offsets.
  47075. ;
  47076. _proto.timestampOffsetForSegment_ = function timestampOffsetForSegment_(options) {
  47077. return timestampOffsetForSegment(options);
  47078. }
  47079. /**
  47080. * Determines if the network has enough bandwidth to complete the current segment
  47081. * request in a timely manner. If not, the request will be aborted early and bandwidth
  47082. * updated to trigger a playlist switch.
  47083. *
  47084. * @param {Object} stats
  47085. * Object containing stats about the request timing and size
  47086. * @private
  47087. */
  47088. ;
  47089. _proto.earlyAbortWhenNeeded_ = function earlyAbortWhenNeeded_(stats) {
  47090. if (this.vhs_.tech_.paused() || // Don't abort if the current playlist is on the lowestEnabledRendition
  47091. // TODO: Replace using timeout with a boolean indicating whether this playlist is
  47092. // the lowestEnabledRendition.
  47093. !this.xhrOptions_.timeout || // Don't abort if we have no bandwidth information to estimate segment sizes
  47094. !this.playlist_.attributes.BANDWIDTH) {
  47095. return;
  47096. } // Wait at least 1 second since the first byte of data has been received before
  47097. // using the calculated bandwidth from the progress event to allow the bitrate
  47098. // to stabilize
  47099. if (Date.now() - (stats.firstBytesReceivedAt || Date.now()) < 1000) {
  47100. return;
  47101. }
  47102. var currentTime = this.currentTime_();
  47103. var measuredBandwidth = stats.bandwidth;
  47104. var segmentDuration = this.pendingSegment_.duration;
  47105. var requestTimeRemaining = Playlist.estimateSegmentRequestTime(segmentDuration, measuredBandwidth, this.playlist_, stats.bytesReceived); // Subtract 1 from the timeUntilRebuffer so we still consider an early abort
  47106. // if we are only left with less than 1 second when the request completes.
  47107. // A negative timeUntilRebuffering indicates we are already rebuffering
  47108. var timeUntilRebuffer$1 = timeUntilRebuffer(this.buffered_(), currentTime, this.vhs_.tech_.playbackRate()) - 1; // Only consider aborting early if the estimated time to finish the download
  47109. // is larger than the estimated time until the player runs out of forward buffer
  47110. if (requestTimeRemaining <= timeUntilRebuffer$1) {
  47111. return;
  47112. }
  47113. var switchCandidate = minRebufferMaxBandwidthSelector({
  47114. master: this.vhs_.playlists.master,
  47115. currentTime: currentTime,
  47116. bandwidth: measuredBandwidth,
  47117. duration: this.duration_(),
  47118. segmentDuration: segmentDuration,
  47119. timeUntilRebuffer: timeUntilRebuffer$1,
  47120. currentTimeline: this.currentTimeline_,
  47121. syncController: this.syncController_
  47122. });
  47123. if (!switchCandidate) {
  47124. return;
  47125. }
  47126. var rebufferingImpact = requestTimeRemaining - timeUntilRebuffer$1;
  47127. var timeSavedBySwitching = rebufferingImpact - switchCandidate.rebufferingImpact;
  47128. var minimumTimeSaving = 0.5; // If we are already rebuffering, increase the amount of variance we add to the
  47129. // potential round trip time of the new request so that we are not too aggressive
  47130. // with switching to a playlist that might save us a fraction of a second.
  47131. if (timeUntilRebuffer$1 <= TIME_FUDGE_FACTOR) {
  47132. minimumTimeSaving = 1;
  47133. }
  47134. if (!switchCandidate.playlist || switchCandidate.playlist.uri === this.playlist_.uri || timeSavedBySwitching < minimumTimeSaving) {
  47135. return;
  47136. } // set the bandwidth to that of the desired playlist being sure to scale by
  47137. // BANDWIDTH_VARIANCE and add one so the playlist selector does not exclude it
  47138. // don't trigger a bandwidthupdate as the bandwidth is artifial
  47139. this.bandwidth = switchCandidate.playlist.attributes.BANDWIDTH * Config.BANDWIDTH_VARIANCE + 1;
  47140. this.trigger('earlyabort');
  47141. };
  47142. _proto.handleAbort_ = function handleAbort_(segmentInfo) {
  47143. this.logger_("Aborting " + segmentInfoString(segmentInfo));
  47144. this.mediaRequestsAborted += 1;
  47145. }
  47146. /**
  47147. * XHR `progress` event handler
  47148. *
  47149. * @param {Event}
  47150. * The XHR `progress` event
  47151. * @param {Object} simpleSegment
  47152. * A simplified segment object copy
  47153. * @private
  47154. */
  47155. ;
  47156. _proto.handleProgress_ = function handleProgress_(event, simpleSegment) {
  47157. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  47158. if (this.checkForAbort_(simpleSegment.requestId)) {
  47159. return;
  47160. }
  47161. this.trigger('progress');
  47162. };
  47163. _proto.handleTrackInfo_ = function handleTrackInfo_(simpleSegment, trackInfo) {
  47164. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  47165. if (this.checkForAbort_(simpleSegment.requestId)) {
  47166. return;
  47167. }
  47168. if (this.checkForIllegalMediaSwitch(trackInfo)) {
  47169. return;
  47170. }
  47171. trackInfo = trackInfo || {}; // When we have track info, determine what media types this loader is dealing with.
  47172. // Guard against cases where we're not getting track info at all until we are
  47173. // certain that all streams will provide it.
  47174. if (!shallowEqual(this.currentMediaInfo_, trackInfo)) {
  47175. this.appendInitSegment_ = {
  47176. audio: true,
  47177. video: true
  47178. };
  47179. this.startingMediaInfo_ = trackInfo;
  47180. this.currentMediaInfo_ = trackInfo;
  47181. this.logger_('trackinfo update', trackInfo);
  47182. this.trigger('trackinfo');
  47183. } // trackinfo may cause an abort if the trackinfo
  47184. // causes a codec change to an unsupported codec.
  47185. if (this.checkForAbort_(simpleSegment.requestId)) {
  47186. return;
  47187. } // set trackinfo on the pending segment so that
  47188. // it can append.
  47189. this.pendingSegment_.trackInfo = trackInfo; // check if any calls were waiting on the track info
  47190. if (this.hasEnoughInfoToAppend_()) {
  47191. this.processCallQueue_();
  47192. }
  47193. };
  47194. _proto.handleTimingInfo_ = function handleTimingInfo_(simpleSegment, mediaType, timeType, time) {
  47195. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  47196. if (this.checkForAbort_(simpleSegment.requestId)) {
  47197. return;
  47198. }
  47199. var segmentInfo = this.pendingSegment_;
  47200. var timingInfoProperty = timingInfoPropertyForMedia(mediaType);
  47201. segmentInfo[timingInfoProperty] = segmentInfo[timingInfoProperty] || {};
  47202. segmentInfo[timingInfoProperty][timeType] = time;
  47203. this.logger_("timinginfo: " + mediaType + " - " + timeType + " - " + time); // check if any calls were waiting on the timing info
  47204. if (this.hasEnoughInfoToAppend_()) {
  47205. this.processCallQueue_();
  47206. }
  47207. };
  47208. _proto.handleCaptions_ = function handleCaptions_(simpleSegment, captionData) {
  47209. var _this2 = this;
  47210. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  47211. if (this.checkForAbort_(simpleSegment.requestId)) {
  47212. return;
  47213. } // This could only happen with fmp4 segments, but
  47214. // should still not happen in general
  47215. if (captionData.length === 0) {
  47216. this.logger_('SegmentLoader received no captions from a caption event');
  47217. return;
  47218. }
  47219. var segmentInfo = this.pendingSegment_; // Wait until we have some video data so that caption timing
  47220. // can be adjusted by the timestamp offset
  47221. if (!segmentInfo.hasAppendedData_) {
  47222. this.metadataQueue_.caption.push(this.handleCaptions_.bind(this, simpleSegment, captionData));
  47223. return;
  47224. }
  47225. var timestampOffset = this.sourceUpdater_.videoTimestampOffset() === null ? this.sourceUpdater_.audioTimestampOffset() : this.sourceUpdater_.videoTimestampOffset();
  47226. var captionTracks = {}; // get total start/end and captions for each track/stream
  47227. captionData.forEach(function (caption) {
  47228. // caption.stream is actually a track name...
  47229. // set to the existing values in tracks or default values
  47230. captionTracks[caption.stream] = captionTracks[caption.stream] || {
  47231. // Infinity, as any other value will be less than this
  47232. startTime: Infinity,
  47233. captions: [],
  47234. // 0 as an other value will be more than this
  47235. endTime: 0
  47236. };
  47237. var captionTrack = captionTracks[caption.stream];
  47238. captionTrack.startTime = Math.min(captionTrack.startTime, caption.startTime + timestampOffset);
  47239. captionTrack.endTime = Math.max(captionTrack.endTime, caption.endTime + timestampOffset);
  47240. captionTrack.captions.push(caption);
  47241. });
  47242. Object.keys(captionTracks).forEach(function (trackName) {
  47243. var _captionTracks$trackN = captionTracks[trackName],
  47244. startTime = _captionTracks$trackN.startTime,
  47245. endTime = _captionTracks$trackN.endTime,
  47246. captions = _captionTracks$trackN.captions;
  47247. var inbandTextTracks = _this2.inbandTextTracks_;
  47248. _this2.logger_("adding cues from " + startTime + " -> " + endTime + " for " + trackName);
  47249. createCaptionsTrackIfNotExists(inbandTextTracks, _this2.vhs_.tech_, trackName); // clear out any cues that start and end at the same time period for the same track.
  47250. // We do this because a rendition change that also changes the timescale for captions
  47251. // will result in captions being re-parsed for certain segments. If we add them again
  47252. // without clearing we will have two of the same captions visible.
  47253. removeCuesFromTrack(startTime, endTime, inbandTextTracks[trackName]);
  47254. addCaptionData({
  47255. captionArray: captions,
  47256. inbandTextTracks: inbandTextTracks,
  47257. timestampOffset: timestampOffset
  47258. });
  47259. }); // Reset stored captions since we added parsed
  47260. // captions to a text track at this point
  47261. if (this.transmuxer_) {
  47262. this.transmuxer_.postMessage({
  47263. action: 'clearParsedMp4Captions'
  47264. });
  47265. }
  47266. };
  47267. _proto.handleId3_ = function handleId3_(simpleSegment, id3Frames, dispatchType) {
  47268. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  47269. if (this.checkForAbort_(simpleSegment.requestId)) {
  47270. return;
  47271. }
  47272. var segmentInfo = this.pendingSegment_; // we need to have appended data in order for the timestamp offset to be set
  47273. if (!segmentInfo.hasAppendedData_) {
  47274. this.metadataQueue_.id3.push(this.handleId3_.bind(this, simpleSegment, id3Frames, dispatchType));
  47275. return;
  47276. }
  47277. 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
  47278. // audio/video source with a metadata track, and an alt audio with a metadata track.
  47279. // However, this probably won't happen, and if it does it can be handled then.
  47280. createMetadataTrackIfNotExists(this.inbandTextTracks_, dispatchType, this.vhs_.tech_);
  47281. addMetadata({
  47282. inbandTextTracks: this.inbandTextTracks_,
  47283. metadataArray: id3Frames,
  47284. timestampOffset: timestampOffset,
  47285. videoDuration: this.duration_()
  47286. });
  47287. };
  47288. _proto.processMetadataQueue_ = function processMetadataQueue_() {
  47289. this.metadataQueue_.id3.forEach(function (fn) {
  47290. return fn();
  47291. });
  47292. this.metadataQueue_.caption.forEach(function (fn) {
  47293. return fn();
  47294. });
  47295. this.metadataQueue_.id3 = [];
  47296. this.metadataQueue_.caption = [];
  47297. };
  47298. _proto.processCallQueue_ = function processCallQueue_() {
  47299. var callQueue = this.callQueue_; // Clear out the queue before the queued functions are run, since some of the
  47300. // functions may check the length of the load queue and default to pushing themselves
  47301. // back onto the queue.
  47302. this.callQueue_ = [];
  47303. callQueue.forEach(function (fun) {
  47304. return fun();
  47305. });
  47306. };
  47307. _proto.processLoadQueue_ = function processLoadQueue_() {
  47308. var loadQueue = this.loadQueue_; // Clear out the queue before the queued functions are run, since some of the
  47309. // functions may check the length of the load queue and default to pushing themselves
  47310. // back onto the queue.
  47311. this.loadQueue_ = [];
  47312. loadQueue.forEach(function (fun) {
  47313. return fun();
  47314. });
  47315. }
  47316. /**
  47317. * Determines whether the loader has enough info to load the next segment.
  47318. *
  47319. * @return {boolean}
  47320. * Whether or not the loader has enough info to load the next segment
  47321. */
  47322. ;
  47323. _proto.hasEnoughInfoToLoad_ = function hasEnoughInfoToLoad_() {
  47324. // Since primary timing goes by video, only the audio loader potentially needs to wait
  47325. // to load.
  47326. if (this.loaderType_ !== 'audio') {
  47327. return true;
  47328. }
  47329. var segmentInfo = this.pendingSegment_; // A fill buffer must have already run to establish a pending segment before there's
  47330. // enough info to load.
  47331. if (!segmentInfo) {
  47332. return false;
  47333. } // The first segment can and should be loaded immediately so that source buffers are
  47334. // created together (before appending). Source buffer creation uses the presence of
  47335. // audio and video data to determine whether to create audio/video source buffers, and
  47336. // uses processed (transmuxed or parsed) media to determine the types required.
  47337. if (!this.getCurrentMediaInfo_()) {
  47338. return true;
  47339. }
  47340. if ( // Technically, instead of waiting to load a segment on timeline changes, a segment
  47341. // can be requested and downloaded and only wait before it is transmuxed or parsed.
  47342. // But in practice, there are a few reasons why it is better to wait until a loader
  47343. // is ready to append that segment before requesting and downloading:
  47344. //
  47345. // 1. Because audio and main loaders cross discontinuities together, if this loader
  47346. // is waiting for the other to catch up, then instead of requesting another
  47347. // segment and using up more bandwidth, by not yet loading, more bandwidth is
  47348. // allotted to the loader currently behind.
  47349. // 2. media-segment-request doesn't have to have logic to consider whether a segment
  47350. // is ready to be processed or not, isolating the queueing behavior to the loader.
  47351. // 3. The audio loader bases some of its segment properties on timing information
  47352. // provided by the main loader, meaning that, if the logic for waiting on
  47353. // processing was in media-segment-request, then it would also need to know how
  47354. // to re-generate the segment information after the main loader caught up.
  47355. shouldWaitForTimelineChange({
  47356. timelineChangeController: this.timelineChangeController_,
  47357. currentTimeline: this.currentTimeline_,
  47358. segmentTimeline: segmentInfo.timeline,
  47359. loaderType: this.loaderType_,
  47360. audioDisabled: this.audioDisabled_
  47361. })) {
  47362. return false;
  47363. }
  47364. return true;
  47365. };
  47366. _proto.getCurrentMediaInfo_ = function getCurrentMediaInfo_(segmentInfo) {
  47367. if (segmentInfo === void 0) {
  47368. segmentInfo = this.pendingSegment_;
  47369. }
  47370. return segmentInfo && segmentInfo.trackInfo || this.currentMediaInfo_;
  47371. };
  47372. _proto.getMediaInfo_ = function getMediaInfo_(segmentInfo) {
  47373. if (segmentInfo === void 0) {
  47374. segmentInfo = this.pendingSegment_;
  47375. }
  47376. return this.getCurrentMediaInfo_(segmentInfo) || this.startingMediaInfo_;
  47377. };
  47378. _proto.getPendingSegmentPlaylist = function getPendingSegmentPlaylist() {
  47379. return this.pendingSegment_ ? this.pendingSegment_.playlist : null;
  47380. };
  47381. _proto.hasEnoughInfoToAppend_ = function hasEnoughInfoToAppend_() {
  47382. if (!this.sourceUpdater_.ready()) {
  47383. return false;
  47384. } // If content needs to be removed or the loader is waiting on an append reattempt,
  47385. // then no additional content should be appended until the prior append is resolved.
  47386. if (this.waitingOnRemove_ || this.quotaExceededErrorRetryTimeout_) {
  47387. return false;
  47388. }
  47389. var segmentInfo = this.pendingSegment_;
  47390. var trackInfo = this.getCurrentMediaInfo_(); // no segment to append any data for or
  47391. // we do not have information on this specific
  47392. // segment yet
  47393. if (!segmentInfo || !trackInfo) {
  47394. return false;
  47395. }
  47396. var hasAudio = trackInfo.hasAudio,
  47397. hasVideo = trackInfo.hasVideo,
  47398. isMuxed = trackInfo.isMuxed;
  47399. if (hasVideo && !segmentInfo.videoTimingInfo) {
  47400. return false;
  47401. } // muxed content only relies on video timing information for now.
  47402. if (hasAudio && !this.audioDisabled_ && !isMuxed && !segmentInfo.audioTimingInfo) {
  47403. return false;
  47404. }
  47405. if (shouldWaitForTimelineChange({
  47406. timelineChangeController: this.timelineChangeController_,
  47407. currentTimeline: this.currentTimeline_,
  47408. segmentTimeline: segmentInfo.timeline,
  47409. loaderType: this.loaderType_,
  47410. audioDisabled: this.audioDisabled_
  47411. })) {
  47412. return false;
  47413. }
  47414. return true;
  47415. };
  47416. _proto.handleData_ = function handleData_(simpleSegment, result) {
  47417. this.earlyAbortWhenNeeded_(simpleSegment.stats);
  47418. if (this.checkForAbort_(simpleSegment.requestId)) {
  47419. return;
  47420. } // If there's anything in the call queue, then this data came later and should be
  47421. // executed after the calls currently queued.
  47422. if (this.callQueue_.length || !this.hasEnoughInfoToAppend_()) {
  47423. this.callQueue_.push(this.handleData_.bind(this, simpleSegment, result));
  47424. return;
  47425. }
  47426. var segmentInfo = this.pendingSegment_; // update the time mapping so we can translate from display time to media time
  47427. this.setTimeMapping_(segmentInfo.timeline); // for tracking overall stats
  47428. this.updateMediaSecondsLoaded_(segmentInfo.part || segmentInfo.segment); // Note that the state isn't changed from loading to appending. This is because abort
  47429. // logic may change behavior depending on the state, and changing state too early may
  47430. // inflate our estimates of bandwidth. In the future this should be re-examined to
  47431. // note more granular states.
  47432. // don't process and append data if the mediaSource is closed
  47433. if (this.mediaSource_.readyState === 'closed') {
  47434. return;
  47435. } // if this request included an initialization segment, save that data
  47436. // to the initSegment cache
  47437. if (simpleSegment.map) {
  47438. simpleSegment.map = this.initSegmentForMap(simpleSegment.map, true); // move over init segment properties to media request
  47439. segmentInfo.segment.map = simpleSegment.map;
  47440. } // if this request included a segment key, save that data in the cache
  47441. if (simpleSegment.key) {
  47442. this.segmentKey(simpleSegment.key, true);
  47443. }
  47444. segmentInfo.isFmp4 = simpleSegment.isFmp4;
  47445. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  47446. if (segmentInfo.isFmp4) {
  47447. this.trigger('fmp4');
  47448. segmentInfo.timingInfo.start = segmentInfo[timingInfoPropertyForMedia(result.type)].start;
  47449. } else {
  47450. var trackInfo = this.getCurrentMediaInfo_();
  47451. var useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  47452. var firstVideoFrameTimeForData;
  47453. if (useVideoTimingInfo) {
  47454. firstVideoFrameTimeForData = segmentInfo.videoTimingInfo.start;
  47455. } // Segment loader knows more about segment timing than the transmuxer (in certain
  47456. // aspects), so make any changes required for a more accurate start time.
  47457. // Don't set the end time yet, as the segment may not be finished processing.
  47458. segmentInfo.timingInfo.start = this.trueSegmentStart_({
  47459. currentStart: segmentInfo.timingInfo.start,
  47460. playlist: segmentInfo.playlist,
  47461. mediaIndex: segmentInfo.mediaIndex,
  47462. currentVideoTimestampOffset: this.sourceUpdater_.videoTimestampOffset(),
  47463. useVideoTimingInfo: useVideoTimingInfo,
  47464. firstVideoFrameTimeForData: firstVideoFrameTimeForData,
  47465. videoTimingInfo: segmentInfo.videoTimingInfo,
  47466. audioTimingInfo: segmentInfo.audioTimingInfo
  47467. });
  47468. } // Init segments for audio and video only need to be appended in certain cases. Now
  47469. // that data is about to be appended, we can check the final cases to determine
  47470. // whether we should append an init segment.
  47471. this.updateAppendInitSegmentStatus(segmentInfo, result.type); // Timestamp offset should be updated once we get new data and have its timing info,
  47472. // as we use the start of the segment to offset the best guess (playlist provided)
  47473. // timestamp offset.
  47474. this.updateSourceBufferTimestampOffset_(segmentInfo); // if this is a sync request we need to determine whether it should
  47475. // be appended or not.
  47476. if (segmentInfo.isSyncRequest) {
  47477. // first save/update our timing info for this segment.
  47478. // this is what allows us to choose an accurate segment
  47479. // and the main reason we make a sync request.
  47480. this.updateTimingInfoEnd_(segmentInfo);
  47481. this.syncController_.saveSegmentTimingInfo({
  47482. segmentInfo: segmentInfo,
  47483. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  47484. });
  47485. var next = this.chooseNextRequest_(); // If the sync request isn't the segment that would be requested next
  47486. // after taking into account its timing info, do not append it.
  47487. if (next.mediaIndex !== segmentInfo.mediaIndex || next.partIndex !== segmentInfo.partIndex) {
  47488. this.logger_('sync segment was incorrect, not appending');
  47489. return;
  47490. } // otherwise append it like any other segment as our guess was correct.
  47491. this.logger_('sync segment was correct, appending');
  47492. } // Save some state so that in the future anything waiting on first append (and/or
  47493. // timestamp offset(s)) can process immediately. While the extra state isn't optimal,
  47494. // we need some notion of whether the timestamp offset or other relevant information
  47495. // has had a chance to be set.
  47496. segmentInfo.hasAppendedData_ = true; // Now that the timestamp offset should be set, we can append any waiting ID3 tags.
  47497. this.processMetadataQueue_();
  47498. this.appendData_(segmentInfo, result);
  47499. };
  47500. _proto.updateAppendInitSegmentStatus = function updateAppendInitSegmentStatus(segmentInfo, type) {
  47501. // alt audio doesn't manage timestamp offset
  47502. 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
  47503. // segment for each chunk
  47504. !segmentInfo.changedTimestampOffset) {
  47505. // if the timestamp offset changed, the timeline may have changed, so we have to re-
  47506. // append init segments
  47507. this.appendInitSegment_ = {
  47508. audio: true,
  47509. video: true
  47510. };
  47511. }
  47512. if (this.playlistOfLastInitSegment_[type] !== segmentInfo.playlist) {
  47513. // make sure we append init segment on playlist changes, in case the media config
  47514. // changed
  47515. this.appendInitSegment_[type] = true;
  47516. }
  47517. };
  47518. _proto.getInitSegmentAndUpdateState_ = function getInitSegmentAndUpdateState_(_ref4) {
  47519. var type = _ref4.type,
  47520. initSegment = _ref4.initSegment,
  47521. map = _ref4.map,
  47522. playlist = _ref4.playlist; // "The EXT-X-MAP tag specifies how to obtain the Media Initialization Section
  47523. // (Section 3) required to parse the applicable Media Segments. It applies to every
  47524. // Media Segment that appears after it in the Playlist until the next EXT-X-MAP tag
  47525. // or until the end of the playlist."
  47526. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-23#section-4.3.2.5
  47527. if (map) {
  47528. var id = initSegmentId(map);
  47529. if (this.activeInitSegmentId_ === id) {
  47530. // don't need to re-append the init segment if the ID matches
  47531. return null;
  47532. } // a map-specified init segment takes priority over any transmuxed (or otherwise
  47533. // obtained) init segment
  47534. //
  47535. // this also caches the init segment for later use
  47536. initSegment = this.initSegmentForMap(map, true).bytes;
  47537. this.activeInitSegmentId_ = id;
  47538. } // We used to always prepend init segments for video, however, that shouldn't be
  47539. // necessary. Instead, we should only append on changes, similar to what we've always
  47540. // done for audio. This is more important (though may not be that important) for
  47541. // frame-by-frame appending for LHLS, simply because of the increased quantity of
  47542. // appends.
  47543. if (initSegment && this.appendInitSegment_[type]) {
  47544. // Make sure we track the playlist that we last used for the init segment, so that
  47545. // we can re-append the init segment in the event that we get data from a new
  47546. // playlist. Discontinuities and track changes are handled in other sections.
  47547. this.playlistOfLastInitSegment_[type] = playlist; // Disable future init segment appends for this type. Until a change is necessary.
  47548. this.appendInitSegment_[type] = false; // we need to clear out the fmp4 active init segment id, since
  47549. // we are appending the muxer init segment
  47550. this.activeInitSegmentId_ = null;
  47551. return initSegment;
  47552. }
  47553. return null;
  47554. };
  47555. _proto.handleQuotaExceededError_ = function handleQuotaExceededError_(_ref5, error) {
  47556. var _this3 = this;
  47557. var segmentInfo = _ref5.segmentInfo,
  47558. type = _ref5.type,
  47559. bytes = _ref5.bytes;
  47560. var audioBuffered = this.sourceUpdater_.audioBuffered();
  47561. var videoBuffered = this.sourceUpdater_.videoBuffered(); // For now we're ignoring any notion of gaps in the buffer, but they, in theory,
  47562. // should be cleared out during the buffer removals. However, log in case it helps
  47563. // debug.
  47564. if (audioBuffered.length > 1) {
  47565. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the audio buffer: ' + timeRangesToArray(audioBuffered).join(', '));
  47566. }
  47567. if (videoBuffered.length > 1) {
  47568. this.logger_('On QUOTA_EXCEEDED_ERR, found gaps in the video buffer: ' + timeRangesToArray(videoBuffered).join(', '));
  47569. }
  47570. var audioBufferStart = audioBuffered.length ? audioBuffered.start(0) : 0;
  47571. var audioBufferEnd = audioBuffered.length ? audioBuffered.end(audioBuffered.length - 1) : 0;
  47572. var videoBufferStart = videoBuffered.length ? videoBuffered.start(0) : 0;
  47573. var videoBufferEnd = videoBuffered.length ? videoBuffered.end(videoBuffered.length - 1) : 0;
  47574. if (audioBufferEnd - audioBufferStart <= MIN_BACK_BUFFER && videoBufferEnd - videoBufferStart <= MIN_BACK_BUFFER) {
  47575. // Can't remove enough buffer to make room for new segment (or the browser doesn't
  47576. // allow for appends of segments this size). In the future, it may be possible to
  47577. // split up the segment and append in pieces, but for now, error out this playlist
  47578. // in an attempt to switch to a more manageable rendition.
  47579. 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(', ') + ", "));
  47580. this.error({
  47581. message: 'Quota exceeded error with append of a single segment of content',
  47582. excludeUntil: Infinity
  47583. });
  47584. this.trigger('error');
  47585. return;
  47586. } // To try to resolve the quota exceeded error, clear back buffer and retry. This means
  47587. // that the segment-loader should block on future events until this one is handled, so
  47588. // that it doesn't keep moving onto further segments. Adding the call to the call
  47589. // queue will prevent further appends until waitingOnRemove_ and
  47590. // quotaExceededErrorRetryTimeout_ are cleared.
  47591. //
  47592. // Note that this will only block the current loader. In the case of demuxed content,
  47593. // the other load may keep filling as fast as possible. In practice, this should be
  47594. // OK, as it is a rare case when either audio has a high enough bitrate to fill up a
  47595. // source buffer, or video fills without enough room for audio to append (and without
  47596. // the availability of clearing out seconds of back buffer to make room for audio).
  47597. // But it might still be good to handle this case in the future as a TODO.
  47598. this.waitingOnRemove_ = true;
  47599. this.callQueue_.push(this.appendToSourceBuffer_.bind(this, {
  47600. segmentInfo: segmentInfo,
  47601. type: type,
  47602. bytes: bytes
  47603. }));
  47604. var currentTime = this.currentTime_(); // Try to remove as much audio and video as possible to make room for new content
  47605. // before retrying.
  47606. var timeToRemoveUntil = currentTime - MIN_BACK_BUFFER;
  47607. this.logger_("On QUOTA_EXCEEDED_ERR, removing audio/video from 0 to " + timeToRemoveUntil);
  47608. this.remove(0, timeToRemoveUntil, function () {
  47609. _this3.logger_("On QUOTA_EXCEEDED_ERR, retrying append in " + MIN_BACK_BUFFER + "s");
  47610. _this3.waitingOnRemove_ = false; // wait the length of time alotted in the back buffer to prevent wasted
  47611. // attempts (since we can't clear less than the minimum)
  47612. _this3.quotaExceededErrorRetryTimeout_ = window.setTimeout(function () {
  47613. _this3.logger_('On QUOTA_EXCEEDED_ERR, re-processing call queue');
  47614. _this3.quotaExceededErrorRetryTimeout_ = null;
  47615. _this3.processCallQueue_();
  47616. }, MIN_BACK_BUFFER * 1000);
  47617. }, true);
  47618. };
  47619. _proto.handleAppendError_ = function handleAppendError_(_ref6, error) {
  47620. var segmentInfo = _ref6.segmentInfo,
  47621. type = _ref6.type,
  47622. bytes = _ref6.bytes; // if there's no error, nothing to do
  47623. if (!error) {
  47624. return;
  47625. }
  47626. if (error.code === QUOTA_EXCEEDED_ERR) {
  47627. this.handleQuotaExceededError_({
  47628. segmentInfo: segmentInfo,
  47629. type: type,
  47630. bytes: bytes
  47631. }); // A quota exceeded error should be recoverable with a future re-append, so no need
  47632. // to trigger an append error.
  47633. return;
  47634. }
  47635. this.logger_('Received non QUOTA_EXCEEDED_ERR on append', error);
  47636. 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.
  47637. // (see https://w3c.github.io/media-source/#sourcebuffer-append-error).
  47638. //
  47639. // Trigger a special error so that it can be handled separately from normal,
  47640. // recoverable errors.
  47641. this.trigger('appenderror');
  47642. };
  47643. _proto.appendToSourceBuffer_ = function appendToSourceBuffer_(_ref7) {
  47644. var segmentInfo = _ref7.segmentInfo,
  47645. type = _ref7.type,
  47646. initSegment = _ref7.initSegment,
  47647. data = _ref7.data,
  47648. bytes = _ref7.bytes; // If this is a re-append, bytes were already created and don't need to be recreated
  47649. if (!bytes) {
  47650. var segments = [data];
  47651. var byteLength = data.byteLength;
  47652. if (initSegment) {
  47653. // if the media initialization segment is changing, append it before the content
  47654. // segment
  47655. segments.unshift(initSegment);
  47656. byteLength += initSegment.byteLength;
  47657. } // Technically we should be OK appending the init segment separately, however, we
  47658. // haven't yet tested that, and prepending is how we have always done things.
  47659. bytes = concatSegments({
  47660. bytes: byteLength,
  47661. segments: segments
  47662. });
  47663. }
  47664. this.sourceUpdater_.appendBuffer({
  47665. segmentInfo: segmentInfo,
  47666. type: type,
  47667. bytes: bytes
  47668. }, this.handleAppendError_.bind(this, {
  47669. segmentInfo: segmentInfo,
  47670. type: type,
  47671. bytes: bytes
  47672. }));
  47673. };
  47674. _proto.handleSegmentTimingInfo_ = function handleSegmentTimingInfo_(type, requestId, segmentTimingInfo) {
  47675. if (!this.pendingSegment_ || requestId !== this.pendingSegment_.requestId) {
  47676. return;
  47677. }
  47678. var segment = this.pendingSegment_.segment;
  47679. var timingInfoProperty = type + "TimingInfo";
  47680. if (!segment[timingInfoProperty]) {
  47681. segment[timingInfoProperty] = {};
  47682. }
  47683. segment[timingInfoProperty].transmuxerPrependedSeconds = segmentTimingInfo.prependedContentDuration || 0;
  47684. segment[timingInfoProperty].transmuxedPresentationStart = segmentTimingInfo.start.presentation;
  47685. segment[timingInfoProperty].transmuxedDecodeStart = segmentTimingInfo.start.decode;
  47686. segment[timingInfoProperty].transmuxedPresentationEnd = segmentTimingInfo.end.presentation;
  47687. segment[timingInfoProperty].transmuxedDecodeEnd = segmentTimingInfo.end.decode; // mainly used as a reference for debugging
  47688. segment[timingInfoProperty].baseMediaDecodeTime = segmentTimingInfo.baseMediaDecodeTime;
  47689. };
  47690. _proto.appendData_ = function appendData_(segmentInfo, result) {
  47691. var type = result.type,
  47692. data = result.data;
  47693. if (!data || !data.byteLength) {
  47694. return;
  47695. }
  47696. if (type === 'audio' && this.audioDisabled_) {
  47697. return;
  47698. }
  47699. var initSegment = this.getInitSegmentAndUpdateState_({
  47700. type: type,
  47701. initSegment: result.initSegment,
  47702. playlist: segmentInfo.playlist,
  47703. map: segmentInfo.isFmp4 ? segmentInfo.segment.map : null
  47704. });
  47705. this.appendToSourceBuffer_({
  47706. segmentInfo: segmentInfo,
  47707. type: type,
  47708. initSegment: initSegment,
  47709. data: data
  47710. });
  47711. }
  47712. /**
  47713. * load a specific segment from a request into the buffer
  47714. *
  47715. * @private
  47716. */
  47717. ;
  47718. _proto.loadSegment_ = function loadSegment_(segmentInfo) {
  47719. var _this4 = this;
  47720. this.state = 'WAITING';
  47721. this.pendingSegment_ = segmentInfo;
  47722. this.trimBackBuffer_(segmentInfo);
  47723. if (typeof segmentInfo.timestampOffset === 'number') {
  47724. if (this.transmuxer_) {
  47725. this.transmuxer_.postMessage({
  47726. action: 'clearAllMp4Captions'
  47727. });
  47728. }
  47729. }
  47730. if (!this.hasEnoughInfoToLoad_()) {
  47731. this.loadQueue_.push(function () {
  47732. // regenerate the audioAppendStart, timestampOffset, etc as they
  47733. // may have changed since this function was added to the queue.
  47734. var options = _extends_1({}, segmentInfo, {
  47735. forceTimestampOffset: true
  47736. });
  47737. _extends_1(segmentInfo, _this4.generateSegmentInfo_(options));
  47738. _this4.isPendingTimestampOffset_ = false;
  47739. _this4.updateTransmuxerAndRequestSegment_(segmentInfo);
  47740. });
  47741. return;
  47742. }
  47743. this.updateTransmuxerAndRequestSegment_(segmentInfo);
  47744. };
  47745. _proto.updateTransmuxerAndRequestSegment_ = function updateTransmuxerAndRequestSegment_(segmentInfo) {
  47746. var _this5 = this; // We'll update the source buffer's timestamp offset once we have transmuxed data, but
  47747. // the transmuxer still needs to be updated before then.
  47748. //
  47749. // Even though keepOriginalTimestamps is set to true for the transmuxer, timestamp
  47750. // offset must be passed to the transmuxer for stream correcting adjustments.
  47751. if (this.shouldUpdateTransmuxerTimestampOffset_(segmentInfo.timestampOffset)) {
  47752. this.gopBuffer_.length = 0; // gopsToAlignWith was set before the GOP buffer was cleared
  47753. segmentInfo.gopsToAlignWith = [];
  47754. this.timeMapping_ = 0; // reset values in the transmuxer since a discontinuity should start fresh
  47755. this.transmuxer_.postMessage({
  47756. action: 'reset'
  47757. });
  47758. this.transmuxer_.postMessage({
  47759. action: 'setTimestampOffset',
  47760. timestampOffset: segmentInfo.timestampOffset
  47761. });
  47762. }
  47763. var simpleSegment = this.createSimplifiedSegmentObj_(segmentInfo);
  47764. var isEndOfStream = this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex);
  47765. var isWalkingForward = this.mediaIndex !== null;
  47766. var isDiscontinuity = segmentInfo.timeline !== this.currentTimeline_ && // currentTimeline starts at -1, so we shouldn't end the timeline switching to 0,
  47767. // the first timeline
  47768. segmentInfo.timeline > 0;
  47769. var isEndOfTimeline = isEndOfStream || isWalkingForward && isDiscontinuity;
  47770. 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),
  47771. // then this init segment has never been seen before and should be appended.
  47772. //
  47773. // At this point the content type (audio/video or both) is not yet known, but it should be safe to set
  47774. // both to true and leave the decision of whether to append the init segment to append time.
  47775. if (simpleSegment.map && !simpleSegment.map.bytes) {
  47776. this.logger_('going to request init segment.');
  47777. this.appendInitSegment_ = {
  47778. video: true,
  47779. audio: true
  47780. };
  47781. }
  47782. segmentInfo.abortRequests = mediaSegmentRequest({
  47783. xhr: this.vhs_.xhr,
  47784. xhrOptions: this.xhrOptions_,
  47785. decryptionWorker: this.decrypter_,
  47786. segment: simpleSegment,
  47787. abortFn: this.handleAbort_.bind(this, segmentInfo),
  47788. progressFn: this.handleProgress_.bind(this),
  47789. trackInfoFn: this.handleTrackInfo_.bind(this),
  47790. timingInfoFn: this.handleTimingInfo_.bind(this),
  47791. videoSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'video', segmentInfo.requestId),
  47792. audioSegmentTimingInfoFn: this.handleSegmentTimingInfo_.bind(this, 'audio', segmentInfo.requestId),
  47793. captionsFn: this.handleCaptions_.bind(this),
  47794. isEndOfTimeline: isEndOfTimeline,
  47795. endedTimelineFn: function endedTimelineFn() {
  47796. _this5.logger_('received endedtimeline callback');
  47797. },
  47798. id3Fn: this.handleId3_.bind(this),
  47799. dataFn: this.handleData_.bind(this),
  47800. doneFn: this.segmentRequestFinished_.bind(this),
  47801. onTransmuxerLog: function onTransmuxerLog(_ref8) {
  47802. var message = _ref8.message,
  47803. level = _ref8.level,
  47804. stream = _ref8.stream;
  47805. _this5.logger_(segmentInfoString(segmentInfo) + " logged from transmuxer stream " + stream + " as a " + level + ": " + message);
  47806. }
  47807. });
  47808. }
  47809. /**
  47810. * trim the back buffer so that we don't have too much data
  47811. * in the source buffer
  47812. *
  47813. * @private
  47814. *
  47815. * @param {Object} segmentInfo - the current segment
  47816. */
  47817. ;
  47818. _proto.trimBackBuffer_ = function trimBackBuffer_(segmentInfo) {
  47819. var removeToTime = safeBackBufferTrimTime(this.seekable_(), this.currentTime_(), this.playlist_.targetDuration || 10); // Chrome has a hard limit of 150MB of
  47820. // buffer and a very conservative "garbage collector"
  47821. // We manually clear out the old buffer to ensure
  47822. // we don't trigger the QuotaExceeded error
  47823. // on the source buffer during subsequent appends
  47824. if (removeToTime > 0) {
  47825. this.remove(0, removeToTime);
  47826. }
  47827. }
  47828. /**
  47829. * created a simplified copy of the segment object with just the
  47830. * information necessary to perform the XHR and decryption
  47831. *
  47832. * @private
  47833. *
  47834. * @param {Object} segmentInfo - the current segment
  47835. * @return {Object} a simplified segment object copy
  47836. */
  47837. ;
  47838. _proto.createSimplifiedSegmentObj_ = function createSimplifiedSegmentObj_(segmentInfo) {
  47839. var segment = segmentInfo.segment;
  47840. var part = segmentInfo.part;
  47841. var simpleSegment = {
  47842. resolvedUri: part ? part.resolvedUri : segment.resolvedUri,
  47843. byterange: part ? part.byterange : segment.byterange,
  47844. requestId: segmentInfo.requestId,
  47845. transmuxer: segmentInfo.transmuxer,
  47846. audioAppendStart: segmentInfo.audioAppendStart,
  47847. gopsToAlignWith: segmentInfo.gopsToAlignWith,
  47848. part: segmentInfo.part
  47849. };
  47850. var previousSegment = segmentInfo.playlist.segments[segmentInfo.mediaIndex - 1];
  47851. if (previousSegment && previousSegment.timeline === segment.timeline) {
  47852. // The baseStartTime of a segment is used to handle rollover when probing the TS
  47853. // segment to retrieve timing information. Since the probe only looks at the media's
  47854. // times (e.g., PTS and DTS values of the segment), and doesn't consider the
  47855. // player's time (e.g., player.currentTime()), baseStartTime should reflect the
  47856. // media time as well. transmuxedDecodeEnd represents the end time of a segment, in
  47857. // seconds of media time, so should be used here. The previous segment is used since
  47858. // the end of the previous segment should represent the beginning of the current
  47859. // segment, so long as they are on the same timeline.
  47860. if (previousSegment.videoTimingInfo) {
  47861. simpleSegment.baseStartTime = previousSegment.videoTimingInfo.transmuxedDecodeEnd;
  47862. } else if (previousSegment.audioTimingInfo) {
  47863. simpleSegment.baseStartTime = previousSegment.audioTimingInfo.transmuxedDecodeEnd;
  47864. }
  47865. }
  47866. if (segment.key) {
  47867. // if the media sequence is greater than 2^32, the IV will be incorrect
  47868. // assuming 10s segments, that would be about 1300 years
  47869. var iv = segment.key.iv || new Uint32Array([0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence]);
  47870. simpleSegment.key = this.segmentKey(segment.key);
  47871. simpleSegment.key.iv = iv;
  47872. }
  47873. if (segment.map) {
  47874. simpleSegment.map = this.initSegmentForMap(segment.map);
  47875. }
  47876. return simpleSegment;
  47877. };
  47878. _proto.saveTransferStats_ = function saveTransferStats_(stats) {
  47879. // every request counts as a media request even if it has been aborted
  47880. // or canceled due to a timeout
  47881. this.mediaRequests += 1;
  47882. if (stats) {
  47883. this.mediaBytesTransferred += stats.bytesReceived;
  47884. this.mediaTransferDuration += stats.roundTripTime;
  47885. }
  47886. };
  47887. _proto.saveBandwidthRelatedStats_ = function saveBandwidthRelatedStats_(duration, stats) {
  47888. // byteLength will be used for throughput, and should be based on bytes receieved,
  47889. // which we only know at the end of the request and should reflect total bytes
  47890. // downloaded rather than just bytes processed from components of the segment
  47891. this.pendingSegment_.byteLength = stats.bytesReceived;
  47892. if (duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  47893. this.logger_("Ignoring segment's bandwidth because its duration of " + duration + (" is less than the min to record " + MIN_SEGMENT_DURATION_TO_SAVE_STATS));
  47894. return;
  47895. }
  47896. this.bandwidth = stats.bandwidth;
  47897. this.roundTrip = stats.roundTripTime;
  47898. };
  47899. _proto.handleTimeout_ = function handleTimeout_() {
  47900. // although the VTT segment loader bandwidth isn't really used, it's good to
  47901. // maintain functinality between segment loaders
  47902. this.mediaRequestsTimedout += 1;
  47903. this.bandwidth = 1;
  47904. this.roundTrip = NaN;
  47905. this.trigger('bandwidthupdate');
  47906. this.trigger('timeout');
  47907. }
  47908. /**
  47909. * Handle the callback from the segmentRequest function and set the
  47910. * associated SegmentLoader state and errors if necessary
  47911. *
  47912. * @private
  47913. */
  47914. ;
  47915. _proto.segmentRequestFinished_ = function segmentRequestFinished_(error, simpleSegment, result) {
  47916. // TODO handle special cases, e.g., muxed audio/video but only audio in the segment
  47917. // check the call queue directly since this function doesn't need to deal with any
  47918. // data, and can continue even if the source buffers are not set up and we didn't get
  47919. // any data from the segment
  47920. if (this.callQueue_.length) {
  47921. this.callQueue_.push(this.segmentRequestFinished_.bind(this, error, simpleSegment, result));
  47922. return;
  47923. }
  47924. this.saveTransferStats_(simpleSegment.stats); // The request was aborted and the SegmentLoader has already been reset
  47925. if (!this.pendingSegment_) {
  47926. return;
  47927. } // the request was aborted and the SegmentLoader has already started
  47928. // another request. this can happen when the timeout for an aborted
  47929. // request triggers due to a limitation in the XHR library
  47930. // do not count this as any sort of request or we risk double-counting
  47931. if (simpleSegment.requestId !== this.pendingSegment_.requestId) {
  47932. return;
  47933. } // an error occurred from the active pendingSegment_ so reset everything
  47934. if (error) {
  47935. this.pendingSegment_ = null;
  47936. this.state = 'READY'; // aborts are not a true error condition and nothing corrective needs to be done
  47937. if (error.code === REQUEST_ERRORS.ABORTED) {
  47938. return;
  47939. }
  47940. this.pause(); // the error is really just that at least one of the requests timed-out
  47941. // set the bandwidth to a very low value and trigger an ABR switch to
  47942. // take emergency action
  47943. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  47944. this.handleTimeout_();
  47945. return;
  47946. } // if control-flow has arrived here, then the error is real
  47947. // emit an error event to blacklist the current playlist
  47948. this.mediaRequestsErrored += 1;
  47949. this.error(error);
  47950. this.trigger('error');
  47951. return;
  47952. }
  47953. var segmentInfo = this.pendingSegment_; // the response was a success so set any bandwidth stats the request
  47954. // generated for ABR purposes
  47955. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats);
  47956. segmentInfo.endOfAllRequests = simpleSegment.endOfAllRequests;
  47957. if (result.gopInfo) {
  47958. this.gopBuffer_ = updateGopBuffer(this.gopBuffer_, result.gopInfo, this.safeAppend_);
  47959. } // Although we may have already started appending on progress, we shouldn't switch the
  47960. // state away from loading until we are officially done loading the segment data.
  47961. this.state = 'APPENDING'; // used for testing
  47962. this.trigger('appending');
  47963. this.waitForAppendsToComplete_(segmentInfo);
  47964. };
  47965. _proto.setTimeMapping_ = function setTimeMapping_(timeline) {
  47966. var timelineMapping = this.syncController_.mappingForTimeline(timeline);
  47967. if (timelineMapping !== null) {
  47968. this.timeMapping_ = timelineMapping;
  47969. }
  47970. };
  47971. _proto.updateMediaSecondsLoaded_ = function updateMediaSecondsLoaded_(segment) {
  47972. if (typeof segment.start === 'number' && typeof segment.end === 'number') {
  47973. this.mediaSecondsLoaded += segment.end - segment.start;
  47974. } else {
  47975. this.mediaSecondsLoaded += segment.duration;
  47976. }
  47977. };
  47978. _proto.shouldUpdateTransmuxerTimestampOffset_ = function shouldUpdateTransmuxerTimestampOffset_(timestampOffset) {
  47979. if (timestampOffset === null) {
  47980. return false;
  47981. } // note that we're potentially using the same timestamp offset for both video and
  47982. // audio
  47983. if (this.loaderType_ === 'main' && timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  47984. return true;
  47985. }
  47986. if (!this.audioDisabled_ && timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  47987. return true;
  47988. }
  47989. return false;
  47990. };
  47991. _proto.trueSegmentStart_ = function trueSegmentStart_(_ref9) {
  47992. var currentStart = _ref9.currentStart,
  47993. playlist = _ref9.playlist,
  47994. mediaIndex = _ref9.mediaIndex,
  47995. firstVideoFrameTimeForData = _ref9.firstVideoFrameTimeForData,
  47996. currentVideoTimestampOffset = _ref9.currentVideoTimestampOffset,
  47997. useVideoTimingInfo = _ref9.useVideoTimingInfo,
  47998. videoTimingInfo = _ref9.videoTimingInfo,
  47999. audioTimingInfo = _ref9.audioTimingInfo;
  48000. if (typeof currentStart !== 'undefined') {
  48001. // if start was set once, keep using it
  48002. return currentStart;
  48003. }
  48004. if (!useVideoTimingInfo) {
  48005. return audioTimingInfo.start;
  48006. }
  48007. var previousSegment = playlist.segments[mediaIndex - 1]; // The start of a segment should be the start of the first full frame contained
  48008. // within that segment. Since the transmuxer maintains a cache of incomplete data
  48009. // from and/or the last frame seen, the start time may reflect a frame that starts
  48010. // in the previous segment. Check for that case and ensure the start time is
  48011. // accurate for the segment.
  48012. if (mediaIndex === 0 || !previousSegment || typeof previousSegment.start === 'undefined' || previousSegment.end !== firstVideoFrameTimeForData + currentVideoTimestampOffset) {
  48013. return firstVideoFrameTimeForData;
  48014. }
  48015. return videoTimingInfo.start;
  48016. };
  48017. _proto.waitForAppendsToComplete_ = function waitForAppendsToComplete_(segmentInfo) {
  48018. var trackInfo = this.getCurrentMediaInfo_(segmentInfo);
  48019. if (!trackInfo) {
  48020. this.error({
  48021. message: 'No starting media returned, likely due to an unsupported media format.',
  48022. blacklistDuration: Infinity
  48023. });
  48024. this.trigger('error');
  48025. return;
  48026. } // Although transmuxing is done, appends may not yet be finished. Throw a marker
  48027. // on each queue this loader is responsible for to ensure that the appends are
  48028. // complete.
  48029. var hasAudio = trackInfo.hasAudio,
  48030. hasVideo = trackInfo.hasVideo,
  48031. isMuxed = trackInfo.isMuxed;
  48032. var waitForVideo = this.loaderType_ === 'main' && hasVideo;
  48033. var waitForAudio = !this.audioDisabled_ && hasAudio && !isMuxed;
  48034. segmentInfo.waitingOnAppends = 0; // segments with no data
  48035. if (!segmentInfo.hasAppendedData_) {
  48036. if (!segmentInfo.timingInfo && typeof segmentInfo.timestampOffset === 'number') {
  48037. // When there's no audio or video data in the segment, there's no audio or video
  48038. // timing information.
  48039. //
  48040. // If there's no audio or video timing information, then the timestamp offset
  48041. // can't be adjusted to the appropriate value for the transmuxer and source
  48042. // buffers.
  48043. //
  48044. // Therefore, the next segment should be used to set the timestamp offset.
  48045. this.isPendingTimestampOffset_ = true;
  48046. } // override settings for metadata only segments
  48047. segmentInfo.timingInfo = {
  48048. start: 0
  48049. };
  48050. segmentInfo.waitingOnAppends++;
  48051. if (!this.isPendingTimestampOffset_) {
  48052. // update the timestampoffset
  48053. this.updateSourceBufferTimestampOffset_(segmentInfo); // make sure the metadata queue is processed even though we have
  48054. // no video/audio data.
  48055. this.processMetadataQueue_();
  48056. } // append is "done" instantly with no data.
  48057. this.checkAppendsDone_(segmentInfo);
  48058. return;
  48059. } // Since source updater could call back synchronously, do the increments first.
  48060. if (waitForVideo) {
  48061. segmentInfo.waitingOnAppends++;
  48062. }
  48063. if (waitForAudio) {
  48064. segmentInfo.waitingOnAppends++;
  48065. }
  48066. if (waitForVideo) {
  48067. this.sourceUpdater_.videoQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  48068. }
  48069. if (waitForAudio) {
  48070. this.sourceUpdater_.audioQueueCallback(this.checkAppendsDone_.bind(this, segmentInfo));
  48071. }
  48072. };
  48073. _proto.checkAppendsDone_ = function checkAppendsDone_(segmentInfo) {
  48074. if (this.checkForAbort_(segmentInfo.requestId)) {
  48075. return;
  48076. }
  48077. segmentInfo.waitingOnAppends--;
  48078. if (segmentInfo.waitingOnAppends === 0) {
  48079. this.handleAppendsDone_();
  48080. }
  48081. };
  48082. _proto.checkForIllegalMediaSwitch = function checkForIllegalMediaSwitch(trackInfo) {
  48083. var illegalMediaSwitchError = illegalMediaSwitch(this.loaderType_, this.getCurrentMediaInfo_(), trackInfo);
  48084. if (illegalMediaSwitchError) {
  48085. this.error({
  48086. message: illegalMediaSwitchError,
  48087. blacklistDuration: Infinity
  48088. });
  48089. this.trigger('error');
  48090. return true;
  48091. }
  48092. return false;
  48093. };
  48094. _proto.updateSourceBufferTimestampOffset_ = function updateSourceBufferTimestampOffset_(segmentInfo) {
  48095. if (segmentInfo.timestampOffset === null || // we don't yet have the start for whatever media type (video or audio) has
  48096. // priority, timing-wise, so we must wait
  48097. typeof segmentInfo.timingInfo.start !== 'number' || // already updated the timestamp offset for this segment
  48098. segmentInfo.changedTimestampOffset || // the alt audio loader should not be responsible for setting the timestamp offset
  48099. this.loaderType_ !== 'main') {
  48100. return;
  48101. }
  48102. var didChange = false; // Primary timing goes by video, and audio is trimmed in the transmuxer, meaning that
  48103. // the timing info here comes from video. In the event that the audio is longer than
  48104. // the video, this will trim the start of the audio.
  48105. // This also trims any offset from 0 at the beginning of the media
  48106. segmentInfo.timestampOffset -= this.getSegmentStartTimeForTimestampOffsetCalculation_({
  48107. videoTimingInfo: segmentInfo.segment.videoTimingInfo,
  48108. audioTimingInfo: segmentInfo.segment.audioTimingInfo,
  48109. timingInfo: segmentInfo.timingInfo
  48110. }); // In the event that there are part segment downloads, each will try to update the
  48111. // timestamp offset. Retaining this bit of state prevents us from updating in the
  48112. // future (within the same segment), however, there may be a better way to handle it.
  48113. segmentInfo.changedTimestampOffset = true;
  48114. if (segmentInfo.timestampOffset !== this.sourceUpdater_.videoTimestampOffset()) {
  48115. this.sourceUpdater_.videoTimestampOffset(segmentInfo.timestampOffset);
  48116. didChange = true;
  48117. }
  48118. if (segmentInfo.timestampOffset !== this.sourceUpdater_.audioTimestampOffset()) {
  48119. this.sourceUpdater_.audioTimestampOffset(segmentInfo.timestampOffset);
  48120. didChange = true;
  48121. }
  48122. if (didChange) {
  48123. this.trigger('timestampoffset');
  48124. }
  48125. };
  48126. _proto.getSegmentStartTimeForTimestampOffsetCalculation_ = function getSegmentStartTimeForTimestampOffsetCalculation_(_ref10) {
  48127. var videoTimingInfo = _ref10.videoTimingInfo,
  48128. audioTimingInfo = _ref10.audioTimingInfo,
  48129. timingInfo = _ref10.timingInfo;
  48130. if (!this.useDtsForTimestampOffset_) {
  48131. return timingInfo.start;
  48132. }
  48133. if (videoTimingInfo && typeof videoTimingInfo.transmuxedDecodeStart === 'number') {
  48134. return videoTimingInfo.transmuxedDecodeStart;
  48135. } // handle audio only
  48136. if (audioTimingInfo && typeof audioTimingInfo.transmuxedDecodeStart === 'number') {
  48137. return audioTimingInfo.transmuxedDecodeStart;
  48138. } // handle content not transmuxed (e.g., MP4)
  48139. return timingInfo.start;
  48140. };
  48141. _proto.updateTimingInfoEnd_ = function updateTimingInfoEnd_(segmentInfo) {
  48142. segmentInfo.timingInfo = segmentInfo.timingInfo || {};
  48143. var trackInfo = this.getMediaInfo_();
  48144. var useVideoTimingInfo = this.loaderType_ === 'main' && trackInfo && trackInfo.hasVideo;
  48145. var prioritizedTimingInfo = useVideoTimingInfo && segmentInfo.videoTimingInfo ? segmentInfo.videoTimingInfo : segmentInfo.audioTimingInfo;
  48146. if (!prioritizedTimingInfo) {
  48147. return;
  48148. }
  48149. segmentInfo.timingInfo.end = typeof prioritizedTimingInfo.end === 'number' ? // End time may not exist in a case where we aren't parsing the full segment (one
  48150. // current example is the case of fmp4), so use the rough duration to calculate an
  48151. // end time.
  48152. prioritizedTimingInfo.end : prioritizedTimingInfo.start + segmentInfo.duration;
  48153. }
  48154. /**
  48155. * callback to run when appendBuffer is finished. detects if we are
  48156. * in a good state to do things with the data we got, or if we need
  48157. * to wait for more
  48158. *
  48159. * @private
  48160. */
  48161. ;
  48162. _proto.handleAppendsDone_ = function handleAppendsDone_() {
  48163. // appendsdone can cause an abort
  48164. if (this.pendingSegment_) {
  48165. this.trigger('appendsdone');
  48166. }
  48167. if (!this.pendingSegment_) {
  48168. this.state = 'READY'; // TODO should this move into this.checkForAbort to speed up requests post abort in
  48169. // all appending cases?
  48170. if (!this.paused()) {
  48171. this.monitorBuffer_();
  48172. }
  48173. return;
  48174. }
  48175. var segmentInfo = this.pendingSegment_; // Now that the end of the segment has been reached, we can set the end time. It's
  48176. // best to wait until all appends are done so we're sure that the primary media is
  48177. // finished (and we have its end time).
  48178. this.updateTimingInfoEnd_(segmentInfo);
  48179. if (this.shouldSaveSegmentTimingInfo_) {
  48180. // Timeline mappings should only be saved for the main loader. This is for multiple
  48181. // reasons:
  48182. //
  48183. // 1) Only one mapping is saved per timeline, meaning that if both the audio loader
  48184. // and the main loader try to save the timeline mapping, whichever comes later
  48185. // will overwrite the first. In theory this is OK, as the mappings should be the
  48186. // same, however, it breaks for (2)
  48187. // 2) In the event of a live stream, the initial live point will make for a somewhat
  48188. // arbitrary mapping. If audio and video streams are not perfectly in-sync, then
  48189. // the mapping will be off for one of the streams, dependent on which one was
  48190. // first saved (see (1)).
  48191. // 3) Primary timing goes by video in VHS, so the mapping should be video.
  48192. //
  48193. // Since the audio loader will wait for the main loader to load the first segment,
  48194. // the main loader will save the first timeline mapping, and ensure that there won't
  48195. // be a case where audio loads two segments without saving a mapping (thus leading
  48196. // to missing segment timing info).
  48197. this.syncController_.saveSegmentTimingInfo({
  48198. segmentInfo: segmentInfo,
  48199. shouldSaveTimelineMapping: this.loaderType_ === 'main'
  48200. });
  48201. }
  48202. var segmentDurationMessage = getTroublesomeSegmentDurationMessage(segmentInfo, this.sourceType_);
  48203. if (segmentDurationMessage) {
  48204. if (segmentDurationMessage.severity === 'warn') {
  48205. videojs.log.warn(segmentDurationMessage.message);
  48206. } else {
  48207. this.logger_(segmentDurationMessage.message);
  48208. }
  48209. }
  48210. this.recordThroughput_(segmentInfo);
  48211. this.pendingSegment_ = null;
  48212. this.state = 'READY';
  48213. if (segmentInfo.isSyncRequest) {
  48214. this.trigger('syncinfoupdate'); // if the sync request was not appended
  48215. // then it was not the correct segment.
  48216. // throw it away and use the data it gave us
  48217. // to get the correct one.
  48218. if (!segmentInfo.hasAppendedData_) {
  48219. this.logger_("Throwing away un-appended sync request " + segmentInfoString(segmentInfo));
  48220. return;
  48221. }
  48222. }
  48223. this.logger_("Appended " + segmentInfoString(segmentInfo));
  48224. this.addSegmentMetadataCue_(segmentInfo);
  48225. this.fetchAtBuffer_ = true;
  48226. if (this.currentTimeline_ !== segmentInfo.timeline) {
  48227. this.timelineChangeController_.lastTimelineChange({
  48228. type: this.loaderType_,
  48229. from: this.currentTimeline_,
  48230. to: segmentInfo.timeline
  48231. }); // If audio is not disabled, the main segment loader is responsible for updating
  48232. // the audio timeline as well. If the content is video only, this won't have any
  48233. // impact.
  48234. if (this.loaderType_ === 'main' && !this.audioDisabled_) {
  48235. this.timelineChangeController_.lastTimelineChange({
  48236. type: 'audio',
  48237. from: this.currentTimeline_,
  48238. to: segmentInfo.timeline
  48239. });
  48240. }
  48241. }
  48242. this.currentTimeline_ = segmentInfo.timeline; // We must update the syncinfo to recalculate the seekable range before
  48243. // the following conditional otherwise it may consider this a bad "guess"
  48244. // and attempt to resync when the post-update seekable window and live
  48245. // point would mean that this was the perfect segment to fetch
  48246. this.trigger('syncinfoupdate');
  48247. var segment = segmentInfo.segment;
  48248. var part = segmentInfo.part;
  48249. var badSegmentGuess = segment.end && this.currentTime_() - segment.end > segmentInfo.playlist.targetDuration * 3;
  48250. 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
  48251. // the currentTime_ that means that our conservative guess was too conservative.
  48252. // In that case, reset the loader state so that we try to use any information gained
  48253. // from the previous request to create a new, more accurate, sync-point.
  48254. if (badSegmentGuess || badPartGuess) {
  48255. this.logger_("bad " + (badSegmentGuess ? 'segment' : 'part') + " " + segmentInfoString(segmentInfo));
  48256. this.resetEverything();
  48257. return;
  48258. }
  48259. var isWalkingForward = this.mediaIndex !== null; // Don't do a rendition switch unless we have enough time to get a sync segment
  48260. // and conservatively guess
  48261. if (isWalkingForward) {
  48262. this.trigger('bandwidthupdate');
  48263. }
  48264. this.trigger('progress');
  48265. this.mediaIndex = segmentInfo.mediaIndex;
  48266. this.partIndex = segmentInfo.partIndex; // any time an update finishes and the last segment is in the
  48267. // buffer, end the stream. this ensures the "ended" event will
  48268. // fire if playback reaches that point.
  48269. if (this.isEndOfStream_(segmentInfo.mediaIndex, segmentInfo.playlist, segmentInfo.partIndex)) {
  48270. this.endOfStream();
  48271. } // used for testing
  48272. this.trigger('appended');
  48273. if (segmentInfo.hasAppendedData_) {
  48274. this.mediaAppends++;
  48275. }
  48276. if (!this.paused()) {
  48277. this.monitorBuffer_();
  48278. }
  48279. }
  48280. /**
  48281. * Records the current throughput of the decrypt, transmux, and append
  48282. * portion of the semgment pipeline. `throughput.rate` is a the cumulative
  48283. * moving average of the throughput. `throughput.count` is the number of
  48284. * data points in the average.
  48285. *
  48286. * @private
  48287. * @param {Object} segmentInfo the object returned by loadSegment
  48288. */
  48289. ;
  48290. _proto.recordThroughput_ = function recordThroughput_(segmentInfo) {
  48291. if (segmentInfo.duration < MIN_SEGMENT_DURATION_TO_SAVE_STATS) {
  48292. 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));
  48293. return;
  48294. }
  48295. var rate = this.throughput.rate; // Add one to the time to ensure that we don't accidentally attempt to divide
  48296. // by zero in the case where the throughput is ridiculously high
  48297. var segmentProcessingTime = Date.now() - segmentInfo.endOfAllRequests + 1; // Multiply by 8000 to convert from bytes/millisecond to bits/second
  48298. var segmentProcessingThroughput = Math.floor(segmentInfo.byteLength / segmentProcessingTime * 8 * 1000); // This is just a cumulative moving average calculation:
  48299. // newAvg = oldAvg + (sample - oldAvg) / (sampleCount + 1)
  48300. this.throughput.rate += (segmentProcessingThroughput - rate) / ++this.throughput.count;
  48301. }
  48302. /**
  48303. * Adds a cue to the segment-metadata track with some metadata information about the
  48304. * segment
  48305. *
  48306. * @private
  48307. * @param {Object} segmentInfo
  48308. * the object returned by loadSegment
  48309. * @method addSegmentMetadataCue_
  48310. */
  48311. ;
  48312. _proto.addSegmentMetadataCue_ = function addSegmentMetadataCue_(segmentInfo) {
  48313. if (!this.segmentMetadataTrack_) {
  48314. return;
  48315. }
  48316. var segment = segmentInfo.segment;
  48317. var start = segment.start;
  48318. var end = segment.end; // Do not try adding the cue if the start and end times are invalid.
  48319. if (!finite(start) || !finite(end)) {
  48320. return;
  48321. }
  48322. removeCuesFromTrack(start, end, this.segmentMetadataTrack_);
  48323. var Cue = window.WebKitDataCue || window.VTTCue;
  48324. var value = {
  48325. custom: segment.custom,
  48326. dateTimeObject: segment.dateTimeObject,
  48327. dateTimeString: segment.dateTimeString,
  48328. bandwidth: segmentInfo.playlist.attributes.BANDWIDTH,
  48329. resolution: segmentInfo.playlist.attributes.RESOLUTION,
  48330. codecs: segmentInfo.playlist.attributes.CODECS,
  48331. byteLength: segmentInfo.byteLength,
  48332. uri: segmentInfo.uri,
  48333. timeline: segmentInfo.timeline,
  48334. playlist: segmentInfo.playlist.id,
  48335. start: start,
  48336. end: end
  48337. };
  48338. var data = JSON.stringify(value);
  48339. var cue = new Cue(start, end, data); // Attach the metadata to the value property of the cue to keep consistency between
  48340. // the differences of WebKitDataCue in safari and VTTCue in other browsers
  48341. cue.value = value;
  48342. this.segmentMetadataTrack_.addCue(cue);
  48343. };
  48344. return SegmentLoader;
  48345. }(videojs.EventTarget);
  48346. function noop() {}
  48347. var toTitleCase = function toTitleCase(string) {
  48348. if (typeof string !== 'string') {
  48349. return string;
  48350. }
  48351. return string.replace(/./, function (w) {
  48352. return w.toUpperCase();
  48353. });
  48354. };
  48355. var bufferTypes = ['video', 'audio'];
  48356. var _updating = function updating(type, sourceUpdater) {
  48357. var sourceBuffer = sourceUpdater[type + "Buffer"];
  48358. return sourceBuffer && sourceBuffer.updating || sourceUpdater.queuePending[type];
  48359. };
  48360. var nextQueueIndexOfType = function nextQueueIndexOfType(type, queue) {
  48361. for (var i = 0; i < queue.length; i++) {
  48362. var queueEntry = queue[i];
  48363. if (queueEntry.type === 'mediaSource') {
  48364. // If the next entry is a media source entry (uses multiple source buffers), block
  48365. // processing to allow it to go through first.
  48366. return null;
  48367. }
  48368. if (queueEntry.type === type) {
  48369. return i;
  48370. }
  48371. }
  48372. return null;
  48373. };
  48374. var shiftQueue = function shiftQueue(type, sourceUpdater) {
  48375. if (sourceUpdater.queue.length === 0) {
  48376. return;
  48377. }
  48378. var queueIndex = 0;
  48379. var queueEntry = sourceUpdater.queue[queueIndex];
  48380. if (queueEntry.type === 'mediaSource') {
  48381. if (!sourceUpdater.updating() && sourceUpdater.mediaSource.readyState !== 'closed') {
  48382. sourceUpdater.queue.shift();
  48383. queueEntry.action(sourceUpdater);
  48384. if (queueEntry.doneFn) {
  48385. queueEntry.doneFn();
  48386. } // Only specific source buffer actions must wait for async updateend events. Media
  48387. // Source actions process synchronously. Therefore, both audio and video source
  48388. // buffers are now clear to process the next queue entries.
  48389. shiftQueue('audio', sourceUpdater);
  48390. shiftQueue('video', sourceUpdater);
  48391. } // Media Source actions require both source buffers, so if the media source action
  48392. // couldn't process yet (because one or both source buffers are busy), block other
  48393. // queue actions until both are available and the media source action can process.
  48394. return;
  48395. }
  48396. if (type === 'mediaSource') {
  48397. // If the queue was shifted by a media source action (this happens when pushing a
  48398. // media source action onto the queue), then it wasn't from an updateend event from an
  48399. // audio or video source buffer, so there's no change from previous state, and no
  48400. // processing should be done.
  48401. return;
  48402. } // Media source queue entries don't need to consider whether the source updater is
  48403. // started (i.e., source buffers are created) as they don't need the source buffers, but
  48404. // source buffer queue entries do.
  48405. if (!sourceUpdater.ready() || sourceUpdater.mediaSource.readyState === 'closed' || _updating(type, sourceUpdater)) {
  48406. return;
  48407. }
  48408. if (queueEntry.type !== type) {
  48409. queueIndex = nextQueueIndexOfType(type, sourceUpdater.queue);
  48410. if (queueIndex === null) {
  48411. // Either there's no queue entry that uses this source buffer type in the queue, or
  48412. // there's a media source queue entry before the next entry of this type, in which
  48413. // case wait for that action to process first.
  48414. return;
  48415. }
  48416. queueEntry = sourceUpdater.queue[queueIndex];
  48417. }
  48418. sourceUpdater.queue.splice(queueIndex, 1); // Keep a record that this source buffer type is in use.
  48419. //
  48420. // The queue pending operation must be set before the action is performed in the event
  48421. // that the action results in a synchronous event that is acted upon. For instance, if
  48422. // an exception is thrown that can be handled, it's possible that new actions will be
  48423. // appended to an empty queue and immediately executed, but would not have the correct
  48424. // pending information if this property was set after the action was performed.
  48425. sourceUpdater.queuePending[type] = queueEntry;
  48426. queueEntry.action(type, sourceUpdater);
  48427. if (!queueEntry.doneFn) {
  48428. // synchronous operation, process next entry
  48429. sourceUpdater.queuePending[type] = null;
  48430. shiftQueue(type, sourceUpdater);
  48431. return;
  48432. }
  48433. };
  48434. var cleanupBuffer = function cleanupBuffer(type, sourceUpdater) {
  48435. var buffer = sourceUpdater[type + "Buffer"];
  48436. var titleType = toTitleCase(type);
  48437. if (!buffer) {
  48438. return;
  48439. }
  48440. buffer.removeEventListener('updateend', sourceUpdater["on" + titleType + "UpdateEnd_"]);
  48441. buffer.removeEventListener('error', sourceUpdater["on" + titleType + "Error_"]);
  48442. sourceUpdater.codecs[type] = null;
  48443. sourceUpdater[type + "Buffer"] = null;
  48444. };
  48445. var inSourceBuffers = function inSourceBuffers(mediaSource, sourceBuffer) {
  48446. return mediaSource && sourceBuffer && Array.prototype.indexOf.call(mediaSource.sourceBuffers, sourceBuffer) !== -1;
  48447. };
  48448. var actions = {
  48449. appendBuffer: function appendBuffer(bytes, segmentInfo, onError) {
  48450. return function (type, sourceUpdater) {
  48451. var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
  48452. // or the media source does not contain this source buffer.
  48453. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  48454. return;
  48455. }
  48456. sourceUpdater.logger_("Appending segment " + segmentInfo.mediaIndex + "'s " + bytes.length + " bytes to " + type + "Buffer");
  48457. try {
  48458. sourceBuffer.appendBuffer(bytes);
  48459. } catch (e) {
  48460. sourceUpdater.logger_("Error with code " + e.code + " " + (e.code === QUOTA_EXCEEDED_ERR ? '(QUOTA_EXCEEDED_ERR) ' : '') + ("when appending segment " + segmentInfo.mediaIndex + " to " + type + "Buffer"));
  48461. sourceUpdater.queuePending[type] = null;
  48462. onError(e);
  48463. }
  48464. };
  48465. },
  48466. remove: function remove(start, end) {
  48467. return function (type, sourceUpdater) {
  48468. var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
  48469. // or the media source does not contain this source buffer.
  48470. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  48471. return;
  48472. }
  48473. sourceUpdater.logger_("Removing " + start + " to " + end + " from " + type + "Buffer");
  48474. try {
  48475. sourceBuffer.remove(start, end);
  48476. } catch (e) {
  48477. sourceUpdater.logger_("Remove " + start + " to " + end + " from " + type + "Buffer failed");
  48478. }
  48479. };
  48480. },
  48481. timestampOffset: function timestampOffset(offset) {
  48482. return function (type, sourceUpdater) {
  48483. var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
  48484. // or the media source does not contain this source buffer.
  48485. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  48486. return;
  48487. }
  48488. sourceUpdater.logger_("Setting " + type + "timestampOffset to " + offset);
  48489. sourceBuffer.timestampOffset = offset;
  48490. };
  48491. },
  48492. callback: function callback(_callback) {
  48493. return function (type, sourceUpdater) {
  48494. _callback();
  48495. };
  48496. },
  48497. endOfStream: function endOfStream(error) {
  48498. return function (sourceUpdater) {
  48499. if (sourceUpdater.mediaSource.readyState !== 'open') {
  48500. return;
  48501. }
  48502. sourceUpdater.logger_("Calling mediaSource endOfStream(" + (error || '') + ")");
  48503. try {
  48504. sourceUpdater.mediaSource.endOfStream(error);
  48505. } catch (e) {
  48506. videojs.log.warn('Failed to call media source endOfStream', e);
  48507. }
  48508. };
  48509. },
  48510. duration: function duration(_duration) {
  48511. return function (sourceUpdater) {
  48512. sourceUpdater.logger_("Setting mediaSource duration to " + _duration);
  48513. try {
  48514. sourceUpdater.mediaSource.duration = _duration;
  48515. } catch (e) {
  48516. videojs.log.warn('Failed to set media source duration', e);
  48517. }
  48518. };
  48519. },
  48520. abort: function abort() {
  48521. return function (type, sourceUpdater) {
  48522. if (sourceUpdater.mediaSource.readyState !== 'open') {
  48523. return;
  48524. }
  48525. var sourceBuffer = sourceUpdater[type + "Buffer"]; // can't do anything if the media source / source buffer is null
  48526. // or the media source does not contain this source buffer.
  48527. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  48528. return;
  48529. }
  48530. sourceUpdater.logger_("calling abort on " + type + "Buffer");
  48531. try {
  48532. sourceBuffer.abort();
  48533. } catch (e) {
  48534. videojs.log.warn("Failed to abort on " + type + "Buffer", e);
  48535. }
  48536. };
  48537. },
  48538. addSourceBuffer: function addSourceBuffer(type, codec) {
  48539. return function (sourceUpdater) {
  48540. var titleType = toTitleCase(type);
  48541. var mime = getMimeForCodec(codec);
  48542. sourceUpdater.logger_("Adding " + type + "Buffer with codec " + codec + " to mediaSource");
  48543. var sourceBuffer = sourceUpdater.mediaSource.addSourceBuffer(mime);
  48544. sourceBuffer.addEventListener('updateend', sourceUpdater["on" + titleType + "UpdateEnd_"]);
  48545. sourceBuffer.addEventListener('error', sourceUpdater["on" + titleType + "Error_"]);
  48546. sourceUpdater.codecs[type] = codec;
  48547. sourceUpdater[type + "Buffer"] = sourceBuffer;
  48548. };
  48549. },
  48550. removeSourceBuffer: function removeSourceBuffer(type) {
  48551. return function (sourceUpdater) {
  48552. var sourceBuffer = sourceUpdater[type + "Buffer"];
  48553. cleanupBuffer(type, sourceUpdater); // can't do anything if the media source / source buffer is null
  48554. // or the media source does not contain this source buffer.
  48555. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  48556. return;
  48557. }
  48558. sourceUpdater.logger_("Removing " + type + "Buffer with codec " + sourceUpdater.codecs[type] + " from mediaSource");
  48559. try {
  48560. sourceUpdater.mediaSource.removeSourceBuffer(sourceBuffer);
  48561. } catch (e) {
  48562. videojs.log.warn("Failed to removeSourceBuffer " + type + "Buffer", e);
  48563. }
  48564. };
  48565. },
  48566. changeType: function changeType(codec) {
  48567. return function (type, sourceUpdater) {
  48568. var sourceBuffer = sourceUpdater[type + "Buffer"];
  48569. var mime = getMimeForCodec(codec); // can't do anything if the media source / source buffer is null
  48570. // or the media source does not contain this source buffer.
  48571. if (!inSourceBuffers(sourceUpdater.mediaSource, sourceBuffer)) {
  48572. return;
  48573. } // do not update codec if we don't need to.
  48574. if (sourceUpdater.codecs[type] === codec) {
  48575. return;
  48576. }
  48577. sourceUpdater.logger_("changing " + type + "Buffer codec from " + sourceUpdater.codecs[type] + " to " + codec);
  48578. sourceBuffer.changeType(mime);
  48579. sourceUpdater.codecs[type] = codec;
  48580. };
  48581. }
  48582. };
  48583. var pushQueue = function pushQueue(_ref) {
  48584. var type = _ref.type,
  48585. sourceUpdater = _ref.sourceUpdater,
  48586. action = _ref.action,
  48587. doneFn = _ref.doneFn,
  48588. name = _ref.name;
  48589. sourceUpdater.queue.push({
  48590. type: type,
  48591. action: action,
  48592. doneFn: doneFn,
  48593. name: name
  48594. });
  48595. shiftQueue(type, sourceUpdater);
  48596. };
  48597. var onUpdateend = function onUpdateend(type, sourceUpdater) {
  48598. return function (e) {
  48599. // Although there should, in theory, be a pending action for any updateend receieved,
  48600. // there are some actions that may trigger updateend events without set definitions in
  48601. // the w3c spec. For instance, setting the duration on the media source may trigger
  48602. // updateend events on source buffers. This does not appear to be in the spec. As such,
  48603. // if we encounter an updateend without a corresponding pending action from our queue
  48604. // for that source buffer type, process the next action.
  48605. if (sourceUpdater.queuePending[type]) {
  48606. var doneFn = sourceUpdater.queuePending[type].doneFn;
  48607. sourceUpdater.queuePending[type] = null;
  48608. if (doneFn) {
  48609. // if there's an error, report it
  48610. doneFn(sourceUpdater[type + "Error_"]);
  48611. }
  48612. }
  48613. shiftQueue(type, sourceUpdater);
  48614. };
  48615. };
  48616. /**
  48617. * A queue of callbacks to be serialized and applied when a
  48618. * MediaSource and its associated SourceBuffers are not in the
  48619. * updating state. It is used by the segment loader to update the
  48620. * underlying SourceBuffers when new data is loaded, for instance.
  48621. *
  48622. * @class SourceUpdater
  48623. * @param {MediaSource} mediaSource the MediaSource to create the SourceBuffer from
  48624. * @param {string} mimeType the desired MIME type of the underlying SourceBuffer
  48625. */
  48626. var SourceUpdater = /*#__PURE__*/function (_videojs$EventTarget) {
  48627. inheritsLoose(SourceUpdater, _videojs$EventTarget);
  48628. function SourceUpdater(mediaSource) {
  48629. var _this;
  48630. _this = _videojs$EventTarget.call(this) || this;
  48631. _this.mediaSource = mediaSource;
  48632. _this.sourceopenListener_ = function () {
  48633. return shiftQueue('mediaSource', assertThisInitialized(_this));
  48634. };
  48635. _this.mediaSource.addEventListener('sourceopen', _this.sourceopenListener_);
  48636. _this.logger_ = logger('SourceUpdater'); // initial timestamp offset is 0
  48637. _this.audioTimestampOffset_ = 0;
  48638. _this.videoTimestampOffset_ = 0;
  48639. _this.queue = [];
  48640. _this.queuePending = {
  48641. audio: null,
  48642. video: null
  48643. };
  48644. _this.delayedAudioAppendQueue_ = [];
  48645. _this.videoAppendQueued_ = false;
  48646. _this.codecs = {};
  48647. _this.onVideoUpdateEnd_ = onUpdateend('video', assertThisInitialized(_this));
  48648. _this.onAudioUpdateEnd_ = onUpdateend('audio', assertThisInitialized(_this));
  48649. _this.onVideoError_ = function (e) {
  48650. // used for debugging
  48651. _this.videoError_ = e;
  48652. };
  48653. _this.onAudioError_ = function (e) {
  48654. // used for debugging
  48655. _this.audioError_ = e;
  48656. };
  48657. _this.createdSourceBuffers_ = false;
  48658. _this.initializedEme_ = false;
  48659. _this.triggeredReady_ = false;
  48660. return _this;
  48661. }
  48662. var _proto = SourceUpdater.prototype;
  48663. _proto.initializedEme = function initializedEme() {
  48664. this.initializedEme_ = true;
  48665. this.triggerReady();
  48666. };
  48667. _proto.hasCreatedSourceBuffers = function hasCreatedSourceBuffers() {
  48668. // if false, likely waiting on one of the segment loaders to get enough data to create
  48669. // source buffers
  48670. return this.createdSourceBuffers_;
  48671. };
  48672. _proto.hasInitializedAnyEme = function hasInitializedAnyEme() {
  48673. return this.initializedEme_;
  48674. };
  48675. _proto.ready = function ready() {
  48676. return this.hasCreatedSourceBuffers() && this.hasInitializedAnyEme();
  48677. };
  48678. _proto.createSourceBuffers = function createSourceBuffers(codecs) {
  48679. if (this.hasCreatedSourceBuffers()) {
  48680. // already created them before
  48681. return;
  48682. } // the intial addOrChangeSourceBuffers will always be
  48683. // two add buffers.
  48684. this.addOrChangeSourceBuffers(codecs);
  48685. this.createdSourceBuffers_ = true;
  48686. this.trigger('createdsourcebuffers');
  48687. this.triggerReady();
  48688. };
  48689. _proto.triggerReady = function triggerReady() {
  48690. // only allow ready to be triggered once, this prevents the case
  48691. // where:
  48692. // 1. we trigger createdsourcebuffers
  48693. // 2. ie 11 synchronously initializates eme
  48694. // 3. the synchronous initialization causes us to trigger ready
  48695. // 4. We go back to the ready check in createSourceBuffers and ready is triggered again.
  48696. if (this.ready() && !this.triggeredReady_) {
  48697. this.triggeredReady_ = true;
  48698. this.trigger('ready');
  48699. }
  48700. }
  48701. /**
  48702. * Add a type of source buffer to the media source.
  48703. *
  48704. * @param {string} type
  48705. * The type of source buffer to add.
  48706. *
  48707. * @param {string} codec
  48708. * The codec to add the source buffer with.
  48709. */
  48710. ;
  48711. _proto.addSourceBuffer = function addSourceBuffer(type, codec) {
  48712. pushQueue({
  48713. type: 'mediaSource',
  48714. sourceUpdater: this,
  48715. action: actions.addSourceBuffer(type, codec),
  48716. name: 'addSourceBuffer'
  48717. });
  48718. }
  48719. /**
  48720. * call abort on a source buffer.
  48721. *
  48722. * @param {string} type
  48723. * The type of source buffer to call abort on.
  48724. */
  48725. ;
  48726. _proto.abort = function abort(type) {
  48727. pushQueue({
  48728. type: type,
  48729. sourceUpdater: this,
  48730. action: actions.abort(type),
  48731. name: 'abort'
  48732. });
  48733. }
  48734. /**
  48735. * Call removeSourceBuffer and remove a specific type
  48736. * of source buffer on the mediaSource.
  48737. *
  48738. * @param {string} type
  48739. * The type of source buffer to remove.
  48740. */
  48741. ;
  48742. _proto.removeSourceBuffer = function removeSourceBuffer(type) {
  48743. if (!this.canRemoveSourceBuffer()) {
  48744. videojs.log.error('removeSourceBuffer is not supported!');
  48745. return;
  48746. }
  48747. pushQueue({
  48748. type: 'mediaSource',
  48749. sourceUpdater: this,
  48750. action: actions.removeSourceBuffer(type),
  48751. name: 'removeSourceBuffer'
  48752. });
  48753. }
  48754. /**
  48755. * Whether or not the removeSourceBuffer function is supported
  48756. * on the mediaSource.
  48757. *
  48758. * @return {boolean}
  48759. * if removeSourceBuffer can be called.
  48760. */
  48761. ;
  48762. _proto.canRemoveSourceBuffer = function canRemoveSourceBuffer() {
  48763. // IE reports that it supports removeSourceBuffer, but often throws
  48764. // errors when attempting to use the function. So we report that it
  48765. // does not support removeSourceBuffer. As of Firefox 83 removeSourceBuffer
  48766. // throws errors, so we report that it does not support this as well.
  48767. return !videojs.browser.IE_VERSION && !videojs.browser.IS_FIREFOX && window.MediaSource && window.MediaSource.prototype && typeof window.MediaSource.prototype.removeSourceBuffer === 'function';
  48768. }
  48769. /**
  48770. * Whether or not the changeType function is supported
  48771. * on our SourceBuffers.
  48772. *
  48773. * @return {boolean}
  48774. * if changeType can be called.
  48775. */
  48776. ;
  48777. SourceUpdater.canChangeType = function canChangeType() {
  48778. return window.SourceBuffer && window.SourceBuffer.prototype && typeof window.SourceBuffer.prototype.changeType === 'function';
  48779. }
  48780. /**
  48781. * Whether or not the changeType function is supported
  48782. * on our SourceBuffers.
  48783. *
  48784. * @return {boolean}
  48785. * if changeType can be called.
  48786. */
  48787. ;
  48788. _proto.canChangeType = function canChangeType() {
  48789. return this.constructor.canChangeType();
  48790. }
  48791. /**
  48792. * Call the changeType function on a source buffer, given the code and type.
  48793. *
  48794. * @param {string} type
  48795. * The type of source buffer to call changeType on.
  48796. *
  48797. * @param {string} codec
  48798. * The codec string to change type with on the source buffer.
  48799. */
  48800. ;
  48801. _proto.changeType = function changeType(type, codec) {
  48802. if (!this.canChangeType()) {
  48803. videojs.log.error('changeType is not supported!');
  48804. return;
  48805. }
  48806. pushQueue({
  48807. type: type,
  48808. sourceUpdater: this,
  48809. action: actions.changeType(codec),
  48810. name: 'changeType'
  48811. });
  48812. }
  48813. /**
  48814. * Add source buffers with a codec or, if they are already created,
  48815. * call changeType on source buffers using changeType.
  48816. *
  48817. * @param {Object} codecs
  48818. * Codecs to switch to
  48819. */
  48820. ;
  48821. _proto.addOrChangeSourceBuffers = function addOrChangeSourceBuffers(codecs) {
  48822. var _this2 = this;
  48823. if (!codecs || typeof codecs !== 'object' || Object.keys(codecs).length === 0) {
  48824. throw new Error('Cannot addOrChangeSourceBuffers to undefined codecs');
  48825. }
  48826. Object.keys(codecs).forEach(function (type) {
  48827. var codec = codecs[type];
  48828. if (!_this2.hasCreatedSourceBuffers()) {
  48829. return _this2.addSourceBuffer(type, codec);
  48830. }
  48831. if (_this2.canChangeType()) {
  48832. _this2.changeType(type, codec);
  48833. }
  48834. });
  48835. }
  48836. /**
  48837. * Queue an update to append an ArrayBuffer.
  48838. *
  48839. * @param {MediaObject} object containing audioBytes and/or videoBytes
  48840. * @param {Function} done the function to call when done
  48841. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-appendBuffer-void-ArrayBuffer-data
  48842. */
  48843. ;
  48844. _proto.appendBuffer = function appendBuffer(options, doneFn) {
  48845. var _this3 = this;
  48846. var segmentInfo = options.segmentInfo,
  48847. type = options.type,
  48848. bytes = options.bytes;
  48849. this.processedAppend_ = true;
  48850. if (type === 'audio' && this.videoBuffer && !this.videoAppendQueued_) {
  48851. this.delayedAudioAppendQueue_.push([options, doneFn]);
  48852. this.logger_("delayed audio append of " + bytes.length + " until video append");
  48853. return;
  48854. } // In the case of certain errors, for instance, QUOTA_EXCEEDED_ERR, updateend will
  48855. // not be fired. This means that the queue will be blocked until the next action
  48856. // taken by the segment-loader. Provide a mechanism for segment-loader to handle
  48857. // these errors by calling the doneFn with the specific error.
  48858. var onError = doneFn;
  48859. pushQueue({
  48860. type: type,
  48861. sourceUpdater: this,
  48862. action: actions.appendBuffer(bytes, segmentInfo || {
  48863. mediaIndex: -1
  48864. }, onError),
  48865. doneFn: doneFn,
  48866. name: 'appendBuffer'
  48867. });
  48868. if (type === 'video') {
  48869. this.videoAppendQueued_ = true;
  48870. if (!this.delayedAudioAppendQueue_.length) {
  48871. return;
  48872. }
  48873. var queue = this.delayedAudioAppendQueue_.slice();
  48874. this.logger_("queuing delayed audio " + queue.length + " appendBuffers");
  48875. this.delayedAudioAppendQueue_.length = 0;
  48876. queue.forEach(function (que) {
  48877. _this3.appendBuffer.apply(_this3, que);
  48878. });
  48879. }
  48880. }
  48881. /**
  48882. * Get the audio buffer's buffered timerange.
  48883. *
  48884. * @return {TimeRange}
  48885. * The audio buffer's buffered time range
  48886. */
  48887. ;
  48888. _proto.audioBuffered = function audioBuffered() {
  48889. // no media source/source buffer or it isn't in the media sources
  48890. // source buffer list
  48891. if (!inSourceBuffers(this.mediaSource, this.audioBuffer)) {
  48892. return videojs.createTimeRange();
  48893. }
  48894. return this.audioBuffer.buffered ? this.audioBuffer.buffered : videojs.createTimeRange();
  48895. }
  48896. /**
  48897. * Get the video buffer's buffered timerange.
  48898. *
  48899. * @return {TimeRange}
  48900. * The video buffer's buffered time range
  48901. */
  48902. ;
  48903. _proto.videoBuffered = function videoBuffered() {
  48904. // no media source/source buffer or it isn't in the media sources
  48905. // source buffer list
  48906. if (!inSourceBuffers(this.mediaSource, this.videoBuffer)) {
  48907. return videojs.createTimeRange();
  48908. }
  48909. return this.videoBuffer.buffered ? this.videoBuffer.buffered : videojs.createTimeRange();
  48910. }
  48911. /**
  48912. * Get a combined video/audio buffer's buffered timerange.
  48913. *
  48914. * @return {TimeRange}
  48915. * the combined time range
  48916. */
  48917. ;
  48918. _proto.buffered = function buffered() {
  48919. var video = inSourceBuffers(this.mediaSource, this.videoBuffer) ? this.videoBuffer : null;
  48920. var audio = inSourceBuffers(this.mediaSource, this.audioBuffer) ? this.audioBuffer : null;
  48921. if (audio && !video) {
  48922. return this.audioBuffered();
  48923. }
  48924. if (video && !audio) {
  48925. return this.videoBuffered();
  48926. }
  48927. return bufferIntersection(this.audioBuffered(), this.videoBuffered());
  48928. }
  48929. /**
  48930. * Add a callback to the queue that will set duration on the mediaSource.
  48931. *
  48932. * @param {number} duration
  48933. * The duration to set
  48934. *
  48935. * @param {Function} [doneFn]
  48936. * function to run after duration has been set.
  48937. */
  48938. ;
  48939. _proto.setDuration = function setDuration(duration, doneFn) {
  48940. if (doneFn === void 0) {
  48941. doneFn = noop;
  48942. } // In order to set the duration on the media source, it's necessary to wait for all
  48943. // source buffers to no longer be updating. "If the updating attribute equals true on
  48944. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  48945. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  48946. pushQueue({
  48947. type: 'mediaSource',
  48948. sourceUpdater: this,
  48949. action: actions.duration(duration),
  48950. name: 'duration',
  48951. doneFn: doneFn
  48952. });
  48953. }
  48954. /**
  48955. * Add a mediaSource endOfStream call to the queue
  48956. *
  48957. * @param {Error} [error]
  48958. * Call endOfStream with an error
  48959. *
  48960. * @param {Function} [doneFn]
  48961. * A function that should be called when the
  48962. * endOfStream call has finished.
  48963. */
  48964. ;
  48965. _proto.endOfStream = function endOfStream(error, doneFn) {
  48966. if (error === void 0) {
  48967. error = null;
  48968. }
  48969. if (doneFn === void 0) {
  48970. doneFn = noop;
  48971. }
  48972. if (typeof error !== 'string') {
  48973. error = undefined;
  48974. } // In order to set the duration on the media source, it's necessary to wait for all
  48975. // source buffers to no longer be updating. "If the updating attribute equals true on
  48976. // any SourceBuffer in sourceBuffers, then throw an InvalidStateError exception and
  48977. // abort these steps." (source: https://www.w3.org/TR/media-source/#attributes).
  48978. pushQueue({
  48979. type: 'mediaSource',
  48980. sourceUpdater: this,
  48981. action: actions.endOfStream(error),
  48982. name: 'endOfStream',
  48983. doneFn: doneFn
  48984. });
  48985. }
  48986. /**
  48987. * Queue an update to remove a time range from the buffer.
  48988. *
  48989. * @param {number} start where to start the removal
  48990. * @param {number} end where to end the removal
  48991. * @param {Function} [done=noop] optional callback to be executed when the remove
  48992. * operation is complete
  48993. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  48994. */
  48995. ;
  48996. _proto.removeAudio = function removeAudio(start, end, done) {
  48997. if (done === void 0) {
  48998. done = noop;
  48999. }
  49000. if (!this.audioBuffered().length || this.audioBuffered().end(0) === 0) {
  49001. done();
  49002. return;
  49003. }
  49004. pushQueue({
  49005. type: 'audio',
  49006. sourceUpdater: this,
  49007. action: actions.remove(start, end),
  49008. doneFn: done,
  49009. name: 'remove'
  49010. });
  49011. }
  49012. /**
  49013. * Queue an update to remove a time range from the buffer.
  49014. *
  49015. * @param {number} start where to start the removal
  49016. * @param {number} end where to end the removal
  49017. * @param {Function} [done=noop] optional callback to be executed when the remove
  49018. * operation is complete
  49019. * @see http://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  49020. */
  49021. ;
  49022. _proto.removeVideo = function removeVideo(start, end, done) {
  49023. if (done === void 0) {
  49024. done = noop;
  49025. }
  49026. if (!this.videoBuffered().length || this.videoBuffered().end(0) === 0) {
  49027. done();
  49028. return;
  49029. }
  49030. pushQueue({
  49031. type: 'video',
  49032. sourceUpdater: this,
  49033. action: actions.remove(start, end),
  49034. doneFn: done,
  49035. name: 'remove'
  49036. });
  49037. }
  49038. /**
  49039. * Whether the underlying sourceBuffer is updating or not
  49040. *
  49041. * @return {boolean} the updating status of the SourceBuffer
  49042. */
  49043. ;
  49044. _proto.updating = function updating() {
  49045. // the audio/video source buffer is updating
  49046. if (_updating('audio', this) || _updating('video', this)) {
  49047. return true;
  49048. }
  49049. return false;
  49050. }
  49051. /**
  49052. * Set/get the timestampoffset on the audio SourceBuffer
  49053. *
  49054. * @return {number} the timestamp offset
  49055. */
  49056. ;
  49057. _proto.audioTimestampOffset = function audioTimestampOffset(offset) {
  49058. if (typeof offset !== 'undefined' && this.audioBuffer && // no point in updating if it's the same
  49059. this.audioTimestampOffset_ !== offset) {
  49060. pushQueue({
  49061. type: 'audio',
  49062. sourceUpdater: this,
  49063. action: actions.timestampOffset(offset),
  49064. name: 'timestampOffset'
  49065. });
  49066. this.audioTimestampOffset_ = offset;
  49067. }
  49068. return this.audioTimestampOffset_;
  49069. }
  49070. /**
  49071. * Set/get the timestampoffset on the video SourceBuffer
  49072. *
  49073. * @return {number} the timestamp offset
  49074. */
  49075. ;
  49076. _proto.videoTimestampOffset = function videoTimestampOffset(offset) {
  49077. if (typeof offset !== 'undefined' && this.videoBuffer && // no point in updating if it's the same
  49078. this.videoTimestampOffset !== offset) {
  49079. pushQueue({
  49080. type: 'video',
  49081. sourceUpdater: this,
  49082. action: actions.timestampOffset(offset),
  49083. name: 'timestampOffset'
  49084. });
  49085. this.videoTimestampOffset_ = offset;
  49086. }
  49087. return this.videoTimestampOffset_;
  49088. }
  49089. /**
  49090. * Add a function to the queue that will be called
  49091. * when it is its turn to run in the audio queue.
  49092. *
  49093. * @param {Function} callback
  49094. * The callback to queue.
  49095. */
  49096. ;
  49097. _proto.audioQueueCallback = function audioQueueCallback(callback) {
  49098. if (!this.audioBuffer) {
  49099. return;
  49100. }
  49101. pushQueue({
  49102. type: 'audio',
  49103. sourceUpdater: this,
  49104. action: actions.callback(callback),
  49105. name: 'callback'
  49106. });
  49107. }
  49108. /**
  49109. * Add a function to the queue that will be called
  49110. * when it is its turn to run in the video queue.
  49111. *
  49112. * @param {Function} callback
  49113. * The callback to queue.
  49114. */
  49115. ;
  49116. _proto.videoQueueCallback = function videoQueueCallback(callback) {
  49117. if (!this.videoBuffer) {
  49118. return;
  49119. }
  49120. pushQueue({
  49121. type: 'video',
  49122. sourceUpdater: this,
  49123. action: actions.callback(callback),
  49124. name: 'callback'
  49125. });
  49126. }
  49127. /**
  49128. * dispose of the source updater and the underlying sourceBuffer
  49129. */
  49130. ;
  49131. _proto.dispose = function dispose() {
  49132. var _this4 = this;
  49133. this.trigger('dispose');
  49134. bufferTypes.forEach(function (type) {
  49135. _this4.abort(type);
  49136. if (_this4.canRemoveSourceBuffer()) {
  49137. _this4.removeSourceBuffer(type);
  49138. } else {
  49139. _this4[type + "QueueCallback"](function () {
  49140. return cleanupBuffer(type, _this4);
  49141. });
  49142. }
  49143. });
  49144. this.videoAppendQueued_ = false;
  49145. this.delayedAudioAppendQueue_.length = 0;
  49146. if (this.sourceopenListener_) {
  49147. this.mediaSource.removeEventListener('sourceopen', this.sourceopenListener_);
  49148. }
  49149. this.off();
  49150. };
  49151. return SourceUpdater;
  49152. }(videojs.EventTarget);
  49153. var uint8ToUtf8 = function uint8ToUtf8(uintArray) {
  49154. return decodeURIComponent(escape(String.fromCharCode.apply(null, uintArray)));
  49155. };
  49156. var VTT_LINE_TERMINATORS = new Uint8Array('\n\n'.split('').map(function (_char3) {
  49157. return _char3.charCodeAt(0);
  49158. }));
  49159. var NoVttJsError = /*#__PURE__*/function (_Error) {
  49160. inheritsLoose(NoVttJsError, _Error);
  49161. function NoVttJsError() {
  49162. return _Error.call(this, 'Trying to parse received VTT cues, but there is no WebVTT. Make sure vtt.js is loaded.') || this;
  49163. }
  49164. return NoVttJsError;
  49165. }( /*#__PURE__*/wrapNativeSuper(Error));
  49166. /**
  49167. * An object that manages segment loading and appending.
  49168. *
  49169. * @class VTTSegmentLoader
  49170. * @param {Object} options required and optional options
  49171. * @extends videojs.EventTarget
  49172. */
  49173. var VTTSegmentLoader = /*#__PURE__*/function (_SegmentLoader) {
  49174. inheritsLoose(VTTSegmentLoader, _SegmentLoader);
  49175. function VTTSegmentLoader(settings, options) {
  49176. var _this;
  49177. if (options === void 0) {
  49178. options = {};
  49179. }
  49180. _this = _SegmentLoader.call(this, settings, options) || this; // SegmentLoader requires a MediaSource be specified or it will throw an error;
  49181. // however, VTTSegmentLoader has no need of a media source, so delete the reference
  49182. _this.mediaSource_ = null;
  49183. _this.subtitlesTrack_ = null;
  49184. _this.loaderType_ = 'subtitle';
  49185. _this.featuresNativeTextTracks_ = settings.featuresNativeTextTracks;
  49186. _this.loadVttJs = settings.loadVttJs; // The VTT segment will have its own time mappings. Saving VTT segment timing info in
  49187. // the sync controller leads to improper behavior.
  49188. _this.shouldSaveSegmentTimingInfo_ = false;
  49189. return _this;
  49190. }
  49191. var _proto = VTTSegmentLoader.prototype;
  49192. _proto.createTransmuxer_ = function createTransmuxer_() {
  49193. // don't need to transmux any subtitles
  49194. return null;
  49195. }
  49196. /**
  49197. * Indicates which time ranges are buffered
  49198. *
  49199. * @return {TimeRange}
  49200. * TimeRange object representing the current buffered ranges
  49201. */
  49202. ;
  49203. _proto.buffered_ = function buffered_() {
  49204. if (!this.subtitlesTrack_ || !this.subtitlesTrack_.cues || !this.subtitlesTrack_.cues.length) {
  49205. return videojs.createTimeRanges();
  49206. }
  49207. var cues = this.subtitlesTrack_.cues;
  49208. var start = cues[0].startTime;
  49209. var end = cues[cues.length - 1].startTime;
  49210. return videojs.createTimeRanges([[start, end]]);
  49211. }
  49212. /**
  49213. * Gets and sets init segment for the provided map
  49214. *
  49215. * @param {Object} map
  49216. * The map object representing the init segment to get or set
  49217. * @param {boolean=} set
  49218. * If true, the init segment for the provided map should be saved
  49219. * @return {Object}
  49220. * map object for desired init segment
  49221. */
  49222. ;
  49223. _proto.initSegmentForMap = function initSegmentForMap(map, set) {
  49224. if (set === void 0) {
  49225. set = false;
  49226. }
  49227. if (!map) {
  49228. return null;
  49229. }
  49230. var id = initSegmentId(map);
  49231. var storedMap = this.initSegments_[id];
  49232. if (set && !storedMap && map.bytes) {
  49233. // append WebVTT line terminators to the media initialization segment if it exists
  49234. // to follow the WebVTT spec (https://w3c.github.io/webvtt/#file-structure) that
  49235. // requires two or more WebVTT line terminators between the WebVTT header and the
  49236. // rest of the file
  49237. var combinedByteLength = VTT_LINE_TERMINATORS.byteLength + map.bytes.byteLength;
  49238. var combinedSegment = new Uint8Array(combinedByteLength);
  49239. combinedSegment.set(map.bytes);
  49240. combinedSegment.set(VTT_LINE_TERMINATORS, map.bytes.byteLength);
  49241. this.initSegments_[id] = storedMap = {
  49242. resolvedUri: map.resolvedUri,
  49243. byterange: map.byterange,
  49244. bytes: combinedSegment
  49245. };
  49246. }
  49247. return storedMap || map;
  49248. }
  49249. /**
  49250. * Returns true if all configuration required for loading is present, otherwise false.
  49251. *
  49252. * @return {boolean} True if the all configuration is ready for loading
  49253. * @private
  49254. */
  49255. ;
  49256. _proto.couldBeginLoading_ = function couldBeginLoading_() {
  49257. return this.playlist_ && this.subtitlesTrack_ && !this.paused();
  49258. }
  49259. /**
  49260. * Once all the starting parameters have been specified, begin
  49261. * operation. This method should only be invoked from the INIT
  49262. * state.
  49263. *
  49264. * @private
  49265. */
  49266. ;
  49267. _proto.init_ = function init_() {
  49268. this.state = 'READY';
  49269. this.resetEverything();
  49270. return this.monitorBuffer_();
  49271. }
  49272. /**
  49273. * Set a subtitle track on the segment loader to add subtitles to
  49274. *
  49275. * @param {TextTrack=} track
  49276. * The text track to add loaded subtitles to
  49277. * @return {TextTrack}
  49278. * Returns the subtitles track
  49279. */
  49280. ;
  49281. _proto.track = function track(_track) {
  49282. if (typeof _track === 'undefined') {
  49283. return this.subtitlesTrack_;
  49284. }
  49285. this.subtitlesTrack_ = _track; // if we were unpaused but waiting for a sourceUpdater, start
  49286. // buffering now
  49287. if (this.state === 'INIT' && this.couldBeginLoading_()) {
  49288. this.init_();
  49289. }
  49290. return this.subtitlesTrack_;
  49291. }
  49292. /**
  49293. * Remove any data in the source buffer between start and end times
  49294. *
  49295. * @param {number} start - the start time of the region to remove from the buffer
  49296. * @param {number} end - the end time of the region to remove from the buffer
  49297. */
  49298. ;
  49299. _proto.remove = function remove(start, end) {
  49300. removeCuesFromTrack(start, end, this.subtitlesTrack_);
  49301. }
  49302. /**
  49303. * fill the buffer with segements unless the sourceBuffers are
  49304. * currently updating
  49305. *
  49306. * Note: this function should only ever be called by monitorBuffer_
  49307. * and never directly
  49308. *
  49309. * @private
  49310. */
  49311. ;
  49312. _proto.fillBuffer_ = function fillBuffer_() {
  49313. var _this2 = this; // see if we need to begin loading immediately
  49314. var segmentInfo = this.chooseNextRequest_();
  49315. if (!segmentInfo) {
  49316. return;
  49317. }
  49318. if (this.syncController_.timestampOffsetForTimeline(segmentInfo.timeline) === null) {
  49319. // We don't have the timestamp offset that we need to sync subtitles.
  49320. // Rerun on a timestamp offset or user interaction.
  49321. var checkTimestampOffset = function checkTimestampOffset() {
  49322. _this2.state = 'READY';
  49323. if (!_this2.paused()) {
  49324. // if not paused, queue a buffer check as soon as possible
  49325. _this2.monitorBuffer_();
  49326. }
  49327. };
  49328. this.syncController_.one('timestampoffset', checkTimestampOffset);
  49329. this.state = 'WAITING_ON_TIMELINE';
  49330. return;
  49331. }
  49332. this.loadSegment_(segmentInfo);
  49333. } // never set a timestamp offset for vtt segments.
  49334. ;
  49335. _proto.timestampOffsetForSegment_ = function timestampOffsetForSegment_() {
  49336. return null;
  49337. };
  49338. _proto.chooseNextRequest_ = function chooseNextRequest_() {
  49339. return this.skipEmptySegments_(_SegmentLoader.prototype.chooseNextRequest_.call(this));
  49340. }
  49341. /**
  49342. * Prevents the segment loader from requesting segments we know contain no subtitles
  49343. * by walking forward until we find the next segment that we don't know whether it is
  49344. * empty or not.
  49345. *
  49346. * @param {Object} segmentInfo
  49347. * a segment info object that describes the current segment
  49348. * @return {Object}
  49349. * a segment info object that describes the current segment
  49350. */
  49351. ;
  49352. _proto.skipEmptySegments_ = function skipEmptySegments_(segmentInfo) {
  49353. while (segmentInfo && segmentInfo.segment.empty) {
  49354. // stop at the last possible segmentInfo
  49355. if (segmentInfo.mediaIndex + 1 >= segmentInfo.playlist.segments.length) {
  49356. segmentInfo = null;
  49357. break;
  49358. }
  49359. segmentInfo = this.generateSegmentInfo_({
  49360. playlist: segmentInfo.playlist,
  49361. mediaIndex: segmentInfo.mediaIndex + 1,
  49362. startOfSegment: segmentInfo.startOfSegment + segmentInfo.duration,
  49363. isSyncRequest: segmentInfo.isSyncRequest
  49364. });
  49365. }
  49366. return segmentInfo;
  49367. };
  49368. _proto.stopForError = function stopForError(error) {
  49369. this.error(error);
  49370. this.state = 'READY';
  49371. this.pause();
  49372. this.trigger('error');
  49373. }
  49374. /**
  49375. * append a decrypted segement to the SourceBuffer through a SourceUpdater
  49376. *
  49377. * @private
  49378. */
  49379. ;
  49380. _proto.segmentRequestFinished_ = function segmentRequestFinished_(error, simpleSegment, result) {
  49381. var _this3 = this;
  49382. if (!this.subtitlesTrack_) {
  49383. this.state = 'READY';
  49384. return;
  49385. }
  49386. this.saveTransferStats_(simpleSegment.stats); // the request was aborted
  49387. if (!this.pendingSegment_) {
  49388. this.state = 'READY';
  49389. this.mediaRequestsAborted += 1;
  49390. return;
  49391. }
  49392. if (error) {
  49393. if (error.code === REQUEST_ERRORS.TIMEOUT) {
  49394. this.handleTimeout_();
  49395. }
  49396. if (error.code === REQUEST_ERRORS.ABORTED) {
  49397. this.mediaRequestsAborted += 1;
  49398. } else {
  49399. this.mediaRequestsErrored += 1;
  49400. }
  49401. this.stopForError(error);
  49402. return;
  49403. }
  49404. var segmentInfo = this.pendingSegment_; // although the VTT segment loader bandwidth isn't really used, it's good to
  49405. // maintain functionality between segment loaders
  49406. this.saveBandwidthRelatedStats_(segmentInfo.duration, simpleSegment.stats); // if this request included a segment key, save that data in the cache
  49407. if (simpleSegment.key) {
  49408. this.segmentKey(simpleSegment.key, true);
  49409. }
  49410. this.state = 'APPENDING'; // used for tests
  49411. this.trigger('appending');
  49412. var segment = segmentInfo.segment;
  49413. if (segment.map) {
  49414. segment.map.bytes = simpleSegment.map.bytes;
  49415. }
  49416. segmentInfo.bytes = simpleSegment.bytes; // Make sure that vttjs has loaded, otherwise, load it and wait till it finished loading
  49417. if (typeof window.WebVTT !== 'function' && typeof this.loadVttJs === 'function') {
  49418. this.state = 'WAITING_ON_VTTJS'; // should be fine to call multiple times
  49419. // script will be loaded once but multiple listeners will be added to the queue, which is expected.
  49420. this.loadVttJs().then(function () {
  49421. return _this3.segmentRequestFinished_(error, simpleSegment, result);
  49422. }, function () {
  49423. return _this3.stopForError({
  49424. message: 'Error loading vtt.js'
  49425. });
  49426. });
  49427. return;
  49428. }
  49429. segment.requested = true;
  49430. try {
  49431. this.parseVTTCues_(segmentInfo);
  49432. } catch (e) {
  49433. this.stopForError({
  49434. message: e.message
  49435. });
  49436. return;
  49437. }
  49438. this.updateTimeMapping_(segmentInfo, this.syncController_.timelines[segmentInfo.timeline], this.playlist_);
  49439. if (segmentInfo.cues.length) {
  49440. segmentInfo.timingInfo = {
  49441. start: segmentInfo.cues[0].startTime,
  49442. end: segmentInfo.cues[segmentInfo.cues.length - 1].endTime
  49443. };
  49444. } else {
  49445. segmentInfo.timingInfo = {
  49446. start: segmentInfo.startOfSegment,
  49447. end: segmentInfo.startOfSegment + segmentInfo.duration
  49448. };
  49449. }
  49450. if (segmentInfo.isSyncRequest) {
  49451. this.trigger('syncinfoupdate');
  49452. this.pendingSegment_ = null;
  49453. this.state = 'READY';
  49454. return;
  49455. }
  49456. segmentInfo.byteLength = segmentInfo.bytes.byteLength;
  49457. this.mediaSecondsLoaded += segment.duration; // Create VTTCue instances for each cue in the new segment and add them to
  49458. // the subtitle track
  49459. segmentInfo.cues.forEach(function (cue) {
  49460. _this3.subtitlesTrack_.addCue(_this3.featuresNativeTextTracks_ ? new window.VTTCue(cue.startTime, cue.endTime, cue.text) : cue);
  49461. }); // Remove any duplicate cues from the subtitle track. The WebVTT spec allows
  49462. // cues to have identical time-intervals, but if the text is also identical
  49463. // we can safely assume it is a duplicate that can be removed (ex. when a cue
  49464. // "overlaps" VTT segments)
  49465. removeDuplicateCuesFromTrack(this.subtitlesTrack_);
  49466. this.handleAppendsDone_();
  49467. };
  49468. _proto.handleData_ = function handleData_() {// noop as we shouldn't be getting video/audio data captions
  49469. // that we do not support here.
  49470. };
  49471. _proto.updateTimingInfoEnd_ = function updateTimingInfoEnd_() {// noop
  49472. }
  49473. /**
  49474. * Uses the WebVTT parser to parse the segment response
  49475. *
  49476. * @throws NoVttJsError
  49477. *
  49478. * @param {Object} segmentInfo
  49479. * a segment info object that describes the current segment
  49480. * @private
  49481. */
  49482. ;
  49483. _proto.parseVTTCues_ = function parseVTTCues_(segmentInfo) {
  49484. var decoder;
  49485. var decodeBytesToString = false;
  49486. if (typeof window.WebVTT !== 'function') {
  49487. // caller is responsible for exception handling.
  49488. throw new NoVttJsError();
  49489. }
  49490. if (typeof window.TextDecoder === 'function') {
  49491. decoder = new window.TextDecoder('utf8');
  49492. } else {
  49493. decoder = window.WebVTT.StringDecoder();
  49494. decodeBytesToString = true;
  49495. }
  49496. var parser = new window.WebVTT.Parser(window, window.vttjs, decoder);
  49497. segmentInfo.cues = [];
  49498. segmentInfo.timestampmap = {
  49499. MPEGTS: 0,
  49500. LOCAL: 0
  49501. };
  49502. parser.oncue = segmentInfo.cues.push.bind(segmentInfo.cues);
  49503. parser.ontimestampmap = function (map) {
  49504. segmentInfo.timestampmap = map;
  49505. };
  49506. parser.onparsingerror = function (error) {
  49507. videojs.log.warn('Error encountered when parsing cues: ' + error.message);
  49508. };
  49509. if (segmentInfo.segment.map) {
  49510. var mapData = segmentInfo.segment.map.bytes;
  49511. if (decodeBytesToString) {
  49512. mapData = uint8ToUtf8(mapData);
  49513. }
  49514. parser.parse(mapData);
  49515. }
  49516. var segmentData = segmentInfo.bytes;
  49517. if (decodeBytesToString) {
  49518. segmentData = uint8ToUtf8(segmentData);
  49519. }
  49520. parser.parse(segmentData);
  49521. parser.flush();
  49522. }
  49523. /**
  49524. * Updates the start and end times of any cues parsed by the WebVTT parser using
  49525. * the information parsed from the X-TIMESTAMP-MAP header and a TS to media time mapping
  49526. * from the SyncController
  49527. *
  49528. * @param {Object} segmentInfo
  49529. * a segment info object that describes the current segment
  49530. * @param {Object} mappingObj
  49531. * object containing a mapping from TS to media time
  49532. * @param {Object} playlist
  49533. * the playlist object containing the segment
  49534. * @private
  49535. */
  49536. ;
  49537. _proto.updateTimeMapping_ = function updateTimeMapping_(segmentInfo, mappingObj, playlist) {
  49538. var segment = segmentInfo.segment;
  49539. if (!mappingObj) {
  49540. // If the sync controller does not have a mapping of TS to Media Time for the
  49541. // timeline, then we don't have enough information to update the cue
  49542. // start/end times
  49543. return;
  49544. }
  49545. if (!segmentInfo.cues.length) {
  49546. // If there are no cues, we also do not have enough information to figure out
  49547. // segment timing. Mark that the segment contains no cues so we don't re-request
  49548. // an empty segment.
  49549. segment.empty = true;
  49550. return;
  49551. }
  49552. var timestampmap = segmentInfo.timestampmap;
  49553. var diff = timestampmap.MPEGTS / clock_1 - timestampmap.LOCAL + mappingObj.mapping;
  49554. segmentInfo.cues.forEach(function (cue) {
  49555. // First convert cue time to TS time using the timestamp-map provided within the vtt
  49556. cue.startTime += diff;
  49557. cue.endTime += diff;
  49558. });
  49559. if (!playlist.syncInfo) {
  49560. var firstStart = segmentInfo.cues[0].startTime;
  49561. var lastStart = segmentInfo.cues[segmentInfo.cues.length - 1].startTime;
  49562. playlist.syncInfo = {
  49563. mediaSequence: playlist.mediaSequence + segmentInfo.mediaIndex,
  49564. time: Math.min(firstStart, lastStart - segment.duration)
  49565. };
  49566. }
  49567. };
  49568. return VTTSegmentLoader;
  49569. }(SegmentLoader);
  49570. /**
  49571. * @file ad-cue-tags.js
  49572. */
  49573. /**
  49574. * Searches for an ad cue that overlaps with the given mediaTime
  49575. *
  49576. * @param {Object} track
  49577. * the track to find the cue for
  49578. *
  49579. * @param {number} mediaTime
  49580. * the time to find the cue at
  49581. *
  49582. * @return {Object|null}
  49583. * the found cue or null
  49584. */
  49585. var findAdCue = function findAdCue(track, mediaTime) {
  49586. var cues = track.cues;
  49587. for (var i = 0; i < cues.length; i++) {
  49588. var cue = cues[i];
  49589. if (mediaTime >= cue.adStartTime && mediaTime <= cue.adEndTime) {
  49590. return cue;
  49591. }
  49592. }
  49593. return null;
  49594. };
  49595. var updateAdCues = function updateAdCues(media, track, offset) {
  49596. if (offset === void 0) {
  49597. offset = 0;
  49598. }
  49599. if (!media.segments) {
  49600. return;
  49601. }
  49602. var mediaTime = offset;
  49603. var cue;
  49604. for (var i = 0; i < media.segments.length; i++) {
  49605. var segment = media.segments[i];
  49606. if (!cue) {
  49607. // Since the cues will span for at least the segment duration, adding a fudge
  49608. // factor of half segment duration will prevent duplicate cues from being
  49609. // created when timing info is not exact (e.g. cue start time initialized
  49610. // at 10.006677, but next call mediaTime is 10.003332 )
  49611. cue = findAdCue(track, mediaTime + segment.duration / 2);
  49612. }
  49613. if (cue) {
  49614. if ('cueIn' in segment) {
  49615. // Found a CUE-IN so end the cue
  49616. cue.endTime = mediaTime;
  49617. cue.adEndTime = mediaTime;
  49618. mediaTime += segment.duration;
  49619. cue = null;
  49620. continue;
  49621. }
  49622. if (mediaTime < cue.endTime) {
  49623. // Already processed this mediaTime for this cue
  49624. mediaTime += segment.duration;
  49625. continue;
  49626. } // otherwise extend cue until a CUE-IN is found
  49627. cue.endTime += segment.duration;
  49628. } else {
  49629. if ('cueOut' in segment) {
  49630. cue = new window.VTTCue(mediaTime, mediaTime + segment.duration, segment.cueOut);
  49631. cue.adStartTime = mediaTime; // Assumes tag format to be
  49632. // #EXT-X-CUE-OUT:30
  49633. cue.adEndTime = mediaTime + parseFloat(segment.cueOut);
  49634. track.addCue(cue);
  49635. }
  49636. if ('cueOutCont' in segment) {
  49637. // Entered into the middle of an ad cue
  49638. // Assumes tag formate to be
  49639. // #EXT-X-CUE-OUT-CONT:10/30
  49640. var _segment$cueOutCont$s = segment.cueOutCont.split('/').map(parseFloat),
  49641. adOffset = _segment$cueOutCont$s[0],
  49642. adTotal = _segment$cueOutCont$s[1];
  49643. cue = new window.VTTCue(mediaTime, mediaTime + segment.duration, '');
  49644. cue.adStartTime = mediaTime - adOffset;
  49645. cue.adEndTime = cue.adStartTime + adTotal;
  49646. track.addCue(cue);
  49647. }
  49648. }
  49649. mediaTime += segment.duration;
  49650. }
  49651. }; // synchronize expired playlist segments.
  49652. // the max media sequence diff is 48 hours of live stream
  49653. // content with two second segments. Anything larger than that
  49654. // will likely be invalid.
  49655. var MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC = 86400;
  49656. var syncPointStrategies = [// Stategy "VOD": Handle the VOD-case where the sync-point is *always*
  49657. // the equivalence display-time 0 === segment-index 0
  49658. {
  49659. name: 'VOD',
  49660. run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
  49661. if (duration !== Infinity) {
  49662. var syncPoint = {
  49663. time: 0,
  49664. segmentIndex: 0,
  49665. partIndex: null
  49666. };
  49667. return syncPoint;
  49668. }
  49669. return null;
  49670. }
  49671. }, // Stategy "ProgramDateTime": We have a program-date-time tag in this playlist
  49672. {
  49673. name: 'ProgramDateTime',
  49674. run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
  49675. if (!Object.keys(syncController.timelineToDatetimeMappings).length) {
  49676. return null;
  49677. }
  49678. var syncPoint = null;
  49679. var lastDistance = null;
  49680. var partsAndSegments = getPartsAndSegments(playlist);
  49681. currentTime = currentTime || 0;
  49682. for (var i = 0; i < partsAndSegments.length; i++) {
  49683. // start from the end and loop backwards for live
  49684. // or start from the front and loop forwards for non-live
  49685. var index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  49686. var partAndSegment = partsAndSegments[index];
  49687. var segment = partAndSegment.segment;
  49688. var datetimeMapping = syncController.timelineToDatetimeMappings[segment.timeline];
  49689. if (!datetimeMapping || !segment.dateTimeObject) {
  49690. continue;
  49691. }
  49692. var segmentTime = segment.dateTimeObject.getTime() / 1000;
  49693. var start = segmentTime + datetimeMapping; // take part duration into account.
  49694. if (segment.parts && typeof partAndSegment.partIndex === 'number') {
  49695. for (var z = 0; z < partAndSegment.partIndex; z++) {
  49696. start += segment.parts[z].duration;
  49697. }
  49698. }
  49699. var distance = Math.abs(currentTime - start); // Once the distance begins to increase, or if distance is 0, we have passed
  49700. // currentTime and can stop looking for better candidates
  49701. if (lastDistance !== null && (distance === 0 || lastDistance < distance)) {
  49702. break;
  49703. }
  49704. lastDistance = distance;
  49705. syncPoint = {
  49706. time: start,
  49707. segmentIndex: partAndSegment.segmentIndex,
  49708. partIndex: partAndSegment.partIndex
  49709. };
  49710. }
  49711. return syncPoint;
  49712. }
  49713. }, // Stategy "Segment": We have a known time mapping for a timeline and a
  49714. // segment in the current timeline with timing data
  49715. {
  49716. name: 'Segment',
  49717. run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
  49718. var syncPoint = null;
  49719. var lastDistance = null;
  49720. currentTime = currentTime || 0;
  49721. var partsAndSegments = getPartsAndSegments(playlist);
  49722. for (var i = 0; i < partsAndSegments.length; i++) {
  49723. // start from the end and loop backwards for live
  49724. // or start from the front and loop forwards for non-live
  49725. var index = playlist.endList || currentTime === 0 ? i : partsAndSegments.length - (i + 1);
  49726. var partAndSegment = partsAndSegments[index];
  49727. var segment = partAndSegment.segment;
  49728. var start = partAndSegment.part && partAndSegment.part.start || segment && segment.start;
  49729. if (segment.timeline === currentTimeline && typeof start !== 'undefined') {
  49730. var distance = Math.abs(currentTime - start); // Once the distance begins to increase, we have passed
  49731. // currentTime and can stop looking for better candidates
  49732. if (lastDistance !== null && lastDistance < distance) {
  49733. break;
  49734. }
  49735. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  49736. lastDistance = distance;
  49737. syncPoint = {
  49738. time: start,
  49739. segmentIndex: partAndSegment.segmentIndex,
  49740. partIndex: partAndSegment.partIndex
  49741. };
  49742. }
  49743. }
  49744. }
  49745. return syncPoint;
  49746. }
  49747. }, // Stategy "Discontinuity": We have a discontinuity with a known
  49748. // display-time
  49749. {
  49750. name: 'Discontinuity',
  49751. run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
  49752. var syncPoint = null;
  49753. currentTime = currentTime || 0;
  49754. if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  49755. var lastDistance = null;
  49756. for (var i = 0; i < playlist.discontinuityStarts.length; i++) {
  49757. var segmentIndex = playlist.discontinuityStarts[i];
  49758. var discontinuity = playlist.discontinuitySequence + i + 1;
  49759. var discontinuitySync = syncController.discontinuities[discontinuity];
  49760. if (discontinuitySync) {
  49761. var distance = Math.abs(currentTime - discontinuitySync.time); // Once the distance begins to increase, we have passed
  49762. // currentTime and can stop looking for better candidates
  49763. if (lastDistance !== null && lastDistance < distance) {
  49764. break;
  49765. }
  49766. if (!syncPoint || lastDistance === null || lastDistance >= distance) {
  49767. lastDistance = distance;
  49768. syncPoint = {
  49769. time: discontinuitySync.time,
  49770. segmentIndex: segmentIndex,
  49771. partIndex: null
  49772. };
  49773. }
  49774. }
  49775. }
  49776. }
  49777. return syncPoint;
  49778. }
  49779. }, // Stategy "Playlist": We have a playlist with a known mapping of
  49780. // segment index to display time
  49781. {
  49782. name: 'Playlist',
  49783. run: function run(syncController, playlist, duration, currentTimeline, currentTime) {
  49784. if (playlist.syncInfo) {
  49785. var syncPoint = {
  49786. time: playlist.syncInfo.time,
  49787. segmentIndex: playlist.syncInfo.mediaSequence - playlist.mediaSequence,
  49788. partIndex: null
  49789. };
  49790. return syncPoint;
  49791. }
  49792. return null;
  49793. }
  49794. }];
  49795. var SyncController = /*#__PURE__*/function (_videojs$EventTarget) {
  49796. inheritsLoose(SyncController, _videojs$EventTarget);
  49797. function SyncController(options) {
  49798. var _this;
  49799. _this = _videojs$EventTarget.call(this) || this; // ...for synching across variants
  49800. _this.timelines = [];
  49801. _this.discontinuities = [];
  49802. _this.timelineToDatetimeMappings = {};
  49803. _this.logger_ = logger('SyncController');
  49804. return _this;
  49805. }
  49806. /**
  49807. * Find a sync-point for the playlist specified
  49808. *
  49809. * A sync-point is defined as a known mapping from display-time to
  49810. * a segment-index in the current playlist.
  49811. *
  49812. * @param {Playlist} playlist
  49813. * The playlist that needs a sync-point
  49814. * @param {number} duration
  49815. * Duration of the MediaSource (Infinite if playing a live source)
  49816. * @param {number} currentTimeline
  49817. * The last timeline from which a segment was loaded
  49818. * @return {Object}
  49819. * A sync-point object
  49820. */
  49821. var _proto = SyncController.prototype;
  49822. _proto.getSyncPoint = function getSyncPoint(playlist, duration, currentTimeline, currentTime) {
  49823. var syncPoints = this.runStrategies_(playlist, duration, currentTimeline, currentTime);
  49824. if (!syncPoints.length) {
  49825. // Signal that we need to attempt to get a sync-point manually
  49826. // by fetching a segment in the playlist and constructing
  49827. // a sync-point from that information
  49828. return null;
  49829. } // Now find the sync-point that is closest to the currentTime because
  49830. // that should result in the most accurate guess about which segment
  49831. // to fetch
  49832. return this.selectSyncPoint_(syncPoints, {
  49833. key: 'time',
  49834. value: currentTime
  49835. });
  49836. }
  49837. /**
  49838. * Calculate the amount of time that has expired off the playlist during playback
  49839. *
  49840. * @param {Playlist} playlist
  49841. * Playlist object to calculate expired from
  49842. * @param {number} duration
  49843. * Duration of the MediaSource (Infinity if playling a live source)
  49844. * @return {number|null}
  49845. * The amount of time that has expired off the playlist during playback. Null
  49846. * if no sync-points for the playlist can be found.
  49847. */
  49848. ;
  49849. _proto.getExpiredTime = function getExpiredTime(playlist, duration) {
  49850. if (!playlist || !playlist.segments) {
  49851. return null;
  49852. }
  49853. var syncPoints = this.runStrategies_(playlist, duration, playlist.discontinuitySequence, 0); // Without sync-points, there is not enough information to determine the expired time
  49854. if (!syncPoints.length) {
  49855. return null;
  49856. }
  49857. var syncPoint = this.selectSyncPoint_(syncPoints, {
  49858. key: 'segmentIndex',
  49859. value: 0
  49860. }); // If the sync-point is beyond the start of the playlist, we want to subtract the
  49861. // duration from index 0 to syncPoint.segmentIndex instead of adding.
  49862. if (syncPoint.segmentIndex > 0) {
  49863. syncPoint.time *= -1;
  49864. }
  49865. return Math.abs(syncPoint.time + sumDurations({
  49866. defaultDuration: playlist.targetDuration,
  49867. durationList: playlist.segments,
  49868. startIndex: syncPoint.segmentIndex,
  49869. endIndex: 0
  49870. }));
  49871. }
  49872. /**
  49873. * Runs each sync-point strategy and returns a list of sync-points returned by the
  49874. * strategies
  49875. *
  49876. * @private
  49877. * @param {Playlist} playlist
  49878. * The playlist that needs a sync-point
  49879. * @param {number} duration
  49880. * Duration of the MediaSource (Infinity if playing a live source)
  49881. * @param {number} currentTimeline
  49882. * The last timeline from which a segment was loaded
  49883. * @return {Array}
  49884. * A list of sync-point objects
  49885. */
  49886. ;
  49887. _proto.runStrategies_ = function runStrategies_(playlist, duration, currentTimeline, currentTime) {
  49888. var syncPoints = []; // Try to find a sync-point in by utilizing various strategies...
  49889. for (var i = 0; i < syncPointStrategies.length; i++) {
  49890. var strategy = syncPointStrategies[i];
  49891. var syncPoint = strategy.run(this, playlist, duration, currentTimeline, currentTime);
  49892. if (syncPoint) {
  49893. syncPoint.strategy = strategy.name;
  49894. syncPoints.push({
  49895. strategy: strategy.name,
  49896. syncPoint: syncPoint
  49897. });
  49898. }
  49899. }
  49900. return syncPoints;
  49901. }
  49902. /**
  49903. * Selects the sync-point nearest the specified target
  49904. *
  49905. * @private
  49906. * @param {Array} syncPoints
  49907. * List of sync-points to select from
  49908. * @param {Object} target
  49909. * Object specifying the property and value we are targeting
  49910. * @param {string} target.key
  49911. * Specifies the property to target. Must be either 'time' or 'segmentIndex'
  49912. * @param {number} target.value
  49913. * The value to target for the specified key.
  49914. * @return {Object}
  49915. * The sync-point nearest the target
  49916. */
  49917. ;
  49918. _proto.selectSyncPoint_ = function selectSyncPoint_(syncPoints, target) {
  49919. var bestSyncPoint = syncPoints[0].syncPoint;
  49920. var bestDistance = Math.abs(syncPoints[0].syncPoint[target.key] - target.value);
  49921. var bestStrategy = syncPoints[0].strategy;
  49922. for (var i = 1; i < syncPoints.length; i++) {
  49923. var newDistance = Math.abs(syncPoints[i].syncPoint[target.key] - target.value);
  49924. if (newDistance < bestDistance) {
  49925. bestDistance = newDistance;
  49926. bestSyncPoint = syncPoints[i].syncPoint;
  49927. bestStrategy = syncPoints[i].strategy;
  49928. }
  49929. }
  49930. 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 : '') + ']');
  49931. return bestSyncPoint;
  49932. }
  49933. /**
  49934. * Save any meta-data present on the segments when segments leave
  49935. * the live window to the playlist to allow for synchronization at the
  49936. * playlist level later.
  49937. *
  49938. * @param {Playlist} oldPlaylist - The previous active playlist
  49939. * @param {Playlist} newPlaylist - The updated and most current playlist
  49940. */
  49941. ;
  49942. _proto.saveExpiredSegmentInfo = function saveExpiredSegmentInfo(oldPlaylist, newPlaylist) {
  49943. var mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence; // Ignore large media sequence gaps
  49944. if (mediaSequenceDiff > MAX_MEDIA_SEQUENCE_DIFF_FOR_SYNC) {
  49945. videojs.log.warn("Not saving expired segment info. Media sequence gap " + mediaSequenceDiff + " is too large.");
  49946. return;
  49947. } // When a segment expires from the playlist and it has a start time
  49948. // save that information as a possible sync-point reference in future
  49949. for (var i = mediaSequenceDiff - 1; i >= 0; i--) {
  49950. var lastRemovedSegment = oldPlaylist.segments[i];
  49951. if (lastRemovedSegment && typeof lastRemovedSegment.start !== 'undefined') {
  49952. newPlaylist.syncInfo = {
  49953. mediaSequence: oldPlaylist.mediaSequence + i,
  49954. time: lastRemovedSegment.start
  49955. };
  49956. this.logger_("playlist refresh sync: [time:" + newPlaylist.syncInfo.time + "," + (" mediaSequence: " + newPlaylist.syncInfo.mediaSequence + "]"));
  49957. this.trigger('syncinfoupdate');
  49958. break;
  49959. }
  49960. }
  49961. }
  49962. /**
  49963. * Save the mapping from playlist's ProgramDateTime to display. This should only happen
  49964. * before segments start to load.
  49965. *
  49966. * @param {Playlist} playlist - The currently active playlist
  49967. */
  49968. ;
  49969. _proto.setDateTimeMappingForStart = function setDateTimeMappingForStart(playlist) {
  49970. // It's possible for the playlist to be updated before playback starts, meaning time
  49971. // zero is not yet set. If, during these playlist refreshes, a discontinuity is
  49972. // crossed, then the old time zero mapping (for the prior timeline) would be retained
  49973. // unless the mappings are cleared.
  49974. this.timelineToDatetimeMappings = {};
  49975. if (playlist.segments && playlist.segments.length && playlist.segments[0].dateTimeObject) {
  49976. var firstSegment = playlist.segments[0];
  49977. var playlistTimestamp = firstSegment.dateTimeObject.getTime() / 1000;
  49978. this.timelineToDatetimeMappings[firstSegment.timeline] = -playlistTimestamp;
  49979. }
  49980. }
  49981. /**
  49982. * Calculates and saves timeline mappings, playlist sync info, and segment timing values
  49983. * based on the latest timing information.
  49984. *
  49985. * @param {Object} options
  49986. * Options object
  49987. * @param {SegmentInfo} options.segmentInfo
  49988. * The current active request information
  49989. * @param {boolean} options.shouldSaveTimelineMapping
  49990. * If there's a timeline change, determines if the timeline mapping should be
  49991. * saved for timeline mapping and program date time mappings.
  49992. */
  49993. ;
  49994. _proto.saveSegmentTimingInfo = function saveSegmentTimingInfo(_ref) {
  49995. var segmentInfo = _ref.segmentInfo,
  49996. shouldSaveTimelineMapping = _ref.shouldSaveTimelineMapping;
  49997. var didCalculateSegmentTimeMapping = this.calculateSegmentTimeMapping_(segmentInfo, segmentInfo.timingInfo, shouldSaveTimelineMapping);
  49998. var segment = segmentInfo.segment;
  49999. if (didCalculateSegmentTimeMapping) {
  50000. this.saveDiscontinuitySyncInfo_(segmentInfo); // If the playlist does not have sync information yet, record that information
  50001. // now with segment timing information
  50002. if (!segmentInfo.playlist.syncInfo) {
  50003. segmentInfo.playlist.syncInfo = {
  50004. mediaSequence: segmentInfo.playlist.mediaSequence + segmentInfo.mediaIndex,
  50005. time: segment.start
  50006. };
  50007. }
  50008. }
  50009. var dateTime = segment.dateTimeObject;
  50010. if (segment.discontinuity && shouldSaveTimelineMapping && dateTime) {
  50011. this.timelineToDatetimeMappings[segment.timeline] = -(dateTime.getTime() / 1000);
  50012. }
  50013. };
  50014. _proto.timestampOffsetForTimeline = function timestampOffsetForTimeline(timeline) {
  50015. if (typeof this.timelines[timeline] === 'undefined') {
  50016. return null;
  50017. }
  50018. return this.timelines[timeline].time;
  50019. };
  50020. _proto.mappingForTimeline = function mappingForTimeline(timeline) {
  50021. if (typeof this.timelines[timeline] === 'undefined') {
  50022. return null;
  50023. }
  50024. return this.timelines[timeline].mapping;
  50025. }
  50026. /**
  50027. * Use the "media time" for a segment to generate a mapping to "display time" and
  50028. * save that display time to the segment.
  50029. *
  50030. * @private
  50031. * @param {SegmentInfo} segmentInfo
  50032. * The current active request information
  50033. * @param {Object} timingInfo
  50034. * The start and end time of the current segment in "media time"
  50035. * @param {boolean} shouldSaveTimelineMapping
  50036. * If there's a timeline change, determines if the timeline mapping should be
  50037. * saved in timelines.
  50038. * @return {boolean}
  50039. * Returns false if segment time mapping could not be calculated
  50040. */
  50041. ;
  50042. _proto.calculateSegmentTimeMapping_ = function calculateSegmentTimeMapping_(segmentInfo, timingInfo, shouldSaveTimelineMapping) {
  50043. // TODO: remove side effects
  50044. var segment = segmentInfo.segment;
  50045. var part = segmentInfo.part;
  50046. var mappingObj = this.timelines[segmentInfo.timeline];
  50047. var start;
  50048. var end;
  50049. if (typeof segmentInfo.timestampOffset === 'number') {
  50050. mappingObj = {
  50051. time: segmentInfo.startOfSegment,
  50052. mapping: segmentInfo.startOfSegment - timingInfo.start
  50053. };
  50054. if (shouldSaveTimelineMapping) {
  50055. this.timelines[segmentInfo.timeline] = mappingObj;
  50056. this.trigger('timestampoffset');
  50057. this.logger_("time mapping for timeline " + segmentInfo.timeline + ": " + ("[time: " + mappingObj.time + "] [mapping: " + mappingObj.mapping + "]"));
  50058. }
  50059. start = segmentInfo.startOfSegment;
  50060. end = timingInfo.end + mappingObj.mapping;
  50061. } else if (mappingObj) {
  50062. start = timingInfo.start + mappingObj.mapping;
  50063. end = timingInfo.end + mappingObj.mapping;
  50064. } else {
  50065. return false;
  50066. }
  50067. if (part) {
  50068. part.start = start;
  50069. part.end = end;
  50070. } // If we don't have a segment start yet or the start value we got
  50071. // is less than our current segment.start value, save a new start value.
  50072. // We have to do this because parts will have segment timing info saved
  50073. // multiple times and we want segment start to be the earliest part start
  50074. // value for that segment.
  50075. if (!segment.start || start < segment.start) {
  50076. segment.start = start;
  50077. }
  50078. segment.end = end;
  50079. return true;
  50080. }
  50081. /**
  50082. * Each time we have discontinuity in the playlist, attempt to calculate the location
  50083. * in display of the start of the discontinuity and save that. We also save an accuracy
  50084. * value so that we save values with the most accuracy (closest to 0.)
  50085. *
  50086. * @private
  50087. * @param {SegmentInfo} segmentInfo - The current active request information
  50088. */
  50089. ;
  50090. _proto.saveDiscontinuitySyncInfo_ = function saveDiscontinuitySyncInfo_(segmentInfo) {
  50091. var playlist = segmentInfo.playlist;
  50092. var segment = segmentInfo.segment; // If the current segment is a discontinuity then we know exactly where
  50093. // the start of the range and it's accuracy is 0 (greater accuracy values
  50094. // mean more approximation)
  50095. if (segment.discontinuity) {
  50096. this.discontinuities[segment.timeline] = {
  50097. time: segment.start,
  50098. accuracy: 0
  50099. };
  50100. } else if (playlist.discontinuityStarts && playlist.discontinuityStarts.length) {
  50101. // Search for future discontinuities that we can provide better timing
  50102. // information for and save that information for sync purposes
  50103. for (var i = 0; i < playlist.discontinuityStarts.length; i++) {
  50104. var segmentIndex = playlist.discontinuityStarts[i];
  50105. var discontinuity = playlist.discontinuitySequence + i + 1;
  50106. var mediaIndexDiff = segmentIndex - segmentInfo.mediaIndex;
  50107. var accuracy = Math.abs(mediaIndexDiff);
  50108. if (!this.discontinuities[discontinuity] || this.discontinuities[discontinuity].accuracy > accuracy) {
  50109. var time = void 0;
  50110. if (mediaIndexDiff < 0) {
  50111. time = segment.start - sumDurations({
  50112. defaultDuration: playlist.targetDuration,
  50113. durationList: playlist.segments,
  50114. startIndex: segmentInfo.mediaIndex,
  50115. endIndex: segmentIndex
  50116. });
  50117. } else {
  50118. time = segment.end + sumDurations({
  50119. defaultDuration: playlist.targetDuration,
  50120. durationList: playlist.segments,
  50121. startIndex: segmentInfo.mediaIndex + 1,
  50122. endIndex: segmentIndex
  50123. });
  50124. }
  50125. this.discontinuities[discontinuity] = {
  50126. time: time,
  50127. accuracy: accuracy
  50128. };
  50129. }
  50130. }
  50131. }
  50132. };
  50133. _proto.dispose = function dispose() {
  50134. this.trigger('dispose');
  50135. this.off();
  50136. };
  50137. return SyncController;
  50138. }(videojs.EventTarget);
  50139. /**
  50140. * The TimelineChangeController acts as a source for segment loaders to listen for and
  50141. * keep track of latest and pending timeline changes. This is useful to ensure proper
  50142. * sync, as each loader may need to make a consideration for what timeline the other
  50143. * loader is on before making changes which could impact the other loader's media.
  50144. *
  50145. * @class TimelineChangeController
  50146. * @extends videojs.EventTarget
  50147. */
  50148. var TimelineChangeController = /*#__PURE__*/function (_videojs$EventTarget) {
  50149. inheritsLoose(TimelineChangeController, _videojs$EventTarget);
  50150. function TimelineChangeController() {
  50151. var _this;
  50152. _this = _videojs$EventTarget.call(this) || this;
  50153. _this.pendingTimelineChanges_ = {};
  50154. _this.lastTimelineChanges_ = {};
  50155. return _this;
  50156. }
  50157. var _proto = TimelineChangeController.prototype;
  50158. _proto.clearPendingTimelineChange = function clearPendingTimelineChange(type) {
  50159. this.pendingTimelineChanges_[type] = null;
  50160. this.trigger('pendingtimelinechange');
  50161. };
  50162. _proto.pendingTimelineChange = function pendingTimelineChange(_ref) {
  50163. var type = _ref.type,
  50164. from = _ref.from,
  50165. to = _ref.to;
  50166. if (typeof from === 'number' && typeof to === 'number') {
  50167. this.pendingTimelineChanges_[type] = {
  50168. type: type,
  50169. from: from,
  50170. to: to
  50171. };
  50172. this.trigger('pendingtimelinechange');
  50173. }
  50174. return this.pendingTimelineChanges_[type];
  50175. };
  50176. _proto.lastTimelineChange = function lastTimelineChange(_ref2) {
  50177. var type = _ref2.type,
  50178. from = _ref2.from,
  50179. to = _ref2.to;
  50180. if (typeof from === 'number' && typeof to === 'number') {
  50181. this.lastTimelineChanges_[type] = {
  50182. type: type,
  50183. from: from,
  50184. to: to
  50185. };
  50186. delete this.pendingTimelineChanges_[type];
  50187. this.trigger('timelinechange');
  50188. }
  50189. return this.lastTimelineChanges_[type];
  50190. };
  50191. _proto.dispose = function dispose() {
  50192. this.trigger('dispose');
  50193. this.pendingTimelineChanges_ = {};
  50194. this.lastTimelineChanges_ = {};
  50195. this.off();
  50196. };
  50197. return TimelineChangeController;
  50198. }(videojs.EventTarget);
  50199. /* rollup-plugin-worker-factory start for worker!/Users/ddashkevich/projects/http-streaming/src/decrypter-worker.js */
  50200. var workerCode = transform(getWorkerString(function () {
  50201. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  50202. function createCommonjsModule(fn, basedir, module) {
  50203. return module = {
  50204. path: basedir,
  50205. exports: {},
  50206. require: function require(path, base) {
  50207. return commonjsRequire(path, base === undefined || base === null ? module.path : base);
  50208. }
  50209. }, fn(module, module.exports), module.exports;
  50210. }
  50211. function commonjsRequire() {
  50212. throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
  50213. }
  50214. var createClass = createCommonjsModule(function (module) {
  50215. function _defineProperties(target, props) {
  50216. for (var i = 0; i < props.length; i++) {
  50217. var descriptor = props[i];
  50218. descriptor.enumerable = descriptor.enumerable || false;
  50219. descriptor.configurable = true;
  50220. if ("value" in descriptor) descriptor.writable = true;
  50221. Object.defineProperty(target, descriptor.key, descriptor);
  50222. }
  50223. }
  50224. function _createClass(Constructor, protoProps, staticProps) {
  50225. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  50226. if (staticProps) _defineProperties(Constructor, staticProps);
  50227. return Constructor;
  50228. }
  50229. module.exports = _createClass;
  50230. module.exports["default"] = module.exports, module.exports.__esModule = true;
  50231. });
  50232. var setPrototypeOf = createCommonjsModule(function (module) {
  50233. function _setPrototypeOf(o, p) {
  50234. module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
  50235. o.__proto__ = p;
  50236. return o;
  50237. };
  50238. module.exports["default"] = module.exports, module.exports.__esModule = true;
  50239. return _setPrototypeOf(o, p);
  50240. }
  50241. module.exports = _setPrototypeOf;
  50242. module.exports["default"] = module.exports, module.exports.__esModule = true;
  50243. });
  50244. var inheritsLoose = createCommonjsModule(function (module) {
  50245. function _inheritsLoose(subClass, superClass) {
  50246. subClass.prototype = Object.create(superClass.prototype);
  50247. subClass.prototype.constructor = subClass;
  50248. setPrototypeOf(subClass, superClass);
  50249. }
  50250. module.exports = _inheritsLoose;
  50251. module.exports["default"] = module.exports, module.exports.__esModule = true;
  50252. });
  50253. /**
  50254. * @file stream.js
  50255. */
  50256. /**
  50257. * A lightweight readable stream implemention that handles event dispatching.
  50258. *
  50259. * @class Stream
  50260. */
  50261. var Stream = /*#__PURE__*/function () {
  50262. function Stream() {
  50263. this.listeners = {};
  50264. }
  50265. /**
  50266. * Add a listener for a specified event type.
  50267. *
  50268. * @param {string} type the event name
  50269. * @param {Function} listener the callback to be invoked when an event of
  50270. * the specified type occurs
  50271. */
  50272. var _proto = Stream.prototype;
  50273. _proto.on = function on(type, listener) {
  50274. if (!this.listeners[type]) {
  50275. this.listeners[type] = [];
  50276. }
  50277. this.listeners[type].push(listener);
  50278. }
  50279. /**
  50280. * Remove a listener for a specified event type.
  50281. *
  50282. * @param {string} type the event name
  50283. * @param {Function} listener a function previously registered for this
  50284. * type of event through `on`
  50285. * @return {boolean} if we could turn it off or not
  50286. */
  50287. ;
  50288. _proto.off = function off(type, listener) {
  50289. if (!this.listeners[type]) {
  50290. return false;
  50291. }
  50292. var index = this.listeners[type].indexOf(listener); // TODO: which is better?
  50293. // In Video.js we slice listener functions
  50294. // on trigger so that it does not mess up the order
  50295. // while we loop through.
  50296. //
  50297. // Here we slice on off so that the loop in trigger
  50298. // can continue using it's old reference to loop without
  50299. // messing up the order.
  50300. this.listeners[type] = this.listeners[type].slice(0);
  50301. this.listeners[type].splice(index, 1);
  50302. return index > -1;
  50303. }
  50304. /**
  50305. * Trigger an event of the specified type on this stream. Any additional
  50306. * arguments to this function are passed as parameters to event listeners.
  50307. *
  50308. * @param {string} type the event name
  50309. */
  50310. ;
  50311. _proto.trigger = function trigger(type) {
  50312. var callbacks = this.listeners[type];
  50313. if (!callbacks) {
  50314. return;
  50315. } // Slicing the arguments on every invocation of this method
  50316. // can add a significant amount of overhead. Avoid the
  50317. // intermediate object creation for the common case of a
  50318. // single callback argument
  50319. if (arguments.length === 2) {
  50320. var length = callbacks.length;
  50321. for (var i = 0; i < length; ++i) {
  50322. callbacks[i].call(this, arguments[1]);
  50323. }
  50324. } else {
  50325. var args = Array.prototype.slice.call(arguments, 1);
  50326. var _length = callbacks.length;
  50327. for (var _i = 0; _i < _length; ++_i) {
  50328. callbacks[_i].apply(this, args);
  50329. }
  50330. }
  50331. }
  50332. /**
  50333. * Destroys the stream and cleans up.
  50334. */
  50335. ;
  50336. _proto.dispose = function dispose() {
  50337. this.listeners = {};
  50338. }
  50339. /**
  50340. * Forwards all `data` events on this stream to the destination stream. The
  50341. * destination stream should provide a method `push` to receive the data
  50342. * events as they arrive.
  50343. *
  50344. * @param {Stream} destination the stream that will receive all `data` events
  50345. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  50346. */
  50347. ;
  50348. _proto.pipe = function pipe(destination) {
  50349. this.on('data', function (data) {
  50350. destination.push(data);
  50351. });
  50352. };
  50353. return Stream;
  50354. }();
  50355. /*! @name pkcs7 @version 1.0.4 @license Apache-2.0 */
  50356. /**
  50357. * Returns the subarray of a Uint8Array without PKCS#7 padding.
  50358. *
  50359. * @param padded {Uint8Array} unencrypted bytes that have been padded
  50360. * @return {Uint8Array} the unpadded bytes
  50361. * @see http://tools.ietf.org/html/rfc5652
  50362. */
  50363. function unpad(padded) {
  50364. return padded.subarray(0, padded.byteLength - padded[padded.byteLength - 1]);
  50365. }
  50366. /*! @name aes-decrypter @version 3.1.3 @license Apache-2.0 */
  50367. /**
  50368. * @file aes.js
  50369. *
  50370. * This file contains an adaptation of the AES decryption algorithm
  50371. * from the Standford Javascript Cryptography Library. That work is
  50372. * covered by the following copyright and permissions notice:
  50373. *
  50374. * Copyright 2009-2010 Emily Stark, Mike Hamburg, Dan Boneh.
  50375. * All rights reserved.
  50376. *
  50377. * Redistribution and use in source and binary forms, with or without
  50378. * modification, are permitted provided that the following conditions are
  50379. * met:
  50380. *
  50381. * 1. Redistributions of source code must retain the above copyright
  50382. * notice, this list of conditions and the following disclaimer.
  50383. *
  50384. * 2. Redistributions in binary form must reproduce the above
  50385. * copyright notice, this list of conditions and the following
  50386. * disclaimer in the documentation and/or other materials provided
  50387. * with the distribution.
  50388. *
  50389. * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
  50390. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  50391. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  50392. * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR CONTRIBUTORS BE
  50393. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  50394. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  50395. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  50396. * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  50397. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  50398. * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
  50399. * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  50400. *
  50401. * The views and conclusions contained in the software and documentation
  50402. * are those of the authors and should not be interpreted as representing
  50403. * official policies, either expressed or implied, of the authors.
  50404. */
  50405. /**
  50406. * Expand the S-box tables.
  50407. *
  50408. * @private
  50409. */
  50410. var precompute = function precompute() {
  50411. var tables = [[[], [], [], [], []], [[], [], [], [], []]];
  50412. var encTable = tables[0];
  50413. var decTable = tables[1];
  50414. var sbox = encTable[4];
  50415. var sboxInv = decTable[4];
  50416. var i;
  50417. var x;
  50418. var xInv;
  50419. var d = [];
  50420. var th = [];
  50421. var x2;
  50422. var x4;
  50423. var x8;
  50424. var s;
  50425. var tEnc;
  50426. var tDec; // Compute double and third tables
  50427. for (i = 0; i < 256; i++) {
  50428. th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
  50429. }
  50430. for (x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
  50431. // Compute sbox
  50432. s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
  50433. s = s >> 8 ^ s & 255 ^ 99;
  50434. sbox[x] = s;
  50435. sboxInv[s] = x; // Compute MixColumns
  50436. x8 = d[x4 = d[x2 = d[x]]];
  50437. tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  50438. tEnc = d[s] * 0x101 ^ s * 0x1010100;
  50439. for (i = 0; i < 4; i++) {
  50440. encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
  50441. decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
  50442. }
  50443. } // Compactify. Considerable speedup on Firefox.
  50444. for (i = 0; i < 5; i++) {
  50445. encTable[i] = encTable[i].slice(0);
  50446. decTable[i] = decTable[i].slice(0);
  50447. }
  50448. return tables;
  50449. };
  50450. var aesTables = null;
  50451. /**
  50452. * Schedule out an AES key for both encryption and decryption. This
  50453. * is a low-level class. Use a cipher mode to do bulk encryption.
  50454. *
  50455. * @class AES
  50456. * @param key {Array} The key as an array of 4, 6 or 8 words.
  50457. */
  50458. var AES = /*#__PURE__*/function () {
  50459. function AES(key) {
  50460. /**
  50461. * The expanded S-box and inverse S-box tables. These will be computed
  50462. * on the client so that we don't have to send them down the wire.
  50463. *
  50464. * There are two tables, _tables[0] is for encryption and
  50465. * _tables[1] is for decryption.
  50466. *
  50467. * The first 4 sub-tables are the expanded S-box with MixColumns. The
  50468. * last (_tables[01][4]) is the S-box itself.
  50469. *
  50470. * @private
  50471. */
  50472. // if we have yet to precompute the S-box tables
  50473. // do so now
  50474. if (!aesTables) {
  50475. aesTables = precompute();
  50476. } // then make a copy of that object for use
  50477. 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()]];
  50478. var i;
  50479. var j;
  50480. var tmp;
  50481. var sbox = this._tables[0][4];
  50482. var decTable = this._tables[1];
  50483. var keyLen = key.length;
  50484. var rcon = 1;
  50485. if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
  50486. throw new Error('Invalid aes key size');
  50487. }
  50488. var encKey = key.slice(0);
  50489. var decKey = [];
  50490. this._key = [encKey, decKey]; // schedule encryption keys
  50491. for (i = keyLen; i < 4 * keyLen + 28; i++) {
  50492. tmp = encKey[i - 1]; // apply sbox
  50493. if (i % keyLen === 0 || keyLen === 8 && i % keyLen === 4) {
  50494. tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255]; // shift rows and add rcon
  50495. if (i % keyLen === 0) {
  50496. tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
  50497. rcon = rcon << 1 ^ (rcon >> 7) * 283;
  50498. }
  50499. }
  50500. encKey[i] = encKey[i - keyLen] ^ tmp;
  50501. } // schedule decryption keys
  50502. for (j = 0; i; j++, i--) {
  50503. tmp = encKey[j & 3 ? i : i - 4];
  50504. if (i <= 4 || j < 4) {
  50505. decKey[j] = tmp;
  50506. } else {
  50507. decKey[j] = decTable[0][sbox[tmp >>> 24]] ^ decTable[1][sbox[tmp >> 16 & 255]] ^ decTable[2][sbox[tmp >> 8 & 255]] ^ decTable[3][sbox[tmp & 255]];
  50508. }
  50509. }
  50510. }
  50511. /**
  50512. * Decrypt 16 bytes, specified as four 32-bit words.
  50513. *
  50514. * @param {number} encrypted0 the first word to decrypt
  50515. * @param {number} encrypted1 the second word to decrypt
  50516. * @param {number} encrypted2 the third word to decrypt
  50517. * @param {number} encrypted3 the fourth word to decrypt
  50518. * @param {Int32Array} out the array to write the decrypted words
  50519. * into
  50520. * @param {number} offset the offset into the output array to start
  50521. * writing results
  50522. * @return {Array} The plaintext.
  50523. */
  50524. var _proto = AES.prototype;
  50525. _proto.decrypt = function decrypt(encrypted0, encrypted1, encrypted2, encrypted3, out, offset) {
  50526. var key = this._key[1]; // state variables a,b,c,d are loaded with pre-whitened data
  50527. var a = encrypted0 ^ key[0];
  50528. var b = encrypted3 ^ key[1];
  50529. var c = encrypted2 ^ key[2];
  50530. var d = encrypted1 ^ key[3];
  50531. var a2;
  50532. var b2;
  50533. var c2; // key.length === 2 ?
  50534. var nInnerRounds = key.length / 4 - 2;
  50535. var i;
  50536. var kIndex = 4;
  50537. var table = this._tables[1]; // load up the tables
  50538. var table0 = table[0];
  50539. var table1 = table[1];
  50540. var table2 = table[2];
  50541. var table3 = table[3];
  50542. var sbox = table[4]; // Inner rounds. Cribbed from OpenSSL.
  50543. for (i = 0; i < nInnerRounds; i++) {
  50544. a2 = table0[a >>> 24] ^ table1[b >> 16 & 255] ^ table2[c >> 8 & 255] ^ table3[d & 255] ^ key[kIndex];
  50545. b2 = table0[b >>> 24] ^ table1[c >> 16 & 255] ^ table2[d >> 8 & 255] ^ table3[a & 255] ^ key[kIndex + 1];
  50546. c2 = table0[c >>> 24] ^ table1[d >> 16 & 255] ^ table2[a >> 8 & 255] ^ table3[b & 255] ^ key[kIndex + 2];
  50547. d = table0[d >>> 24] ^ table1[a >> 16 & 255] ^ table2[b >> 8 & 255] ^ table3[c & 255] ^ key[kIndex + 3];
  50548. kIndex += 4;
  50549. a = a2;
  50550. b = b2;
  50551. c = c2;
  50552. } // Last round.
  50553. for (i = 0; i < 4; i++) {
  50554. out[(3 & -i) + offset] = sbox[a >>> 24] << 24 ^ sbox[b >> 16 & 255] << 16 ^ sbox[c >> 8 & 255] << 8 ^ sbox[d & 255] ^ key[kIndex++];
  50555. a2 = a;
  50556. a = b;
  50557. b = c;
  50558. c = d;
  50559. d = a2;
  50560. }
  50561. };
  50562. return AES;
  50563. }();
  50564. /**
  50565. * A wrapper around the Stream class to use setTimeout
  50566. * and run stream "jobs" Asynchronously
  50567. *
  50568. * @class AsyncStream
  50569. * @extends Stream
  50570. */
  50571. var AsyncStream = /*#__PURE__*/function (_Stream) {
  50572. inheritsLoose(AsyncStream, _Stream);
  50573. function AsyncStream() {
  50574. var _this;
  50575. _this = _Stream.call(this, Stream) || this;
  50576. _this.jobs = [];
  50577. _this.delay = 1;
  50578. _this.timeout_ = null;
  50579. return _this;
  50580. }
  50581. /**
  50582. * process an async job
  50583. *
  50584. * @private
  50585. */
  50586. var _proto = AsyncStream.prototype;
  50587. _proto.processJob_ = function processJob_() {
  50588. this.jobs.shift()();
  50589. if (this.jobs.length) {
  50590. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  50591. } else {
  50592. this.timeout_ = null;
  50593. }
  50594. }
  50595. /**
  50596. * push a job into the stream
  50597. *
  50598. * @param {Function} job the job to push into the stream
  50599. */
  50600. ;
  50601. _proto.push = function push(job) {
  50602. this.jobs.push(job);
  50603. if (!this.timeout_) {
  50604. this.timeout_ = setTimeout(this.processJob_.bind(this), this.delay);
  50605. }
  50606. };
  50607. return AsyncStream;
  50608. }(Stream);
  50609. /**
  50610. * Convert network-order (big-endian) bytes into their little-endian
  50611. * representation.
  50612. */
  50613. var ntoh = function ntoh(word) {
  50614. return word << 24 | (word & 0xff00) << 8 | (word & 0xff0000) >> 8 | word >>> 24;
  50615. };
  50616. /**
  50617. * Decrypt bytes using AES-128 with CBC and PKCS#7 padding.
  50618. *
  50619. * @param {Uint8Array} encrypted the encrypted bytes
  50620. * @param {Uint32Array} key the bytes of the decryption key
  50621. * @param {Uint32Array} initVector the initialization vector (IV) to
  50622. * use for the first round of CBC.
  50623. * @return {Uint8Array} the decrypted bytes
  50624. *
  50625. * @see http://en.wikipedia.org/wiki/Advanced_Encryption_Standard
  50626. * @see http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29
  50627. * @see https://tools.ietf.org/html/rfc2315
  50628. */
  50629. var decrypt = function decrypt(encrypted, key, initVector) {
  50630. // word-level access to the encrypted bytes
  50631. var encrypted32 = new Int32Array(encrypted.buffer, encrypted.byteOffset, encrypted.byteLength >> 2);
  50632. var decipher = new AES(Array.prototype.slice.call(key)); // byte and word-level access for the decrypted output
  50633. var decrypted = new Uint8Array(encrypted.byteLength);
  50634. var decrypted32 = new Int32Array(decrypted.buffer); // temporary variables for working with the IV, encrypted, and
  50635. // decrypted data
  50636. var init0;
  50637. var init1;
  50638. var init2;
  50639. var init3;
  50640. var encrypted0;
  50641. var encrypted1;
  50642. var encrypted2;
  50643. var encrypted3; // iteration variable
  50644. var wordIx; // pull out the words of the IV to ensure we don't modify the
  50645. // passed-in reference and easier access
  50646. init0 = initVector[0];
  50647. init1 = initVector[1];
  50648. init2 = initVector[2];
  50649. init3 = initVector[3]; // decrypt four word sequences, applying cipher-block chaining (CBC)
  50650. // to each decrypted block
  50651. for (wordIx = 0; wordIx < encrypted32.length; wordIx += 4) {
  50652. // convert big-endian (network order) words into little-endian
  50653. // (javascript order)
  50654. encrypted0 = ntoh(encrypted32[wordIx]);
  50655. encrypted1 = ntoh(encrypted32[wordIx + 1]);
  50656. encrypted2 = ntoh(encrypted32[wordIx + 2]);
  50657. encrypted3 = ntoh(encrypted32[wordIx + 3]); // decrypt the block
  50658. decipher.decrypt(encrypted0, encrypted1, encrypted2, encrypted3, decrypted32, wordIx); // XOR with the IV, and restore network byte-order to obtain the
  50659. // plaintext
  50660. decrypted32[wordIx] = ntoh(decrypted32[wordIx] ^ init0);
  50661. decrypted32[wordIx + 1] = ntoh(decrypted32[wordIx + 1] ^ init1);
  50662. decrypted32[wordIx + 2] = ntoh(decrypted32[wordIx + 2] ^ init2);
  50663. decrypted32[wordIx + 3] = ntoh(decrypted32[wordIx + 3] ^ init3); // setup the IV for the next round
  50664. init0 = encrypted0;
  50665. init1 = encrypted1;
  50666. init2 = encrypted2;
  50667. init3 = encrypted3;
  50668. }
  50669. return decrypted;
  50670. };
  50671. /**
  50672. * The `Decrypter` class that manages decryption of AES
  50673. * data through `AsyncStream` objects and the `decrypt`
  50674. * function
  50675. *
  50676. * @param {Uint8Array} encrypted the encrypted bytes
  50677. * @param {Uint32Array} key the bytes of the decryption key
  50678. * @param {Uint32Array} initVector the initialization vector (IV) to
  50679. * @param {Function} done the function to run when done
  50680. * @class Decrypter
  50681. */
  50682. var Decrypter = /*#__PURE__*/function () {
  50683. function Decrypter(encrypted, key, initVector, done) {
  50684. var step = Decrypter.STEP;
  50685. var encrypted32 = new Int32Array(encrypted.buffer);
  50686. var decrypted = new Uint8Array(encrypted.byteLength);
  50687. var i = 0;
  50688. this.asyncStream_ = new AsyncStream(); // split up the encryption job and do the individual chunks asynchronously
  50689. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  50690. for (i = step; i < encrypted32.length; i += step) {
  50691. initVector = new Uint32Array([ntoh(encrypted32[i - 4]), ntoh(encrypted32[i - 3]), ntoh(encrypted32[i - 2]), ntoh(encrypted32[i - 1])]);
  50692. this.asyncStream_.push(this.decryptChunk_(encrypted32.subarray(i, i + step), key, initVector, decrypted));
  50693. } // invoke the done() callback when everything is finished
  50694. this.asyncStream_.push(function () {
  50695. // remove pkcs#7 padding from the decrypted bytes
  50696. done(null, unpad(decrypted));
  50697. });
  50698. }
  50699. /**
  50700. * a getter for step the maximum number of bytes to process at one time
  50701. *
  50702. * @return {number} the value of step 32000
  50703. */
  50704. var _proto = Decrypter.prototype;
  50705. /**
  50706. * @private
  50707. */
  50708. _proto.decryptChunk_ = function decryptChunk_(encrypted, key, initVector, decrypted) {
  50709. return function () {
  50710. var bytes = decrypt(encrypted, key, initVector);
  50711. decrypted.set(bytes, encrypted.byteOffset);
  50712. };
  50713. };
  50714. createClass(Decrypter, null, [{
  50715. key: "STEP",
  50716. get: function get() {
  50717. // 4 * 8000;
  50718. return 32000;
  50719. }
  50720. }]);
  50721. return Decrypter;
  50722. }();
  50723. var win;
  50724. if (typeof window !== "undefined") {
  50725. win = window;
  50726. } else if (typeof commonjsGlobal !== "undefined") {
  50727. win = commonjsGlobal;
  50728. } else if (typeof self !== "undefined") {
  50729. win = self;
  50730. } else {
  50731. win = {};
  50732. }
  50733. var window_1 = win;
  50734. var isArrayBufferView = function isArrayBufferView(obj) {
  50735. if (ArrayBuffer.isView === 'function') {
  50736. return ArrayBuffer.isView(obj);
  50737. }
  50738. return obj && obj.buffer instanceof ArrayBuffer;
  50739. };
  50740. var BigInt = window_1.BigInt || Number;
  50741. [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
  50742. /**
  50743. * Creates an object for sending to a web worker modifying properties that are TypedArrays
  50744. * into a new object with seperated properties for the buffer, byteOffset, and byteLength.
  50745. *
  50746. * @param {Object} message
  50747. * Object of properties and values to send to the web worker
  50748. * @return {Object}
  50749. * Modified message with TypedArray values expanded
  50750. * @function createTransferableMessage
  50751. */
  50752. var createTransferableMessage = function createTransferableMessage(message) {
  50753. var transferable = {};
  50754. Object.keys(message).forEach(function (key) {
  50755. var value = message[key];
  50756. if (isArrayBufferView(value)) {
  50757. transferable[key] = {
  50758. bytes: value.buffer,
  50759. byteOffset: value.byteOffset,
  50760. byteLength: value.byteLength
  50761. };
  50762. } else {
  50763. transferable[key] = value;
  50764. }
  50765. });
  50766. return transferable;
  50767. };
  50768. /* global self */
  50769. /**
  50770. * Our web worker interface so that things can talk to aes-decrypter
  50771. * that will be running in a web worker. the scope is passed to this by
  50772. * webworkify.
  50773. */
  50774. self.onmessage = function (event) {
  50775. var data = event.data;
  50776. var encrypted = new Uint8Array(data.encrypted.bytes, data.encrypted.byteOffset, data.encrypted.byteLength);
  50777. var key = new Uint32Array(data.key.bytes, data.key.byteOffset, data.key.byteLength / 4);
  50778. var iv = new Uint32Array(data.iv.bytes, data.iv.byteOffset, data.iv.byteLength / 4);
  50779. /* eslint-disable no-new, handle-callback-err */
  50780. new Decrypter(encrypted, key, iv, function (err, bytes) {
  50781. self.postMessage(createTransferableMessage({
  50782. source: data.source,
  50783. decrypted: bytes
  50784. }), [bytes.buffer]);
  50785. });
  50786. /* eslint-enable */
  50787. };
  50788. }));
  50789. var Decrypter = factory(workerCode);
  50790. /* rollup-plugin-worker-factory end for worker!/Users/ddashkevich/projects/http-streaming/src/decrypter-worker.js */
  50791. /**
  50792. * Convert the properties of an HLS track into an audioTrackKind.
  50793. *
  50794. * @private
  50795. */
  50796. var audioTrackKind_ = function audioTrackKind_(properties) {
  50797. var kind = properties["default"] ? 'main' : 'alternative';
  50798. if (properties.characteristics && properties.characteristics.indexOf('public.accessibility.describes-video') >= 0) {
  50799. kind = 'main-desc';
  50800. }
  50801. return kind;
  50802. };
  50803. /**
  50804. * Pause provided segment loader and playlist loader if active
  50805. *
  50806. * @param {SegmentLoader} segmentLoader
  50807. * SegmentLoader to pause
  50808. * @param {Object} mediaType
  50809. * Active media type
  50810. * @function stopLoaders
  50811. */
  50812. var stopLoaders = function stopLoaders(segmentLoader, mediaType) {
  50813. segmentLoader.abort();
  50814. segmentLoader.pause();
  50815. if (mediaType && mediaType.activePlaylistLoader) {
  50816. mediaType.activePlaylistLoader.pause();
  50817. mediaType.activePlaylistLoader = null;
  50818. }
  50819. };
  50820. /**
  50821. * Start loading provided segment loader and playlist loader
  50822. *
  50823. * @param {PlaylistLoader} playlistLoader
  50824. * PlaylistLoader to start loading
  50825. * @param {Object} mediaType
  50826. * Active media type
  50827. * @function startLoaders
  50828. */
  50829. var startLoaders = function startLoaders(playlistLoader, mediaType) {
  50830. // Segment loader will be started after `loadedmetadata` or `loadedplaylist` from the
  50831. // playlist loader
  50832. mediaType.activePlaylistLoader = playlistLoader;
  50833. playlistLoader.load();
  50834. };
  50835. /**
  50836. * Returns a function to be called when the media group changes. It performs a
  50837. * non-destructive (preserve the buffer) resync of the SegmentLoader. This is because a
  50838. * change of group is merely a rendition switch of the same content at another encoding,
  50839. * rather than a change of content, such as switching audio from English to Spanish.
  50840. *
  50841. * @param {string} type
  50842. * MediaGroup type
  50843. * @param {Object} settings
  50844. * Object containing required information for media groups
  50845. * @return {Function}
  50846. * Handler for a non-destructive resync of SegmentLoader when the active media
  50847. * group changes.
  50848. * @function onGroupChanged
  50849. */
  50850. var onGroupChanged = function onGroupChanged(type, settings) {
  50851. return function () {
  50852. var _settings$segmentLoad = settings.segmentLoaders,
  50853. segmentLoader = _settings$segmentLoad[type],
  50854. mainSegmentLoader = _settings$segmentLoad.main,
  50855. mediaType = settings.mediaTypes[type];
  50856. var activeTrack = mediaType.activeTrack();
  50857. var activeGroup = mediaType.getActiveGroup();
  50858. var previousActiveLoader = mediaType.activePlaylistLoader;
  50859. var lastGroup = mediaType.lastGroup_; // the group did not change do nothing
  50860. if (activeGroup && lastGroup && activeGroup.id === lastGroup.id) {
  50861. return;
  50862. }
  50863. mediaType.lastGroup_ = activeGroup;
  50864. mediaType.lastTrack_ = activeTrack;
  50865. stopLoaders(segmentLoader, mediaType);
  50866. if (!activeGroup || activeGroup.isMasterPlaylist) {
  50867. // there is no group active or active group is a main playlist and won't change
  50868. return;
  50869. }
  50870. if (!activeGroup.playlistLoader) {
  50871. if (previousActiveLoader) {
  50872. // The previous group had a playlist loader but the new active group does not
  50873. // this means we are switching from demuxed to muxed audio. In this case we want to
  50874. // do a destructive reset of the main segment loader and not restart the audio
  50875. // loaders.
  50876. mainSegmentLoader.resetEverything();
  50877. }
  50878. return;
  50879. } // Non-destructive resync
  50880. segmentLoader.resyncLoader();
  50881. startLoaders(activeGroup.playlistLoader, mediaType);
  50882. };
  50883. };
  50884. var onGroupChanging = function onGroupChanging(type, settings) {
  50885. return function () {
  50886. var segmentLoader = settings.segmentLoaders[type],
  50887. mediaType = settings.mediaTypes[type];
  50888. mediaType.lastGroup_ = null;
  50889. segmentLoader.abort();
  50890. segmentLoader.pause();
  50891. };
  50892. };
  50893. /**
  50894. * Returns a function to be called when the media track changes. It performs a
  50895. * destructive reset of the SegmentLoader to ensure we start loading as close to
  50896. * currentTime as possible.
  50897. *
  50898. * @param {string} type
  50899. * MediaGroup type
  50900. * @param {Object} settings
  50901. * Object containing required information for media groups
  50902. * @return {Function}
  50903. * Handler for a destructive reset of SegmentLoader when the active media
  50904. * track changes.
  50905. * @function onTrackChanged
  50906. */
  50907. var onTrackChanged = function onTrackChanged(type, settings) {
  50908. return function () {
  50909. var masterPlaylistLoader = settings.masterPlaylistLoader,
  50910. _settings$segmentLoad2 = settings.segmentLoaders,
  50911. segmentLoader = _settings$segmentLoad2[type],
  50912. mainSegmentLoader = _settings$segmentLoad2.main,
  50913. mediaType = settings.mediaTypes[type];
  50914. var activeTrack = mediaType.activeTrack();
  50915. var activeGroup = mediaType.getActiveGroup();
  50916. var previousActiveLoader = mediaType.activePlaylistLoader;
  50917. var lastTrack = mediaType.lastTrack_; // track did not change, do nothing
  50918. if (lastTrack && activeTrack && lastTrack.id === activeTrack.id) {
  50919. return;
  50920. }
  50921. mediaType.lastGroup_ = activeGroup;
  50922. mediaType.lastTrack_ = activeTrack;
  50923. stopLoaders(segmentLoader, mediaType);
  50924. if (!activeGroup) {
  50925. // there is no group active so we do not want to restart loaders
  50926. return;
  50927. }
  50928. if (activeGroup.isMasterPlaylist) {
  50929. // track did not change, do nothing
  50930. if (!activeTrack || !lastTrack || activeTrack.id === lastTrack.id) {
  50931. return;
  50932. }
  50933. var mpc = settings.vhs.masterPlaylistController_;
  50934. var newPlaylist = mpc.selectPlaylist(); // media will not change do nothing
  50935. if (mpc.media() === newPlaylist) {
  50936. return;
  50937. }
  50938. mediaType.logger_("track change. Switching master audio from " + lastTrack.id + " to " + activeTrack.id);
  50939. masterPlaylistLoader.pause();
  50940. mainSegmentLoader.resetEverything();
  50941. mpc.fastQualityChange_(newPlaylist);
  50942. return;
  50943. }
  50944. if (type === 'AUDIO') {
  50945. if (!activeGroup.playlistLoader) {
  50946. // when switching from demuxed audio/video to muxed audio/video (noted by no
  50947. // playlist loader for the audio group), we want to do a destructive reset of the
  50948. // main segment loader and not restart the audio loaders
  50949. mainSegmentLoader.setAudio(true); // don't have to worry about disabling the audio of the audio segment loader since
  50950. // it should be stopped
  50951. mainSegmentLoader.resetEverything();
  50952. return;
  50953. } // although the segment loader is an audio segment loader, call the setAudio
  50954. // function to ensure it is prepared to re-append the init segment (or handle other
  50955. // config changes)
  50956. segmentLoader.setAudio(true);
  50957. mainSegmentLoader.setAudio(false);
  50958. }
  50959. if (previousActiveLoader === activeGroup.playlistLoader) {
  50960. // Nothing has actually changed. This can happen because track change events can fire
  50961. // multiple times for a "single" change. One for enabling the new active track, and
  50962. // one for disabling the track that was active
  50963. startLoaders(activeGroup.playlistLoader, mediaType);
  50964. return;
  50965. }
  50966. if (segmentLoader.track) {
  50967. // For WebVTT, set the new text track in the segmentloader
  50968. segmentLoader.track(activeTrack);
  50969. } // destructive reset
  50970. segmentLoader.resetEverything();
  50971. startLoaders(activeGroup.playlistLoader, mediaType);
  50972. };
  50973. };
  50974. var onError = {
  50975. /**
  50976. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  50977. * an error.
  50978. *
  50979. * @param {string} type
  50980. * MediaGroup type
  50981. * @param {Object} settings
  50982. * Object containing required information for media groups
  50983. * @return {Function}
  50984. * Error handler. Logs warning (or error if the playlist is blacklisted) to
  50985. * console and switches back to default audio track.
  50986. * @function onError.AUDIO
  50987. */
  50988. AUDIO: function AUDIO(type, settings) {
  50989. return function () {
  50990. var segmentLoader = settings.segmentLoaders[type],
  50991. mediaType = settings.mediaTypes[type],
  50992. blacklistCurrentPlaylist = settings.blacklistCurrentPlaylist;
  50993. stopLoaders(segmentLoader, mediaType); // switch back to default audio track
  50994. var activeTrack = mediaType.activeTrack();
  50995. var activeGroup = mediaType.activeGroup();
  50996. var id = (activeGroup.filter(function (group) {
  50997. return group["default"];
  50998. })[0] || activeGroup[0]).id;
  50999. var defaultTrack = mediaType.tracks[id];
  51000. if (activeTrack === defaultTrack) {
  51001. // Default track encountered an error. All we can do now is blacklist the current
  51002. // rendition and hope another will switch audio groups
  51003. blacklistCurrentPlaylist({
  51004. message: 'Problem encountered loading the default audio track.'
  51005. });
  51006. return;
  51007. }
  51008. videojs.log.warn('Problem encountered loading the alternate audio track.' + 'Switching back to default.');
  51009. for (var trackId in mediaType.tracks) {
  51010. mediaType.tracks[trackId].enabled = mediaType.tracks[trackId] === defaultTrack;
  51011. }
  51012. mediaType.onTrackChanged();
  51013. };
  51014. },
  51015. /**
  51016. * Returns a function to be called when a SegmentLoader or PlaylistLoader encounters
  51017. * an error.
  51018. *
  51019. * @param {string} type
  51020. * MediaGroup type
  51021. * @param {Object} settings
  51022. * Object containing required information for media groups
  51023. * @return {Function}
  51024. * Error handler. Logs warning to console and disables the active subtitle track
  51025. * @function onError.SUBTITLES
  51026. */
  51027. SUBTITLES: function SUBTITLES(type, settings) {
  51028. return function () {
  51029. var segmentLoader = settings.segmentLoaders[type],
  51030. mediaType = settings.mediaTypes[type];
  51031. videojs.log.warn('Problem encountered loading the subtitle track.' + 'Disabling subtitle track.');
  51032. stopLoaders(segmentLoader, mediaType);
  51033. var track = mediaType.activeTrack();
  51034. if (track) {
  51035. track.mode = 'disabled';
  51036. }
  51037. mediaType.onTrackChanged();
  51038. };
  51039. }
  51040. };
  51041. var setupListeners = {
  51042. /**
  51043. * Setup event listeners for audio playlist loader
  51044. *
  51045. * @param {string} type
  51046. * MediaGroup type
  51047. * @param {PlaylistLoader|null} playlistLoader
  51048. * PlaylistLoader to register listeners on
  51049. * @param {Object} settings
  51050. * Object containing required information for media groups
  51051. * @function setupListeners.AUDIO
  51052. */
  51053. AUDIO: function AUDIO(type, playlistLoader, settings) {
  51054. if (!playlistLoader) {
  51055. // no playlist loader means audio will be muxed with the video
  51056. return;
  51057. }
  51058. var tech = settings.tech,
  51059. requestOptions = settings.requestOptions,
  51060. segmentLoader = settings.segmentLoaders[type];
  51061. playlistLoader.on('loadedmetadata', function () {
  51062. var media = playlistLoader.media();
  51063. segmentLoader.playlist(media, requestOptions); // if the video is already playing, or if this isn't a live video and preload
  51064. // permits, start downloading segments
  51065. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  51066. segmentLoader.load();
  51067. }
  51068. });
  51069. playlistLoader.on('loadedplaylist', function () {
  51070. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  51071. if (!tech.paused()) {
  51072. segmentLoader.load();
  51073. }
  51074. });
  51075. playlistLoader.on('error', onError[type](type, settings));
  51076. },
  51077. /**
  51078. * Setup event listeners for subtitle playlist loader
  51079. *
  51080. * @param {string} type
  51081. * MediaGroup type
  51082. * @param {PlaylistLoader|null} playlistLoader
  51083. * PlaylistLoader to register listeners on
  51084. * @param {Object} settings
  51085. * Object containing required information for media groups
  51086. * @function setupListeners.SUBTITLES
  51087. */
  51088. SUBTITLES: function SUBTITLES(type, playlistLoader, settings) {
  51089. var tech = settings.tech,
  51090. requestOptions = settings.requestOptions,
  51091. segmentLoader = settings.segmentLoaders[type],
  51092. mediaType = settings.mediaTypes[type];
  51093. playlistLoader.on('loadedmetadata', function () {
  51094. var media = playlistLoader.media();
  51095. segmentLoader.playlist(media, requestOptions);
  51096. segmentLoader.track(mediaType.activeTrack()); // if the video is already playing, or if this isn't a live video and preload
  51097. // permits, start downloading segments
  51098. if (!tech.paused() || media.endList && tech.preload() !== 'none') {
  51099. segmentLoader.load();
  51100. }
  51101. });
  51102. playlistLoader.on('loadedplaylist', function () {
  51103. segmentLoader.playlist(playlistLoader.media(), requestOptions); // If the player isn't paused, ensure that the segment loader is running
  51104. if (!tech.paused()) {
  51105. segmentLoader.load();
  51106. }
  51107. });
  51108. playlistLoader.on('error', onError[type](type, settings));
  51109. }
  51110. };
  51111. var initialize = {
  51112. /**
  51113. * Setup PlaylistLoaders and AudioTracks for the audio groups
  51114. *
  51115. * @param {string} type
  51116. * MediaGroup type
  51117. * @param {Object} settings
  51118. * Object containing required information for media groups
  51119. * @function initialize.AUDIO
  51120. */
  51121. 'AUDIO': function AUDIO(type, settings) {
  51122. var vhs = settings.vhs,
  51123. sourceType = settings.sourceType,
  51124. segmentLoader = settings.segmentLoaders[type],
  51125. requestOptions = settings.requestOptions,
  51126. mediaGroups = settings.master.mediaGroups,
  51127. _settings$mediaTypes$ = settings.mediaTypes[type],
  51128. groups = _settings$mediaTypes$.groups,
  51129. tracks = _settings$mediaTypes$.tracks,
  51130. logger_ = _settings$mediaTypes$.logger_,
  51131. masterPlaylistLoader = settings.masterPlaylistLoader;
  51132. var audioOnlyMaster = isAudioOnly(masterPlaylistLoader.master); // force a default if we have none
  51133. if (!mediaGroups[type] || Object.keys(mediaGroups[type]).length === 0) {
  51134. mediaGroups[type] = {
  51135. main: {
  51136. "default": {
  51137. "default": true
  51138. }
  51139. }
  51140. };
  51141. if (audioOnlyMaster) {
  51142. mediaGroups[type].main["default"].playlists = masterPlaylistLoader.master.playlists;
  51143. }
  51144. }
  51145. for (var groupId in mediaGroups[type]) {
  51146. if (!groups[groupId]) {
  51147. groups[groupId] = [];
  51148. }
  51149. for (var variantLabel in mediaGroups[type][groupId]) {
  51150. var properties = mediaGroups[type][groupId][variantLabel];
  51151. var playlistLoader = void 0;
  51152. if (audioOnlyMaster) {
  51153. logger_("AUDIO group '" + groupId + "' label '" + variantLabel + "' is a master playlist");
  51154. properties.isMasterPlaylist = true;
  51155. playlistLoader = null; // if vhs-json was provided as the source, and the media playlist was resolved,
  51156. // use the resolved media playlist object
  51157. } else if (sourceType === 'vhs-json' && properties.playlists) {
  51158. playlistLoader = new PlaylistLoader(properties.playlists[0], vhs, requestOptions);
  51159. } else if (properties.resolvedUri) {
  51160. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions); // TODO: dash isn't the only type with properties.playlists
  51161. // should we even have properties.playlists in this check.
  51162. } else if (properties.playlists && sourceType === 'dash') {
  51163. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, masterPlaylistLoader);
  51164. } else {
  51165. // no resolvedUri means the audio is muxed with the video when using this
  51166. // audio track
  51167. playlistLoader = null;
  51168. }
  51169. properties = videojs.mergeOptions({
  51170. id: variantLabel,
  51171. playlistLoader: playlistLoader
  51172. }, properties);
  51173. setupListeners[type](type, properties.playlistLoader, settings);
  51174. groups[groupId].push(properties);
  51175. if (typeof tracks[variantLabel] === 'undefined') {
  51176. var track = new videojs.AudioTrack({
  51177. id: variantLabel,
  51178. kind: audioTrackKind_(properties),
  51179. enabled: false,
  51180. language: properties.language,
  51181. "default": properties["default"],
  51182. label: variantLabel
  51183. });
  51184. tracks[variantLabel] = track;
  51185. }
  51186. }
  51187. } // setup single error event handler for the segment loader
  51188. segmentLoader.on('error', onError[type](type, settings));
  51189. },
  51190. /**
  51191. * Setup PlaylistLoaders and TextTracks for the subtitle groups
  51192. *
  51193. * @param {string} type
  51194. * MediaGroup type
  51195. * @param {Object} settings
  51196. * Object containing required information for media groups
  51197. * @function initialize.SUBTITLES
  51198. */
  51199. 'SUBTITLES': function SUBTITLES(type, settings) {
  51200. var tech = settings.tech,
  51201. vhs = settings.vhs,
  51202. sourceType = settings.sourceType,
  51203. segmentLoader = settings.segmentLoaders[type],
  51204. requestOptions = settings.requestOptions,
  51205. mediaGroups = settings.master.mediaGroups,
  51206. _settings$mediaTypes$2 = settings.mediaTypes[type],
  51207. groups = _settings$mediaTypes$2.groups,
  51208. tracks = _settings$mediaTypes$2.tracks,
  51209. masterPlaylistLoader = settings.masterPlaylistLoader;
  51210. for (var groupId in mediaGroups[type]) {
  51211. if (!groups[groupId]) {
  51212. groups[groupId] = [];
  51213. }
  51214. for (var variantLabel in mediaGroups[type][groupId]) {
  51215. if (mediaGroups[type][groupId][variantLabel].forced) {
  51216. // Subtitle playlists with the forced attribute are not selectable in Safari.
  51217. // According to Apple's HLS Authoring Specification:
  51218. // If content has forced subtitles and regular subtitles in a given language,
  51219. // the regular subtitles track in that language MUST contain both the forced
  51220. // subtitles and the regular subtitles for that language.
  51221. // Because of this requirement and that Safari does not add forced subtitles,
  51222. // forced subtitles are skipped here to maintain consistent experience across
  51223. // all platforms
  51224. continue;
  51225. }
  51226. var properties = mediaGroups[type][groupId][variantLabel];
  51227. var playlistLoader = void 0;
  51228. if (sourceType === 'hls') {
  51229. playlistLoader = new PlaylistLoader(properties.resolvedUri, vhs, requestOptions);
  51230. } else if (sourceType === 'dash') {
  51231. var playlists = properties.playlists.filter(function (p) {
  51232. return p.excludeUntil !== Infinity;
  51233. });
  51234. if (!playlists.length) {
  51235. return;
  51236. }
  51237. playlistLoader = new DashPlaylistLoader(properties.playlists[0], vhs, requestOptions, masterPlaylistLoader);
  51238. } else if (sourceType === 'vhs-json') {
  51239. playlistLoader = new PlaylistLoader( // if the vhs-json object included the media playlist, use the media playlist
  51240. // as provided, otherwise use the resolved URI to load the playlist
  51241. properties.playlists ? properties.playlists[0] : properties.resolvedUri, vhs, requestOptions);
  51242. }
  51243. properties = videojs.mergeOptions({
  51244. id: variantLabel,
  51245. playlistLoader: playlistLoader
  51246. }, properties);
  51247. setupListeners[type](type, properties.playlistLoader, settings);
  51248. groups[groupId].push(properties);
  51249. if (typeof tracks[variantLabel] === 'undefined') {
  51250. var track = tech.addRemoteTextTrack({
  51251. id: variantLabel,
  51252. kind: 'subtitles',
  51253. "default": properties["default"] && properties.autoselect,
  51254. language: properties.language,
  51255. label: variantLabel
  51256. }, false).track;
  51257. tracks[variantLabel] = track;
  51258. }
  51259. }
  51260. } // setup single error event handler for the segment loader
  51261. segmentLoader.on('error', onError[type](type, settings));
  51262. },
  51263. /**
  51264. * Setup TextTracks for the closed-caption groups
  51265. *
  51266. * @param {String} type
  51267. * MediaGroup type
  51268. * @param {Object} settings
  51269. * Object containing required information for media groups
  51270. * @function initialize['CLOSED-CAPTIONS']
  51271. */
  51272. 'CLOSED-CAPTIONS': function CLOSEDCAPTIONS(type, settings) {
  51273. var tech = settings.tech,
  51274. mediaGroups = settings.master.mediaGroups,
  51275. _settings$mediaTypes$3 = settings.mediaTypes[type],
  51276. groups = _settings$mediaTypes$3.groups,
  51277. tracks = _settings$mediaTypes$3.tracks;
  51278. for (var groupId in mediaGroups[type]) {
  51279. if (!groups[groupId]) {
  51280. groups[groupId] = [];
  51281. }
  51282. for (var variantLabel in mediaGroups[type][groupId]) {
  51283. var properties = mediaGroups[type][groupId][variantLabel]; // Look for either 608 (CCn) or 708 (SERVICEn) caption services
  51284. if (!/^(?:CC|SERVICE)/.test(properties.instreamId)) {
  51285. continue;
  51286. }
  51287. var captionServices = tech.options_.vhs && tech.options_.vhs.captionServices || {};
  51288. var newProps = {
  51289. label: variantLabel,
  51290. language: properties.language,
  51291. instreamId: properties.instreamId,
  51292. "default": properties["default"] && properties.autoselect
  51293. };
  51294. if (captionServices[newProps.instreamId]) {
  51295. newProps = videojs.mergeOptions(newProps, captionServices[newProps.instreamId]);
  51296. }
  51297. if (newProps["default"] === undefined) {
  51298. delete newProps["default"];
  51299. } // No PlaylistLoader is required for Closed-Captions because the captions are
  51300. // embedded within the video stream
  51301. groups[groupId].push(videojs.mergeOptions({
  51302. id: variantLabel
  51303. }, properties));
  51304. if (typeof tracks[variantLabel] === 'undefined') {
  51305. var track = tech.addRemoteTextTrack({
  51306. id: newProps.instreamId,
  51307. kind: 'captions',
  51308. "default": newProps["default"],
  51309. language: newProps.language,
  51310. label: newProps.label
  51311. }, false).track;
  51312. tracks[variantLabel] = track;
  51313. }
  51314. }
  51315. }
  51316. }
  51317. };
  51318. var groupMatch = function groupMatch(list, media) {
  51319. for (var i = 0; i < list.length; i++) {
  51320. if (playlistMatch(media, list[i])) {
  51321. return true;
  51322. }
  51323. if (list[i].playlists && groupMatch(list[i].playlists, media)) {
  51324. return true;
  51325. }
  51326. }
  51327. return false;
  51328. };
  51329. /**
  51330. * Returns a function used to get the active group of the provided type
  51331. *
  51332. * @param {string} type
  51333. * MediaGroup type
  51334. * @param {Object} settings
  51335. * Object containing required information for media groups
  51336. * @return {Function}
  51337. * Function that returns the active media group for the provided type. Takes an
  51338. * optional parameter {TextTrack} track. If no track is provided, a list of all
  51339. * variants in the group, otherwise the variant corresponding to the provided
  51340. * track is returned.
  51341. * @function activeGroup
  51342. */
  51343. var activeGroup = function activeGroup(type, settings) {
  51344. return function (track) {
  51345. var masterPlaylistLoader = settings.masterPlaylistLoader,
  51346. groups = settings.mediaTypes[type].groups;
  51347. var media = masterPlaylistLoader.media();
  51348. if (!media) {
  51349. return null;
  51350. }
  51351. var variants = null; // set to variants to main media active group
  51352. if (media.attributes[type]) {
  51353. variants = groups[media.attributes[type]];
  51354. }
  51355. var groupKeys = Object.keys(groups);
  51356. if (!variants) {
  51357. // find the masterPlaylistLoader media
  51358. // that is in a media group if we are dealing
  51359. // with audio only
  51360. if (type === 'AUDIO' && groupKeys.length > 1 && isAudioOnly(settings.master)) {
  51361. for (var i = 0; i < groupKeys.length; i++) {
  51362. var groupPropertyList = groups[groupKeys[i]];
  51363. if (groupMatch(groupPropertyList, media)) {
  51364. variants = groupPropertyList;
  51365. break;
  51366. }
  51367. } // use the main group if it exists
  51368. } else if (groups.main) {
  51369. variants = groups.main; // only one group, use that one
  51370. } else if (groupKeys.length === 1) {
  51371. variants = groups[groupKeys[0]];
  51372. }
  51373. }
  51374. if (typeof track === 'undefined') {
  51375. return variants;
  51376. }
  51377. if (track === null || !variants) {
  51378. // An active track was specified so a corresponding group is expected. track === null
  51379. // means no track is currently active so there is no corresponding group
  51380. return null;
  51381. }
  51382. return variants.filter(function (props) {
  51383. return props.id === track.id;
  51384. })[0] || null;
  51385. };
  51386. };
  51387. var activeTrack = {
  51388. /**
  51389. * Returns a function used to get the active track of type provided
  51390. *
  51391. * @param {string} type
  51392. * MediaGroup type
  51393. * @param {Object} settings
  51394. * Object containing required information for media groups
  51395. * @return {Function}
  51396. * Function that returns the active media track for the provided type. Returns
  51397. * null if no track is active
  51398. * @function activeTrack.AUDIO
  51399. */
  51400. AUDIO: function AUDIO(type, settings) {
  51401. return function () {
  51402. var tracks = settings.mediaTypes[type].tracks;
  51403. for (var id in tracks) {
  51404. if (tracks[id].enabled) {
  51405. return tracks[id];
  51406. }
  51407. }
  51408. return null;
  51409. };
  51410. },
  51411. /**
  51412. * Returns a function used to get the active track of type provided
  51413. *
  51414. * @param {string} type
  51415. * MediaGroup type
  51416. * @param {Object} settings
  51417. * Object containing required information for media groups
  51418. * @return {Function}
  51419. * Function that returns the active media track for the provided type. Returns
  51420. * null if no track is active
  51421. * @function activeTrack.SUBTITLES
  51422. */
  51423. SUBTITLES: function SUBTITLES(type, settings) {
  51424. return function () {
  51425. var tracks = settings.mediaTypes[type].tracks;
  51426. for (var id in tracks) {
  51427. if (tracks[id].mode === 'showing' || tracks[id].mode === 'hidden') {
  51428. return tracks[id];
  51429. }
  51430. }
  51431. return null;
  51432. };
  51433. }
  51434. };
  51435. var getActiveGroup = function getActiveGroup(type, _ref) {
  51436. var mediaTypes = _ref.mediaTypes;
  51437. return function () {
  51438. var activeTrack_ = mediaTypes[type].activeTrack();
  51439. if (!activeTrack_) {
  51440. return null;
  51441. }
  51442. return mediaTypes[type].activeGroup(activeTrack_);
  51443. };
  51444. };
  51445. /**
  51446. * Setup PlaylistLoaders and Tracks for media groups (Audio, Subtitles,
  51447. * Closed-Captions) specified in the master manifest.
  51448. *
  51449. * @param {Object} settings
  51450. * Object containing required information for setting up the media groups
  51451. * @param {Tech} settings.tech
  51452. * The tech of the player
  51453. * @param {Object} settings.requestOptions
  51454. * XHR request options used by the segment loaders
  51455. * @param {PlaylistLoader} settings.masterPlaylistLoader
  51456. * PlaylistLoader for the master source
  51457. * @param {VhsHandler} settings.vhs
  51458. * VHS SourceHandler
  51459. * @param {Object} settings.master
  51460. * The parsed master manifest
  51461. * @param {Object} settings.mediaTypes
  51462. * Object to store the loaders, tracks, and utility methods for each media type
  51463. * @param {Function} settings.blacklistCurrentPlaylist
  51464. * Blacklists the current rendition and forces a rendition switch.
  51465. * @function setupMediaGroups
  51466. */
  51467. var setupMediaGroups = function setupMediaGroups(settings) {
  51468. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(function (type) {
  51469. initialize[type](type, settings);
  51470. });
  51471. var mediaTypes = settings.mediaTypes,
  51472. masterPlaylistLoader = settings.masterPlaylistLoader,
  51473. tech = settings.tech,
  51474. vhs = settings.vhs,
  51475. _settings$segmentLoad3 = settings.segmentLoaders,
  51476. audioSegmentLoader = _settings$segmentLoad3['AUDIO'],
  51477. mainSegmentLoader = _settings$segmentLoad3.main; // setup active group and track getters and change event handlers
  51478. ['AUDIO', 'SUBTITLES'].forEach(function (type) {
  51479. mediaTypes[type].activeGroup = activeGroup(type, settings);
  51480. mediaTypes[type].activeTrack = activeTrack[type](type, settings);
  51481. mediaTypes[type].onGroupChanged = onGroupChanged(type, settings);
  51482. mediaTypes[type].onGroupChanging = onGroupChanging(type, settings);
  51483. mediaTypes[type].onTrackChanged = onTrackChanged(type, settings);
  51484. mediaTypes[type].getActiveGroup = getActiveGroup(type, settings);
  51485. }); // DO NOT enable the default subtitle or caption track.
  51486. // DO enable the default audio track
  51487. var audioGroup = mediaTypes.AUDIO.activeGroup();
  51488. if (audioGroup) {
  51489. var groupId = (audioGroup.filter(function (group) {
  51490. return group["default"];
  51491. })[0] || audioGroup[0]).id;
  51492. mediaTypes.AUDIO.tracks[groupId].enabled = true;
  51493. mediaTypes.AUDIO.onGroupChanged();
  51494. mediaTypes.AUDIO.onTrackChanged();
  51495. var activeAudioGroup = mediaTypes.AUDIO.getActiveGroup(); // a similar check for handling setAudio on each loader is run again each time the
  51496. // track is changed, but needs to be handled here since the track may not be considered
  51497. // changed on the first call to onTrackChanged
  51498. if (!activeAudioGroup.playlistLoader) {
  51499. // either audio is muxed with video or the stream is audio only
  51500. mainSegmentLoader.setAudio(true);
  51501. } else {
  51502. // audio is demuxed
  51503. mainSegmentLoader.setAudio(false);
  51504. audioSegmentLoader.setAudio(true);
  51505. }
  51506. }
  51507. masterPlaylistLoader.on('mediachange', function () {
  51508. ['AUDIO', 'SUBTITLES'].forEach(function (type) {
  51509. return mediaTypes[type].onGroupChanged();
  51510. });
  51511. });
  51512. masterPlaylistLoader.on('mediachanging', function () {
  51513. ['AUDIO', 'SUBTITLES'].forEach(function (type) {
  51514. return mediaTypes[type].onGroupChanging();
  51515. });
  51516. }); // custom audio track change event handler for usage event
  51517. var onAudioTrackChanged = function onAudioTrackChanged() {
  51518. mediaTypes.AUDIO.onTrackChanged();
  51519. tech.trigger({
  51520. type: 'usage',
  51521. name: 'vhs-audio-change'
  51522. });
  51523. tech.trigger({
  51524. type: 'usage',
  51525. name: 'hls-audio-change'
  51526. });
  51527. };
  51528. tech.audioTracks().addEventListener('change', onAudioTrackChanged);
  51529. tech.remoteTextTracks().addEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  51530. vhs.on('dispose', function () {
  51531. tech.audioTracks().removeEventListener('change', onAudioTrackChanged);
  51532. tech.remoteTextTracks().removeEventListener('change', mediaTypes.SUBTITLES.onTrackChanged);
  51533. }); // clear existing audio tracks and add the ones we just created
  51534. tech.clearTracks('audio');
  51535. for (var id in mediaTypes.AUDIO.tracks) {
  51536. tech.audioTracks().addTrack(mediaTypes.AUDIO.tracks[id]);
  51537. }
  51538. };
  51539. /**
  51540. * Creates skeleton object used to store the loaders, tracks, and utility methods for each
  51541. * media type
  51542. *
  51543. * @return {Object}
  51544. * Object to store the loaders, tracks, and utility methods for each media type
  51545. * @function createMediaTypes
  51546. */
  51547. var createMediaTypes = function createMediaTypes() {
  51548. var mediaTypes = {};
  51549. ['AUDIO', 'SUBTITLES', 'CLOSED-CAPTIONS'].forEach(function (type) {
  51550. mediaTypes[type] = {
  51551. groups: {},
  51552. tracks: {},
  51553. activePlaylistLoader: null,
  51554. activeGroup: noop,
  51555. activeTrack: noop,
  51556. getActiveGroup: noop,
  51557. onGroupChanged: noop,
  51558. onTrackChanged: noop,
  51559. lastTrack_: null,
  51560. logger_: logger("MediaGroups[" + type + "]")
  51561. };
  51562. });
  51563. return mediaTypes;
  51564. };
  51565. var ABORT_EARLY_BLACKLIST_SECONDS = 60 * 2;
  51566. var Vhs$1; // SegmentLoader stats that need to have each loader's
  51567. // values summed to calculate the final value
  51568. var loaderStats = ['mediaRequests', 'mediaRequestsAborted', 'mediaRequestsTimedout', 'mediaRequestsErrored', 'mediaTransferDuration', 'mediaBytesTransferred', 'mediaAppends'];
  51569. var sumLoaderStat = function sumLoaderStat(stat) {
  51570. return this.audioSegmentLoader_[stat] + this.mainSegmentLoader_[stat];
  51571. };
  51572. var shouldSwitchToMedia = function shouldSwitchToMedia(_ref) {
  51573. var currentPlaylist = _ref.currentPlaylist,
  51574. buffered = _ref.buffered,
  51575. currentTime = _ref.currentTime,
  51576. nextPlaylist = _ref.nextPlaylist,
  51577. bufferLowWaterLine = _ref.bufferLowWaterLine,
  51578. bufferHighWaterLine = _ref.bufferHighWaterLine,
  51579. duration = _ref.duration,
  51580. experimentalBufferBasedABR = _ref.experimentalBufferBasedABR,
  51581. log = _ref.log; // we have no other playlist to switch to
  51582. if (!nextPlaylist) {
  51583. videojs.log.warn('We received no playlist to switch to. Please check your stream.');
  51584. return false;
  51585. }
  51586. var sharedLogLine = "allowing switch " + (currentPlaylist && currentPlaylist.id || 'null') + " -> " + nextPlaylist.id;
  51587. if (!currentPlaylist) {
  51588. log(sharedLogLine + " as current playlist is not set");
  51589. return true;
  51590. } // no need to switch if playlist is the same
  51591. if (nextPlaylist.id === currentPlaylist.id) {
  51592. return false;
  51593. } // determine if current time is in a buffered range.
  51594. var isBuffered = Boolean(findRange(buffered, currentTime).length); // If the playlist is live, then we want to not take low water line into account.
  51595. // This is because in LIVE, the player plays 3 segments from the end of the
  51596. // playlist, and if `BUFFER_LOW_WATER_LINE` is greater than the duration availble
  51597. // in those segments, a viewer will never experience a rendition upswitch.
  51598. if (!currentPlaylist.endList) {
  51599. // For LLHLS live streams, don't switch renditions before playback has started, as it almost
  51600. // doubles the time to first playback.
  51601. if (!isBuffered && typeof currentPlaylist.partTargetDuration === 'number') {
  51602. log("not " + sharedLogLine + " as current playlist is live llhls, but currentTime isn't in buffered.");
  51603. return false;
  51604. }
  51605. log(sharedLogLine + " as current playlist is live");
  51606. return true;
  51607. }
  51608. var forwardBuffer = timeAheadOf(buffered, currentTime);
  51609. 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
  51610. // duration is below the max potential low water line
  51611. if (duration < maxBufferLowWaterLine) {
  51612. log(sharedLogLine + " as duration < max low water line (" + duration + " < " + maxBufferLowWaterLine + ")");
  51613. return true;
  51614. }
  51615. var nextBandwidth = nextPlaylist.attributes.BANDWIDTH;
  51616. var currBandwidth = currentPlaylist.attributes.BANDWIDTH; // when switching down, if our buffer is lower than the high water line,
  51617. // we can switch down
  51618. if (nextBandwidth < currBandwidth && (!experimentalBufferBasedABR || forwardBuffer < bufferHighWaterLine)) {
  51619. var logLine = sharedLogLine + " as next bandwidth < current bandwidth (" + nextBandwidth + " < " + currBandwidth + ")";
  51620. if (experimentalBufferBasedABR) {
  51621. logLine += " and forwardBuffer < bufferHighWaterLine (" + forwardBuffer + " < " + bufferHighWaterLine + ")";
  51622. }
  51623. log(logLine);
  51624. return true;
  51625. } // and if our buffer is higher than the low water line,
  51626. // we can switch up
  51627. if ((!experimentalBufferBasedABR || nextBandwidth > currBandwidth) && forwardBuffer >= bufferLowWaterLine) {
  51628. var _logLine = sharedLogLine + " as forwardBuffer >= bufferLowWaterLine (" + forwardBuffer + " >= " + bufferLowWaterLine + ")";
  51629. if (experimentalBufferBasedABR) {
  51630. _logLine += " and next bandwidth > current bandwidth (" + nextBandwidth + " > " + currBandwidth + ")";
  51631. }
  51632. log(_logLine);
  51633. return true;
  51634. }
  51635. log("not " + sharedLogLine + " as no switching criteria met");
  51636. return false;
  51637. };
  51638. /**
  51639. * the master playlist controller controller all interactons
  51640. * between playlists and segmentloaders. At this time this mainly
  51641. * involves a master playlist and a series of audio playlists
  51642. * if they are available
  51643. *
  51644. * @class MasterPlaylistController
  51645. * @extends videojs.EventTarget
  51646. */
  51647. var MasterPlaylistController = /*#__PURE__*/function (_videojs$EventTarget) {
  51648. inheritsLoose(MasterPlaylistController, _videojs$EventTarget);
  51649. function MasterPlaylistController(options) {
  51650. var _this;
  51651. _this = _videojs$EventTarget.call(this) || this;
  51652. var src = options.src,
  51653. handleManifestRedirects = options.handleManifestRedirects,
  51654. withCredentials = options.withCredentials,
  51655. tech = options.tech,
  51656. bandwidth = options.bandwidth,
  51657. externVhs = options.externVhs,
  51658. useCueTags = options.useCueTags,
  51659. blacklistDuration = options.blacklistDuration,
  51660. enableLowInitialPlaylist = options.enableLowInitialPlaylist,
  51661. sourceType = options.sourceType,
  51662. cacheEncryptionKeys = options.cacheEncryptionKeys,
  51663. experimentalBufferBasedABR = options.experimentalBufferBasedABR,
  51664. experimentalLeastPixelDiffSelector = options.experimentalLeastPixelDiffSelector,
  51665. captionServices = options.captionServices;
  51666. if (!src) {
  51667. throw new Error('A non-empty playlist URL or JSON manifest string is required');
  51668. }
  51669. var maxPlaylistRetries = options.maxPlaylistRetries;
  51670. if (maxPlaylistRetries === null || typeof maxPlaylistRetries === 'undefined') {
  51671. maxPlaylistRetries = Infinity;
  51672. }
  51673. Vhs$1 = externVhs;
  51674. _this.experimentalBufferBasedABR = Boolean(experimentalBufferBasedABR);
  51675. _this.experimentalLeastPixelDiffSelector = Boolean(experimentalLeastPixelDiffSelector);
  51676. _this.withCredentials = withCredentials;
  51677. _this.tech_ = tech;
  51678. _this.vhs_ = tech.vhs;
  51679. _this.sourceType_ = sourceType;
  51680. _this.useCueTags_ = useCueTags;
  51681. _this.blacklistDuration = blacklistDuration;
  51682. _this.maxPlaylistRetries = maxPlaylistRetries;
  51683. _this.enableLowInitialPlaylist = enableLowInitialPlaylist;
  51684. if (_this.useCueTags_) {
  51685. _this.cueTagsTrack_ = _this.tech_.addTextTrack('metadata', 'ad-cues');
  51686. _this.cueTagsTrack_.inBandMetadataTrackDispatchType = '';
  51687. }
  51688. _this.requestOptions_ = {
  51689. withCredentials: withCredentials,
  51690. handleManifestRedirects: handleManifestRedirects,
  51691. maxPlaylistRetries: maxPlaylistRetries,
  51692. timeout: null
  51693. };
  51694. _this.on('error', _this.pauseLoading);
  51695. _this.mediaTypes_ = createMediaTypes();
  51696. _this.mediaSource = new window.MediaSource();
  51697. _this.handleDurationChange_ = _this.handleDurationChange_.bind(assertThisInitialized(_this));
  51698. _this.handleSourceOpen_ = _this.handleSourceOpen_.bind(assertThisInitialized(_this));
  51699. _this.handleSourceEnded_ = _this.handleSourceEnded_.bind(assertThisInitialized(_this));
  51700. _this.mediaSource.addEventListener('durationchange', _this.handleDurationChange_); // load the media source into the player
  51701. _this.mediaSource.addEventListener('sourceopen', _this.handleSourceOpen_);
  51702. _this.mediaSource.addEventListener('sourceended', _this.handleSourceEnded_); // we don't have to handle sourceclose since dispose will handle termination of
  51703. // everything, and the MediaSource should not be detached without a proper disposal
  51704. _this.seekable_ = videojs.createTimeRanges();
  51705. _this.hasPlayed_ = false;
  51706. _this.syncController_ = new SyncController(options);
  51707. _this.segmentMetadataTrack_ = tech.addRemoteTextTrack({
  51708. kind: 'metadata',
  51709. label: 'segment-metadata'
  51710. }, false).track;
  51711. _this.decrypter_ = new Decrypter();
  51712. _this.sourceUpdater_ = new SourceUpdater(_this.mediaSource);
  51713. _this.inbandTextTracks_ = {};
  51714. _this.timelineChangeController_ = new TimelineChangeController();
  51715. var segmentLoaderSettings = {
  51716. vhs: _this.vhs_,
  51717. parse708captions: options.parse708captions,
  51718. useDtsForTimestampOffset: options.useDtsForTimestampOffset,
  51719. captionServices: captionServices,
  51720. mediaSource: _this.mediaSource,
  51721. currentTime: _this.tech_.currentTime.bind(_this.tech_),
  51722. seekable: function seekable() {
  51723. return _this.seekable();
  51724. },
  51725. seeking: function seeking() {
  51726. return _this.tech_.seeking();
  51727. },
  51728. duration: function duration() {
  51729. return _this.duration();
  51730. },
  51731. hasPlayed: function hasPlayed() {
  51732. return _this.hasPlayed_;
  51733. },
  51734. goalBufferLength: function goalBufferLength() {
  51735. return _this.goalBufferLength();
  51736. },
  51737. bandwidth: bandwidth,
  51738. syncController: _this.syncController_,
  51739. decrypter: _this.decrypter_,
  51740. sourceType: _this.sourceType_,
  51741. inbandTextTracks: _this.inbandTextTracks_,
  51742. cacheEncryptionKeys: cacheEncryptionKeys,
  51743. sourceUpdater: _this.sourceUpdater_,
  51744. timelineChangeController: _this.timelineChangeController_,
  51745. experimentalExactManifestTimings: options.experimentalExactManifestTimings
  51746. }; // The source type check not only determines whether a special DASH playlist loader
  51747. // should be used, but also covers the case where the provided src is a vhs-json
  51748. // manifest object (instead of a URL). In the case of vhs-json, the default
  51749. // PlaylistLoader should be used.
  51750. _this.masterPlaylistLoader_ = _this.sourceType_ === 'dash' ? new DashPlaylistLoader(src, _this.vhs_, _this.requestOptions_) : new PlaylistLoader(src, _this.vhs_, _this.requestOptions_);
  51751. _this.setupMasterPlaylistLoaderListeners_(); // setup segment loaders
  51752. // combined audio/video or just video when alternate audio track is selected
  51753. _this.mainSegmentLoader_ = new SegmentLoader(videojs.mergeOptions(segmentLoaderSettings, {
  51754. segmentMetadataTrack: _this.segmentMetadataTrack_,
  51755. loaderType: 'main'
  51756. }), options); // alternate audio track
  51757. _this.audioSegmentLoader_ = new SegmentLoader(videojs.mergeOptions(segmentLoaderSettings, {
  51758. loaderType: 'audio'
  51759. }), options);
  51760. _this.subtitleSegmentLoader_ = new VTTSegmentLoader(videojs.mergeOptions(segmentLoaderSettings, {
  51761. loaderType: 'vtt',
  51762. featuresNativeTextTracks: _this.tech_.featuresNativeTextTracks,
  51763. loadVttJs: function loadVttJs() {
  51764. return new Promise(function (resolve, reject) {
  51765. function onLoad() {
  51766. tech.off('vttjserror', onError);
  51767. resolve();
  51768. }
  51769. function onError() {
  51770. tech.off('vttjsloaded', onLoad);
  51771. reject();
  51772. }
  51773. tech.one('vttjsloaded', onLoad);
  51774. tech.one('vttjserror', onError); // safe to call multiple times, script will be loaded only once:
  51775. tech.addWebVttScript_();
  51776. });
  51777. }
  51778. }), options);
  51779. _this.setupSegmentLoaderListeners_();
  51780. if (_this.experimentalBufferBasedABR) {
  51781. _this.masterPlaylistLoader_.one('loadedplaylist', function () {
  51782. return _this.startABRTimer_();
  51783. });
  51784. _this.tech_.on('pause', function () {
  51785. return _this.stopABRTimer_();
  51786. });
  51787. _this.tech_.on('play', function () {
  51788. return _this.startABRTimer_();
  51789. });
  51790. } // Create SegmentLoader stat-getters
  51791. // mediaRequests_
  51792. // mediaRequestsAborted_
  51793. // mediaRequestsTimedout_
  51794. // mediaRequestsErrored_
  51795. // mediaTransferDuration_
  51796. // mediaBytesTransferred_
  51797. // mediaAppends_
  51798. loaderStats.forEach(function (stat) {
  51799. _this[stat + '_'] = sumLoaderStat.bind(assertThisInitialized(_this), stat);
  51800. });
  51801. _this.logger_ = logger('MPC');
  51802. _this.triggeredFmp4Usage = false;
  51803. if (_this.tech_.preload() === 'none') {
  51804. _this.loadOnPlay_ = function () {
  51805. _this.loadOnPlay_ = null;
  51806. _this.masterPlaylistLoader_.load();
  51807. };
  51808. _this.tech_.one('play', _this.loadOnPlay_);
  51809. } else {
  51810. _this.masterPlaylistLoader_.load();
  51811. }
  51812. _this.timeToLoadedData__ = -1;
  51813. _this.mainAppendsToLoadedData__ = -1;
  51814. _this.audioAppendsToLoadedData__ = -1;
  51815. var event = _this.tech_.preload() === 'none' ? 'play' : 'loadstart'; // start the first frame timer on loadstart or play (for preload none)
  51816. _this.tech_.one(event, function () {
  51817. var timeToLoadedDataStart = Date.now();
  51818. _this.tech_.one('loadeddata', function () {
  51819. _this.timeToLoadedData__ = Date.now() - timeToLoadedDataStart;
  51820. _this.mainAppendsToLoadedData__ = _this.mainSegmentLoader_.mediaAppends;
  51821. _this.audioAppendsToLoadedData__ = _this.audioSegmentLoader_.mediaAppends;
  51822. });
  51823. });
  51824. return _this;
  51825. }
  51826. var _proto = MasterPlaylistController.prototype;
  51827. _proto.mainAppendsToLoadedData_ = function mainAppendsToLoadedData_() {
  51828. return this.mainAppendsToLoadedData__;
  51829. };
  51830. _proto.audioAppendsToLoadedData_ = function audioAppendsToLoadedData_() {
  51831. return this.audioAppendsToLoadedData__;
  51832. };
  51833. _proto.appendsToLoadedData_ = function appendsToLoadedData_() {
  51834. var main = this.mainAppendsToLoadedData_();
  51835. var audio = this.audioAppendsToLoadedData_();
  51836. if (main === -1 || audio === -1) {
  51837. return -1;
  51838. }
  51839. return main + audio;
  51840. };
  51841. _proto.timeToLoadedData_ = function timeToLoadedData_() {
  51842. return this.timeToLoadedData__;
  51843. }
  51844. /**
  51845. * Run selectPlaylist and switch to the new playlist if we should
  51846. *
  51847. * @param {string} [reason=abr] a reason for why the ABR check is made
  51848. * @private
  51849. */
  51850. ;
  51851. _proto.checkABR_ = function checkABR_(reason) {
  51852. if (reason === void 0) {
  51853. reason = 'abr';
  51854. }
  51855. var nextPlaylist = this.selectPlaylist();
  51856. if (nextPlaylist && this.shouldSwitchToMedia_(nextPlaylist)) {
  51857. this.switchMedia_(nextPlaylist, reason);
  51858. }
  51859. };
  51860. _proto.switchMedia_ = function switchMedia_(playlist, cause, delay) {
  51861. var oldMedia = this.media();
  51862. var oldId = oldMedia && (oldMedia.id || oldMedia.uri);
  51863. var newId = playlist.id || playlist.uri;
  51864. if (oldId && oldId !== newId) {
  51865. this.logger_("switch media " + oldId + " -> " + newId + " from " + cause);
  51866. this.tech_.trigger({
  51867. type: 'usage',
  51868. name: "vhs-rendition-change-" + cause
  51869. });
  51870. }
  51871. this.masterPlaylistLoader_.media(playlist, delay);
  51872. }
  51873. /**
  51874. * Start a timer that periodically calls checkABR_
  51875. *
  51876. * @private
  51877. */
  51878. ;
  51879. _proto.startABRTimer_ = function startABRTimer_() {
  51880. var _this2 = this;
  51881. this.stopABRTimer_();
  51882. this.abrTimer_ = window.setInterval(function () {
  51883. return _this2.checkABR_();
  51884. }, 250);
  51885. }
  51886. /**
  51887. * Stop the timer that periodically calls checkABR_
  51888. *
  51889. * @private
  51890. */
  51891. ;
  51892. _proto.stopABRTimer_ = function stopABRTimer_() {
  51893. // if we're scrubbing, we don't need to pause.
  51894. // This getter will be added to Video.js in version 7.11.
  51895. if (this.tech_.scrubbing && this.tech_.scrubbing()) {
  51896. return;
  51897. }
  51898. window.clearInterval(this.abrTimer_);
  51899. this.abrTimer_ = null;
  51900. }
  51901. /**
  51902. * Get a list of playlists for the currently selected audio playlist
  51903. *
  51904. * @return {Array} the array of audio playlists
  51905. */
  51906. ;
  51907. _proto.getAudioTrackPlaylists_ = function getAudioTrackPlaylists_() {
  51908. var master = this.master();
  51909. var defaultPlaylists = master && master.playlists || []; // if we don't have any audio groups then we can only
  51910. // assume that the audio tracks are contained in masters
  51911. // playlist array, use that or an empty array.
  51912. if (!master || !master.mediaGroups || !master.mediaGroups.AUDIO) {
  51913. return defaultPlaylists;
  51914. }
  51915. var AUDIO = master.mediaGroups.AUDIO;
  51916. var groupKeys = Object.keys(AUDIO);
  51917. var track; // get the current active track
  51918. if (Object.keys(this.mediaTypes_.AUDIO.groups).length) {
  51919. track = this.mediaTypes_.AUDIO.activeTrack(); // or get the default track from master if mediaTypes_ isn't setup yet
  51920. } else {
  51921. // default group is `main` or just the first group.
  51922. var defaultGroup = AUDIO.main || groupKeys.length && AUDIO[groupKeys[0]];
  51923. for (var label in defaultGroup) {
  51924. if (defaultGroup[label]["default"]) {
  51925. track = {
  51926. label: label
  51927. };
  51928. break;
  51929. }
  51930. }
  51931. } // no active track no playlists.
  51932. if (!track) {
  51933. return defaultPlaylists;
  51934. }
  51935. var playlists = []; // get all of the playlists that are possible for the
  51936. // active track.
  51937. for (var group in AUDIO) {
  51938. if (AUDIO[group][track.label]) {
  51939. var properties = AUDIO[group][track.label];
  51940. if (properties.playlists && properties.playlists.length) {
  51941. playlists.push.apply(playlists, properties.playlists);
  51942. } else if (properties.uri) {
  51943. playlists.push(properties);
  51944. } else if (master.playlists.length) {
  51945. // if an audio group does not have a uri
  51946. // see if we have main playlists that use it as a group.
  51947. // if we do then add those to the playlists list.
  51948. for (var i = 0; i < master.playlists.length; i++) {
  51949. var playlist = master.playlists[i];
  51950. if (playlist.attributes && playlist.attributes.AUDIO && playlist.attributes.AUDIO === group) {
  51951. playlists.push(playlist);
  51952. }
  51953. }
  51954. }
  51955. }
  51956. }
  51957. if (!playlists.length) {
  51958. return defaultPlaylists;
  51959. }
  51960. return playlists;
  51961. }
  51962. /**
  51963. * Register event handlers on the master playlist loader. A helper
  51964. * function for construction time.
  51965. *
  51966. * @private
  51967. */
  51968. ;
  51969. _proto.setupMasterPlaylistLoaderListeners_ = function setupMasterPlaylistLoaderListeners_() {
  51970. var _this3 = this;
  51971. this.masterPlaylistLoader_.on('loadedmetadata', function () {
  51972. var media = _this3.masterPlaylistLoader_.media();
  51973. var requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  51974. // timeout the request.
  51975. if (isLowestEnabledRendition(_this3.masterPlaylistLoader_.master, _this3.masterPlaylistLoader_.media())) {
  51976. _this3.requestOptions_.timeout = 0;
  51977. } else {
  51978. _this3.requestOptions_.timeout = requestTimeout;
  51979. } // if this isn't a live video and preload permits, start
  51980. // downloading segments
  51981. if (media.endList && _this3.tech_.preload() !== 'none') {
  51982. _this3.mainSegmentLoader_.playlist(media, _this3.requestOptions_);
  51983. _this3.mainSegmentLoader_.load();
  51984. }
  51985. setupMediaGroups({
  51986. sourceType: _this3.sourceType_,
  51987. segmentLoaders: {
  51988. AUDIO: _this3.audioSegmentLoader_,
  51989. SUBTITLES: _this3.subtitleSegmentLoader_,
  51990. main: _this3.mainSegmentLoader_
  51991. },
  51992. tech: _this3.tech_,
  51993. requestOptions: _this3.requestOptions_,
  51994. masterPlaylistLoader: _this3.masterPlaylistLoader_,
  51995. vhs: _this3.vhs_,
  51996. master: _this3.master(),
  51997. mediaTypes: _this3.mediaTypes_,
  51998. blacklistCurrentPlaylist: _this3.blacklistCurrentPlaylist.bind(_this3)
  51999. });
  52000. _this3.triggerPresenceUsage_(_this3.master(), media);
  52001. _this3.setupFirstPlay();
  52002. if (!_this3.mediaTypes_.AUDIO.activePlaylistLoader || _this3.mediaTypes_.AUDIO.activePlaylistLoader.media()) {
  52003. _this3.trigger('selectedinitialmedia');
  52004. } else {
  52005. // We must wait for the active audio playlist loader to
  52006. // finish setting up before triggering this event so the
  52007. // representations API and EME setup is correct
  52008. _this3.mediaTypes_.AUDIO.activePlaylistLoader.one('loadedmetadata', function () {
  52009. _this3.trigger('selectedinitialmedia');
  52010. });
  52011. }
  52012. });
  52013. this.masterPlaylistLoader_.on('loadedplaylist', function () {
  52014. if (_this3.loadOnPlay_) {
  52015. _this3.tech_.off('play', _this3.loadOnPlay_);
  52016. }
  52017. var updatedPlaylist = _this3.masterPlaylistLoader_.media();
  52018. if (!updatedPlaylist) {
  52019. // exclude any variants that are not supported by the browser before selecting
  52020. // an initial media as the playlist selectors do not consider browser support
  52021. _this3.excludeUnsupportedVariants_();
  52022. var selectedMedia;
  52023. if (_this3.enableLowInitialPlaylist) {
  52024. selectedMedia = _this3.selectInitialPlaylist();
  52025. }
  52026. if (!selectedMedia) {
  52027. selectedMedia = _this3.selectPlaylist();
  52028. }
  52029. if (!selectedMedia || !_this3.shouldSwitchToMedia_(selectedMedia)) {
  52030. return;
  52031. }
  52032. _this3.initialMedia_ = selectedMedia;
  52033. _this3.switchMedia_(_this3.initialMedia_, 'initial'); // Under the standard case where a source URL is provided, loadedplaylist will
  52034. // fire again since the playlist will be requested. In the case of vhs-json
  52035. // (where the manifest object is provided as the source), when the media
  52036. // playlist's `segments` list is already available, a media playlist won't be
  52037. // requested, and loadedplaylist won't fire again, so the playlist handler must be
  52038. // called on its own here.
  52039. var haveJsonSource = _this3.sourceType_ === 'vhs-json' && _this3.initialMedia_.segments;
  52040. if (!haveJsonSource) {
  52041. return;
  52042. }
  52043. updatedPlaylist = _this3.initialMedia_;
  52044. }
  52045. _this3.handleUpdatedMediaPlaylist(updatedPlaylist);
  52046. });
  52047. this.masterPlaylistLoader_.on('error', function () {
  52048. _this3.blacklistCurrentPlaylist(_this3.masterPlaylistLoader_.error);
  52049. });
  52050. this.masterPlaylistLoader_.on('mediachanging', function () {
  52051. _this3.mainSegmentLoader_.abort();
  52052. _this3.mainSegmentLoader_.pause();
  52053. });
  52054. this.masterPlaylistLoader_.on('mediachange', function () {
  52055. var media = _this3.masterPlaylistLoader_.media();
  52056. var requestTimeout = media.targetDuration * 1.5 * 1000; // If we don't have any more available playlists, we don't want to
  52057. // timeout the request.
  52058. if (isLowestEnabledRendition(_this3.masterPlaylistLoader_.master, _this3.masterPlaylistLoader_.media())) {
  52059. _this3.requestOptions_.timeout = 0;
  52060. } else {
  52061. _this3.requestOptions_.timeout = requestTimeout;
  52062. }
  52063. _this3.masterPlaylistLoader_.load(); // TODO: Create a new event on the PlaylistLoader that signals
  52064. // that the segments have changed in some way and use that to
  52065. // update the SegmentLoader instead of doing it twice here and
  52066. // on `loadedplaylist`
  52067. _this3.mainSegmentLoader_.playlist(media, _this3.requestOptions_);
  52068. _this3.mainSegmentLoader_.load();
  52069. _this3.tech_.trigger({
  52070. type: 'mediachange',
  52071. bubbles: true
  52072. });
  52073. });
  52074. this.masterPlaylistLoader_.on('playlistunchanged', function () {
  52075. var updatedPlaylist = _this3.masterPlaylistLoader_.media(); // ignore unchanged playlists that have already been
  52076. // excluded for not-changing. We likely just have a really slowly updating
  52077. // playlist.
  52078. if (updatedPlaylist.lastExcludeReason_ === 'playlist-unchanged') {
  52079. return;
  52080. }
  52081. var playlistOutdated = _this3.stuckAtPlaylistEnd_(updatedPlaylist);
  52082. if (playlistOutdated) {
  52083. // Playlist has stopped updating and we're stuck at its end. Try to
  52084. // blacklist it and switch to another playlist in the hope that that
  52085. // one is updating (and give the player a chance to re-adjust to the
  52086. // safe live point).
  52087. _this3.blacklistCurrentPlaylist({
  52088. message: 'Playlist no longer updating.',
  52089. reason: 'playlist-unchanged'
  52090. }); // useful for monitoring QoS
  52091. _this3.tech_.trigger('playliststuck');
  52092. }
  52093. });
  52094. this.masterPlaylistLoader_.on('renditiondisabled', function () {
  52095. _this3.tech_.trigger({
  52096. type: 'usage',
  52097. name: 'vhs-rendition-disabled'
  52098. });
  52099. _this3.tech_.trigger({
  52100. type: 'usage',
  52101. name: 'hls-rendition-disabled'
  52102. });
  52103. });
  52104. this.masterPlaylistLoader_.on('renditionenabled', function () {
  52105. _this3.tech_.trigger({
  52106. type: 'usage',
  52107. name: 'vhs-rendition-enabled'
  52108. });
  52109. _this3.tech_.trigger({
  52110. type: 'usage',
  52111. name: 'hls-rendition-enabled'
  52112. });
  52113. });
  52114. }
  52115. /**
  52116. * Given an updated media playlist (whether it was loaded for the first time, or
  52117. * refreshed for live playlists), update any relevant properties and state to reflect
  52118. * changes in the media that should be accounted for (e.g., cues and duration).
  52119. *
  52120. * @param {Object} updatedPlaylist the updated media playlist object
  52121. *
  52122. * @private
  52123. */
  52124. ;
  52125. _proto.handleUpdatedMediaPlaylist = function handleUpdatedMediaPlaylist(updatedPlaylist) {
  52126. if (this.useCueTags_) {
  52127. this.updateAdCues_(updatedPlaylist);
  52128. } // TODO: Create a new event on the PlaylistLoader that signals
  52129. // that the segments have changed in some way and use that to
  52130. // update the SegmentLoader instead of doing it twice here and
  52131. // on `mediachange`
  52132. this.mainSegmentLoader_.playlist(updatedPlaylist, this.requestOptions_);
  52133. this.updateDuration(!updatedPlaylist.endList); // If the player isn't paused, ensure that the segment loader is running,
  52134. // as it is possible that it was temporarily stopped while waiting for
  52135. // a playlist (e.g., in case the playlist errored and we re-requested it).
  52136. if (!this.tech_.paused()) {
  52137. this.mainSegmentLoader_.load();
  52138. if (this.audioSegmentLoader_) {
  52139. this.audioSegmentLoader_.load();
  52140. }
  52141. }
  52142. }
  52143. /**
  52144. * A helper function for triggerring presence usage events once per source
  52145. *
  52146. * @private
  52147. */
  52148. ;
  52149. _proto.triggerPresenceUsage_ = function triggerPresenceUsage_(master, media) {
  52150. var mediaGroups = master.mediaGroups || {};
  52151. var defaultDemuxed = true;
  52152. var audioGroupKeys = Object.keys(mediaGroups.AUDIO);
  52153. for (var mediaGroup in mediaGroups.AUDIO) {
  52154. for (var label in mediaGroups.AUDIO[mediaGroup]) {
  52155. var properties = mediaGroups.AUDIO[mediaGroup][label];
  52156. if (!properties.uri) {
  52157. defaultDemuxed = false;
  52158. }
  52159. }
  52160. }
  52161. if (defaultDemuxed) {
  52162. this.tech_.trigger({
  52163. type: 'usage',
  52164. name: 'vhs-demuxed'
  52165. });
  52166. this.tech_.trigger({
  52167. type: 'usage',
  52168. name: 'hls-demuxed'
  52169. });
  52170. }
  52171. if (Object.keys(mediaGroups.SUBTITLES).length) {
  52172. this.tech_.trigger({
  52173. type: 'usage',
  52174. name: 'vhs-webvtt'
  52175. });
  52176. this.tech_.trigger({
  52177. type: 'usage',
  52178. name: 'hls-webvtt'
  52179. });
  52180. }
  52181. if (Vhs$1.Playlist.isAes(media)) {
  52182. this.tech_.trigger({
  52183. type: 'usage',
  52184. name: 'vhs-aes'
  52185. });
  52186. this.tech_.trigger({
  52187. type: 'usage',
  52188. name: 'hls-aes'
  52189. });
  52190. }
  52191. if (audioGroupKeys.length && Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length > 1) {
  52192. this.tech_.trigger({
  52193. type: 'usage',
  52194. name: 'vhs-alternate-audio'
  52195. });
  52196. this.tech_.trigger({
  52197. type: 'usage',
  52198. name: 'hls-alternate-audio'
  52199. });
  52200. }
  52201. if (this.useCueTags_) {
  52202. this.tech_.trigger({
  52203. type: 'usage',
  52204. name: 'vhs-playlist-cue-tags'
  52205. });
  52206. this.tech_.trigger({
  52207. type: 'usage',
  52208. name: 'hls-playlist-cue-tags'
  52209. });
  52210. }
  52211. };
  52212. _proto.shouldSwitchToMedia_ = function shouldSwitchToMedia_(nextPlaylist) {
  52213. var currentPlaylist = this.masterPlaylistLoader_.media() || this.masterPlaylistLoader_.pendingMedia_;
  52214. var currentTime = this.tech_.currentTime();
  52215. var bufferLowWaterLine = this.bufferLowWaterLine();
  52216. var bufferHighWaterLine = this.bufferHighWaterLine();
  52217. var buffered = this.tech_.buffered();
  52218. return shouldSwitchToMedia({
  52219. buffered: buffered,
  52220. currentTime: currentTime,
  52221. currentPlaylist: currentPlaylist,
  52222. nextPlaylist: nextPlaylist,
  52223. bufferLowWaterLine: bufferLowWaterLine,
  52224. bufferHighWaterLine: bufferHighWaterLine,
  52225. duration: this.duration(),
  52226. experimentalBufferBasedABR: this.experimentalBufferBasedABR,
  52227. log: this.logger_
  52228. });
  52229. }
  52230. /**
  52231. * Register event handlers on the segment loaders. A helper function
  52232. * for construction time.
  52233. *
  52234. * @private
  52235. */
  52236. ;
  52237. _proto.setupSegmentLoaderListeners_ = function setupSegmentLoaderListeners_() {
  52238. var _this4 = this;
  52239. this.mainSegmentLoader_.on('bandwidthupdate', function () {
  52240. // Whether or not buffer based ABR or another ABR is used, on a bandwidth change it's
  52241. // useful to check to see if a rendition switch should be made.
  52242. _this4.checkABR_('bandwidthupdate');
  52243. _this4.tech_.trigger('bandwidthupdate');
  52244. });
  52245. this.mainSegmentLoader_.on('timeout', function () {
  52246. if (_this4.experimentalBufferBasedABR) {
  52247. // If a rendition change is needed, then it would've be done on `bandwidthupdate`.
  52248. // Here the only consideration is that for buffer based ABR there's no guarantee
  52249. // of an immediate switch (since the bandwidth is averaged with a timeout
  52250. // bandwidth value of 1), so force a load on the segment loader to keep it going.
  52251. _this4.mainSegmentLoader_.load();
  52252. }
  52253. }); // `progress` events are not reliable enough of a bandwidth measure to trigger buffer
  52254. // based ABR.
  52255. if (!this.experimentalBufferBasedABR) {
  52256. this.mainSegmentLoader_.on('progress', function () {
  52257. _this4.trigger('progress');
  52258. });
  52259. }
  52260. this.mainSegmentLoader_.on('error', function () {
  52261. _this4.blacklistCurrentPlaylist(_this4.mainSegmentLoader_.error());
  52262. });
  52263. this.mainSegmentLoader_.on('appenderror', function () {
  52264. _this4.error = _this4.mainSegmentLoader_.error_;
  52265. _this4.trigger('error');
  52266. });
  52267. this.mainSegmentLoader_.on('syncinfoupdate', function () {
  52268. _this4.onSyncInfoUpdate_();
  52269. });
  52270. this.mainSegmentLoader_.on('timestampoffset', function () {
  52271. _this4.tech_.trigger({
  52272. type: 'usage',
  52273. name: 'vhs-timestamp-offset'
  52274. });
  52275. _this4.tech_.trigger({
  52276. type: 'usage',
  52277. name: 'hls-timestamp-offset'
  52278. });
  52279. });
  52280. this.audioSegmentLoader_.on('syncinfoupdate', function () {
  52281. _this4.onSyncInfoUpdate_();
  52282. });
  52283. this.audioSegmentLoader_.on('appenderror', function () {
  52284. _this4.error = _this4.audioSegmentLoader_.error_;
  52285. _this4.trigger('error');
  52286. });
  52287. this.mainSegmentLoader_.on('ended', function () {
  52288. _this4.logger_('main segment loader ended');
  52289. _this4.onEndOfStream();
  52290. });
  52291. this.mainSegmentLoader_.on('earlyabort', function (event) {
  52292. // never try to early abort with the new ABR algorithm
  52293. if (_this4.experimentalBufferBasedABR) {
  52294. return;
  52295. }
  52296. _this4.delegateLoaders_('all', ['abort']);
  52297. _this4.blacklistCurrentPlaylist({
  52298. message: 'Aborted early because there isn\'t enough bandwidth to complete the ' + 'request without rebuffering.'
  52299. }, ABORT_EARLY_BLACKLIST_SECONDS);
  52300. });
  52301. var updateCodecs = function updateCodecs() {
  52302. if (!_this4.sourceUpdater_.hasCreatedSourceBuffers()) {
  52303. return _this4.tryToCreateSourceBuffers_();
  52304. }
  52305. var codecs = _this4.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  52306. if (!codecs) {
  52307. return;
  52308. }
  52309. _this4.sourceUpdater_.addOrChangeSourceBuffers(codecs);
  52310. };
  52311. this.mainSegmentLoader_.on('trackinfo', updateCodecs);
  52312. this.audioSegmentLoader_.on('trackinfo', updateCodecs);
  52313. this.mainSegmentLoader_.on('fmp4', function () {
  52314. if (!_this4.triggeredFmp4Usage) {
  52315. _this4.tech_.trigger({
  52316. type: 'usage',
  52317. name: 'vhs-fmp4'
  52318. });
  52319. _this4.tech_.trigger({
  52320. type: 'usage',
  52321. name: 'hls-fmp4'
  52322. });
  52323. _this4.triggeredFmp4Usage = true;
  52324. }
  52325. });
  52326. this.audioSegmentLoader_.on('fmp4', function () {
  52327. if (!_this4.triggeredFmp4Usage) {
  52328. _this4.tech_.trigger({
  52329. type: 'usage',
  52330. name: 'vhs-fmp4'
  52331. });
  52332. _this4.tech_.trigger({
  52333. type: 'usage',
  52334. name: 'hls-fmp4'
  52335. });
  52336. _this4.triggeredFmp4Usage = true;
  52337. }
  52338. });
  52339. this.audioSegmentLoader_.on('ended', function () {
  52340. _this4.logger_('audioSegmentLoader ended');
  52341. _this4.onEndOfStream();
  52342. });
  52343. };
  52344. _proto.mediaSecondsLoaded_ = function mediaSecondsLoaded_() {
  52345. return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded + this.mainSegmentLoader_.mediaSecondsLoaded);
  52346. }
  52347. /**
  52348. * Call load on our SegmentLoaders
  52349. */
  52350. ;
  52351. _proto.load = function load() {
  52352. this.mainSegmentLoader_.load();
  52353. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  52354. this.audioSegmentLoader_.load();
  52355. }
  52356. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  52357. this.subtitleSegmentLoader_.load();
  52358. }
  52359. }
  52360. /**
  52361. * Re-tune playback quality level for the current player
  52362. * conditions without performing destructive actions, like
  52363. * removing already buffered content
  52364. *
  52365. * @private
  52366. * @deprecated
  52367. */
  52368. ;
  52369. _proto.smoothQualityChange_ = function smoothQualityChange_(media) {
  52370. if (media === void 0) {
  52371. media = this.selectPlaylist();
  52372. }
  52373. this.fastQualityChange_(media);
  52374. }
  52375. /**
  52376. * Re-tune playback quality level for the current player
  52377. * conditions. This method will perform destructive actions like removing
  52378. * already buffered content in order to readjust the currently active
  52379. * playlist quickly. This is good for manual quality changes
  52380. *
  52381. * @private
  52382. */
  52383. ;
  52384. _proto.fastQualityChange_ = function fastQualityChange_(media) {
  52385. var _this5 = this;
  52386. if (media === void 0) {
  52387. media = this.selectPlaylist();
  52388. }
  52389. if (media === this.masterPlaylistLoader_.media()) {
  52390. this.logger_('skipping fastQualityChange because new media is same as old');
  52391. return;
  52392. }
  52393. this.switchMedia_(media, 'fast-quality'); // Delete all buffered data to allow an immediate quality switch, then seek to give
  52394. // the browser a kick to remove any cached frames from the previous rendtion (.04 seconds
  52395. // ahead is roughly the minimum that will accomplish this across a variety of content
  52396. // in IE and Edge, but seeking in place is sufficient on all other browsers)
  52397. // Edge/IE bug: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14600375/
  52398. // Chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=651904
  52399. this.mainSegmentLoader_.resetEverything(function () {
  52400. // Since this is not a typical seek, we avoid the seekTo method which can cause segments
  52401. // from the previously enabled rendition to load before the new playlist has finished loading
  52402. if (videojs.browser.IE_VERSION || videojs.browser.IS_EDGE) {
  52403. _this5.tech_.setCurrentTime(_this5.tech_.currentTime() + 0.04);
  52404. } else {
  52405. _this5.tech_.setCurrentTime(_this5.tech_.currentTime());
  52406. }
  52407. }); // don't need to reset audio as it is reset when media changes
  52408. }
  52409. /**
  52410. * Begin playback.
  52411. */
  52412. ;
  52413. _proto.play = function play() {
  52414. if (this.setupFirstPlay()) {
  52415. return;
  52416. }
  52417. if (this.tech_.ended()) {
  52418. this.tech_.setCurrentTime(0);
  52419. }
  52420. if (this.hasPlayed_) {
  52421. this.load();
  52422. }
  52423. var seekable = this.tech_.seekable(); // if the viewer has paused and we fell out of the live window,
  52424. // seek forward to the live point
  52425. if (this.tech_.duration() === Infinity) {
  52426. if (this.tech_.currentTime() < seekable.start(0)) {
  52427. return this.tech_.setCurrentTime(seekable.end(seekable.length - 1));
  52428. }
  52429. }
  52430. }
  52431. /**
  52432. * Seek to the latest media position if this is a live video and the
  52433. * player and video are loaded and initialized.
  52434. */
  52435. ;
  52436. _proto.setupFirstPlay = function setupFirstPlay() {
  52437. var _this6 = this;
  52438. var media = this.masterPlaylistLoader_.media(); // Check that everything is ready to begin buffering for the first call to play
  52439. // If 1) there is no active media
  52440. // 2) the player is paused
  52441. // 3) the first play has already been setup
  52442. // then exit early
  52443. if (!media || this.tech_.paused() || this.hasPlayed_) {
  52444. return false;
  52445. } // when the video is a live stream
  52446. if (!media.endList) {
  52447. var seekable = this.seekable();
  52448. if (!seekable.length) {
  52449. // without a seekable range, the player cannot seek to begin buffering at the live
  52450. // point
  52451. return false;
  52452. }
  52453. if (videojs.browser.IE_VERSION && this.tech_.readyState() === 0) {
  52454. // IE11 throws an InvalidStateError if you try to set currentTime while the
  52455. // readyState is 0, so it must be delayed until the tech fires loadedmetadata.
  52456. this.tech_.one('loadedmetadata', function () {
  52457. _this6.trigger('firstplay');
  52458. _this6.tech_.setCurrentTime(seekable.end(0));
  52459. _this6.hasPlayed_ = true;
  52460. });
  52461. return false;
  52462. } // trigger firstplay to inform the source handler to ignore the next seek event
  52463. this.trigger('firstplay'); // seek to the live point
  52464. this.tech_.setCurrentTime(seekable.end(0));
  52465. }
  52466. this.hasPlayed_ = true; // we can begin loading now that everything is ready
  52467. this.load();
  52468. return true;
  52469. }
  52470. /**
  52471. * handle the sourceopen event on the MediaSource
  52472. *
  52473. * @private
  52474. */
  52475. ;
  52476. _proto.handleSourceOpen_ = function handleSourceOpen_() {
  52477. // Only attempt to create the source buffer if none already exist.
  52478. // handleSourceOpen is also called when we are "re-opening" a source buffer
  52479. // after `endOfStream` has been called (in response to a seek for instance)
  52480. this.tryToCreateSourceBuffers_(); // if autoplay is enabled, begin playback. This is duplicative of
  52481. // code in video.js but is required because play() must be invoked
  52482. // *after* the media source has opened.
  52483. if (this.tech_.autoplay()) {
  52484. var playPromise = this.tech_.play(); // Catch/silence error when a pause interrupts a play request
  52485. // on browsers which return a promise
  52486. if (typeof playPromise !== 'undefined' && typeof playPromise.then === 'function') {
  52487. playPromise.then(null, function (e) {});
  52488. }
  52489. }
  52490. this.trigger('sourceopen');
  52491. }
  52492. /**
  52493. * handle the sourceended event on the MediaSource
  52494. *
  52495. * @private
  52496. */
  52497. ;
  52498. _proto.handleSourceEnded_ = function handleSourceEnded_() {
  52499. if (!this.inbandTextTracks_.metadataTrack_) {
  52500. return;
  52501. }
  52502. var cues = this.inbandTextTracks_.metadataTrack_.cues;
  52503. if (!cues || !cues.length) {
  52504. return;
  52505. }
  52506. var duration = this.duration();
  52507. cues[cues.length - 1].endTime = isNaN(duration) || Math.abs(duration) === Infinity ? Number.MAX_VALUE : duration;
  52508. }
  52509. /**
  52510. * handle the durationchange event on the MediaSource
  52511. *
  52512. * @private
  52513. */
  52514. ;
  52515. _proto.handleDurationChange_ = function handleDurationChange_() {
  52516. this.tech_.trigger('durationchange');
  52517. }
  52518. /**
  52519. * Calls endOfStream on the media source when all active stream types have called
  52520. * endOfStream
  52521. *
  52522. * @param {string} streamType
  52523. * Stream type of the segment loader that called endOfStream
  52524. * @private
  52525. */
  52526. ;
  52527. _proto.onEndOfStream = function onEndOfStream() {
  52528. var isEndOfStream = this.mainSegmentLoader_.ended_;
  52529. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  52530. var mainMediaInfo = this.mainSegmentLoader_.getCurrentMediaInfo_(); // if the audio playlist loader exists, then alternate audio is active
  52531. if (!mainMediaInfo || mainMediaInfo.hasVideo) {
  52532. // if we do not know if the main segment loader contains video yet or if we
  52533. // definitively know the main segment loader contains video, then we need to wait
  52534. // for both main and audio segment loaders to call endOfStream
  52535. isEndOfStream = isEndOfStream && this.audioSegmentLoader_.ended_;
  52536. } else {
  52537. // otherwise just rely on the audio loader
  52538. isEndOfStream = this.audioSegmentLoader_.ended_;
  52539. }
  52540. }
  52541. if (!isEndOfStream) {
  52542. return;
  52543. }
  52544. this.stopABRTimer_();
  52545. this.sourceUpdater_.endOfStream();
  52546. }
  52547. /**
  52548. * Check if a playlist has stopped being updated
  52549. *
  52550. * @param {Object} playlist the media playlist object
  52551. * @return {boolean} whether the playlist has stopped being updated or not
  52552. */
  52553. ;
  52554. _proto.stuckAtPlaylistEnd_ = function stuckAtPlaylistEnd_(playlist) {
  52555. var seekable = this.seekable();
  52556. if (!seekable.length) {
  52557. // playlist doesn't have enough information to determine whether we are stuck
  52558. return false;
  52559. }
  52560. var expired = this.syncController_.getExpiredTime(playlist, this.duration());
  52561. if (expired === null) {
  52562. return false;
  52563. } // does not use the safe live end to calculate playlist end, since we
  52564. // don't want to say we are stuck while there is still content
  52565. var absolutePlaylistEnd = Vhs$1.Playlist.playlistEnd(playlist, expired);
  52566. var currentTime = this.tech_.currentTime();
  52567. var buffered = this.tech_.buffered();
  52568. if (!buffered.length) {
  52569. // return true if the playhead reached the absolute end of the playlist
  52570. return absolutePlaylistEnd - currentTime <= SAFE_TIME_DELTA;
  52571. }
  52572. var bufferedEnd = buffered.end(buffered.length - 1); // return true if there is too little buffer left and buffer has reached absolute
  52573. // end of playlist
  52574. return bufferedEnd - currentTime <= SAFE_TIME_DELTA && absolutePlaylistEnd - bufferedEnd <= SAFE_TIME_DELTA;
  52575. }
  52576. /**
  52577. * Blacklists a playlist when an error occurs for a set amount of time
  52578. * making it unavailable for selection by the rendition selection algorithm
  52579. * and then forces a new playlist (rendition) selection.
  52580. *
  52581. * @param {Object=} error an optional error that may include the playlist
  52582. * to blacklist
  52583. * @param {number=} blacklistDuration an optional number of seconds to blacklist the
  52584. * playlist
  52585. */
  52586. ;
  52587. _proto.blacklistCurrentPlaylist = function blacklistCurrentPlaylist(error, blacklistDuration) {
  52588. if (error === void 0) {
  52589. error = {};
  52590. } // If the `error` was generated by the playlist loader, it will contain
  52591. // the playlist we were trying to load (but failed) and that should be
  52592. // blacklisted instead of the currently selected playlist which is likely
  52593. // out-of-date in this scenario
  52594. var currentPlaylist = error.playlist || this.masterPlaylistLoader_.media();
  52595. blacklistDuration = blacklistDuration || error.blacklistDuration || this.blacklistDuration; // If there is no current playlist, then an error occurred while we were
  52596. // trying to load the master OR while we were disposing of the tech
  52597. if (!currentPlaylist) {
  52598. this.error = error;
  52599. if (this.mediaSource.readyState !== 'open') {
  52600. this.trigger('error');
  52601. } else {
  52602. this.sourceUpdater_.endOfStream('network');
  52603. }
  52604. return;
  52605. }
  52606. currentPlaylist.playlistErrors_++;
  52607. var playlists = this.masterPlaylistLoader_.master.playlists;
  52608. var enabledPlaylists = playlists.filter(isEnabled);
  52609. var isFinalRendition = enabledPlaylists.length === 1 && enabledPlaylists[0] === currentPlaylist; // Don't blacklist the only playlist unless it was blacklisted
  52610. // forever
  52611. if (playlists.length === 1 && blacklistDuration !== Infinity) {
  52612. videojs.log.warn("Problem encountered with playlist " + currentPlaylist.id + ". " + 'Trying again since it is the only playlist.');
  52613. this.tech_.trigger('retryplaylist'); // if this is a final rendition, we should delay
  52614. return this.masterPlaylistLoader_.load(isFinalRendition);
  52615. }
  52616. if (isFinalRendition) {
  52617. // Since we're on the final non-blacklisted playlist, and we're about to blacklist
  52618. // it, instead of erring the player or retrying this playlist, clear out the current
  52619. // blacklist. This allows other playlists to be attempted in case any have been
  52620. // fixed.
  52621. var reincluded = false;
  52622. playlists.forEach(function (playlist) {
  52623. // skip current playlist which is about to be blacklisted
  52624. if (playlist === currentPlaylist) {
  52625. return;
  52626. }
  52627. var excludeUntil = playlist.excludeUntil; // a playlist cannot be reincluded if it wasn't excluded to begin with.
  52628. if (typeof excludeUntil !== 'undefined' && excludeUntil !== Infinity) {
  52629. reincluded = true;
  52630. delete playlist.excludeUntil;
  52631. }
  52632. });
  52633. if (reincluded) {
  52634. 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
  52635. // playlist. This is needed for users relying on the retryplaylist event to catch a
  52636. // case where the player might be stuck and looping through "dead" playlists.
  52637. this.tech_.trigger('retryplaylist');
  52638. }
  52639. } // Blacklist this playlist
  52640. var excludeUntil;
  52641. if (currentPlaylist.playlistErrors_ > this.maxPlaylistRetries) {
  52642. excludeUntil = Infinity;
  52643. } else {
  52644. excludeUntil = Date.now() + blacklistDuration * 1000;
  52645. }
  52646. currentPlaylist.excludeUntil = excludeUntil;
  52647. if (error.reason) {
  52648. currentPlaylist.lastExcludeReason_ = error.reason;
  52649. }
  52650. this.tech_.trigger('blacklistplaylist');
  52651. this.tech_.trigger({
  52652. type: 'usage',
  52653. name: 'vhs-rendition-blacklisted'
  52654. });
  52655. this.tech_.trigger({
  52656. type: 'usage',
  52657. name: 'hls-rendition-blacklisted'
  52658. }); // TODO: should we select a new playlist if this blacklist wasn't for the currentPlaylist?
  52659. // Would be something like media().id !=== currentPlaylist.id and we would need something
  52660. // like `pendingMedia` in playlist loaders to check against that too. This will prevent us
  52661. // from loading a new playlist on any blacklist.
  52662. // Select a new playlist
  52663. var nextPlaylist = this.selectPlaylist();
  52664. if (!nextPlaylist) {
  52665. this.error = 'Playback cannot continue. No available working or supported playlists.';
  52666. this.trigger('error');
  52667. return;
  52668. }
  52669. var logFn = error.internal ? this.logger_ : videojs.log.warn;
  52670. var errorMessage = error.message ? ' ' + error.message : '';
  52671. logFn((error.internal ? 'Internal problem' : 'Problem') + " encountered with playlist " + currentPlaylist.id + "." + (errorMessage + " Switching to playlist " + nextPlaylist.id + ".")); // if audio group changed reset audio loaders
  52672. if (nextPlaylist.attributes.AUDIO !== currentPlaylist.attributes.AUDIO) {
  52673. this.delegateLoaders_('audio', ['abort', 'pause']);
  52674. } // if subtitle group changed reset subtitle loaders
  52675. if (nextPlaylist.attributes.SUBTITLES !== currentPlaylist.attributes.SUBTITLES) {
  52676. this.delegateLoaders_('subtitle', ['abort', 'pause']);
  52677. }
  52678. this.delegateLoaders_('main', ['abort', 'pause']);
  52679. var delayDuration = nextPlaylist.targetDuration / 2 * 1000 || 5 * 1000;
  52680. 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
  52681. return this.switchMedia_(nextPlaylist, 'exclude', isFinalRendition || shouldDelay);
  52682. }
  52683. /**
  52684. * Pause all segment/playlist loaders
  52685. */
  52686. ;
  52687. _proto.pauseLoading = function pauseLoading() {
  52688. this.delegateLoaders_('all', ['abort', 'pause']);
  52689. this.stopABRTimer_();
  52690. }
  52691. /**
  52692. * Call a set of functions in order on playlist loaders, segment loaders,
  52693. * or both types of loaders.
  52694. *
  52695. * @param {string} filter
  52696. * Filter loaders that should call fnNames using a string. Can be:
  52697. * * all - run on all loaders
  52698. * * audio - run on all audio loaders
  52699. * * subtitle - run on all subtitle loaders
  52700. * * main - run on the main/master loaders
  52701. *
  52702. * @param {Array|string} fnNames
  52703. * A string or array of function names to call.
  52704. */
  52705. ;
  52706. _proto.delegateLoaders_ = function delegateLoaders_(filter, fnNames) {
  52707. var _this7 = this;
  52708. var loaders = [];
  52709. var dontFilterPlaylist = filter === 'all';
  52710. if (dontFilterPlaylist || filter === 'main') {
  52711. loaders.push(this.masterPlaylistLoader_);
  52712. }
  52713. var mediaTypes = [];
  52714. if (dontFilterPlaylist || filter === 'audio') {
  52715. mediaTypes.push('AUDIO');
  52716. }
  52717. if (dontFilterPlaylist || filter === 'subtitle') {
  52718. mediaTypes.push('CLOSED-CAPTIONS');
  52719. mediaTypes.push('SUBTITLES');
  52720. }
  52721. mediaTypes.forEach(function (mediaType) {
  52722. var loader = _this7.mediaTypes_[mediaType] && _this7.mediaTypes_[mediaType].activePlaylistLoader;
  52723. if (loader) {
  52724. loaders.push(loader);
  52725. }
  52726. });
  52727. ['main', 'audio', 'subtitle'].forEach(function (name) {
  52728. var loader = _this7[name + "SegmentLoader_"];
  52729. if (loader && (filter === name || filter === 'all')) {
  52730. loaders.push(loader);
  52731. }
  52732. });
  52733. loaders.forEach(function (loader) {
  52734. return fnNames.forEach(function (fnName) {
  52735. if (typeof loader[fnName] === 'function') {
  52736. loader[fnName]();
  52737. }
  52738. });
  52739. });
  52740. }
  52741. /**
  52742. * set the current time on all segment loaders
  52743. *
  52744. * @param {TimeRange} currentTime the current time to set
  52745. * @return {TimeRange} the current time
  52746. */
  52747. ;
  52748. _proto.setCurrentTime = function setCurrentTime(currentTime) {
  52749. var buffered = findRange(this.tech_.buffered(), currentTime);
  52750. if (!(this.masterPlaylistLoader_ && this.masterPlaylistLoader_.media())) {
  52751. // return immediately if the metadata is not ready yet
  52752. return 0;
  52753. } // it's clearly an edge-case but don't thrown an error if asked to
  52754. // seek within an empty playlist
  52755. if (!this.masterPlaylistLoader_.media().segments) {
  52756. return 0;
  52757. } // if the seek location is already buffered, continue buffering as usual
  52758. if (buffered && buffered.length) {
  52759. return currentTime;
  52760. } // cancel outstanding requests so we begin buffering at the new
  52761. // location
  52762. this.mainSegmentLoader_.resetEverything();
  52763. this.mainSegmentLoader_.abort();
  52764. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  52765. this.audioSegmentLoader_.resetEverything();
  52766. this.audioSegmentLoader_.abort();
  52767. }
  52768. if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
  52769. this.subtitleSegmentLoader_.resetEverything();
  52770. this.subtitleSegmentLoader_.abort();
  52771. } // start segment loader loading in case they are paused
  52772. this.load();
  52773. }
  52774. /**
  52775. * get the current duration
  52776. *
  52777. * @return {TimeRange} the duration
  52778. */
  52779. ;
  52780. _proto.duration = function duration() {
  52781. if (!this.masterPlaylistLoader_) {
  52782. return 0;
  52783. }
  52784. var media = this.masterPlaylistLoader_.media();
  52785. if (!media) {
  52786. // no playlists loaded yet, so can't determine a duration
  52787. return 0;
  52788. } // Don't rely on the media source for duration in the case of a live playlist since
  52789. // setting the native MediaSource's duration to infinity ends up with consequences to
  52790. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  52791. //
  52792. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  52793. // however, few browsers have support for setLiveSeekableRange()
  52794. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  52795. //
  52796. // Until a time when the duration of the media source can be set to infinity, and a
  52797. // seekable range specified across browsers, just return Infinity.
  52798. if (!media.endList) {
  52799. return Infinity;
  52800. } // Since this is a VOD video, it is safe to rely on the media source's duration (if
  52801. // available). If it's not available, fall back to a playlist-calculated estimate.
  52802. if (this.mediaSource) {
  52803. return this.mediaSource.duration;
  52804. }
  52805. return Vhs$1.Playlist.duration(media);
  52806. }
  52807. /**
  52808. * check the seekable range
  52809. *
  52810. * @return {TimeRange} the seekable range
  52811. */
  52812. ;
  52813. _proto.seekable = function seekable() {
  52814. return this.seekable_;
  52815. };
  52816. _proto.onSyncInfoUpdate_ = function onSyncInfoUpdate_() {
  52817. var audioSeekable; // TODO check for creation of both source buffers before updating seekable
  52818. //
  52819. // A fix was made to this function where a check for
  52820. // this.sourceUpdater_.hasCreatedSourceBuffers
  52821. // was added to ensure that both source buffers were created before seekable was
  52822. // updated. However, it originally had a bug where it was checking for a true and
  52823. // returning early instead of checking for false. Setting it to check for false to
  52824. // return early though created other issues. A call to play() would check for seekable
  52825. // end without verifying that a seekable range was present. In addition, even checking
  52826. // for that didn't solve some issues, as handleFirstPlay is sometimes worked around
  52827. // due to a media update calling load on the segment loaders, skipping a seek to live,
  52828. // thereby starting live streams at the beginning of the stream rather than at the end.
  52829. //
  52830. // This conditional should be fixed to wait for the creation of two source buffers at
  52831. // the same time as the other sections of code are fixed to properly seek to live and
  52832. // not throw an error due to checking for a seekable end when no seekable range exists.
  52833. //
  52834. // For now, fall back to the older behavior, with the understanding that the seekable
  52835. // range may not be completely correct, leading to a suboptimal initial live point.
  52836. if (!this.masterPlaylistLoader_) {
  52837. return;
  52838. }
  52839. var media = this.masterPlaylistLoader_.media();
  52840. if (!media) {
  52841. return;
  52842. }
  52843. var expired = this.syncController_.getExpiredTime(media, this.duration());
  52844. if (expired === null) {
  52845. // not enough information to update seekable
  52846. return;
  52847. }
  52848. var master = this.masterPlaylistLoader_.master;
  52849. var mainSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(master, media));
  52850. if (mainSeekable.length === 0) {
  52851. return;
  52852. }
  52853. if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
  52854. media = this.mediaTypes_.AUDIO.activePlaylistLoader.media();
  52855. expired = this.syncController_.getExpiredTime(media, this.duration());
  52856. if (expired === null) {
  52857. return;
  52858. }
  52859. audioSeekable = Vhs$1.Playlist.seekable(media, expired, Vhs$1.Playlist.liveEdgeDelay(master, media));
  52860. if (audioSeekable.length === 0) {
  52861. return;
  52862. }
  52863. }
  52864. var oldEnd;
  52865. var oldStart;
  52866. if (this.seekable_ && this.seekable_.length) {
  52867. oldEnd = this.seekable_.end(0);
  52868. oldStart = this.seekable_.start(0);
  52869. }
  52870. if (!audioSeekable) {
  52871. // seekable has been calculated based on buffering video data so it
  52872. // can be returned directly
  52873. this.seekable_ = mainSeekable;
  52874. } else if (audioSeekable.start(0) > mainSeekable.end(0) || mainSeekable.start(0) > audioSeekable.end(0)) {
  52875. // seekables are pretty far off, rely on main
  52876. this.seekable_ = mainSeekable;
  52877. } else {
  52878. 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)]]);
  52879. } // seekable is the same as last time
  52880. if (this.seekable_ && this.seekable_.length) {
  52881. if (this.seekable_.end(0) === oldEnd && this.seekable_.start(0) === oldStart) {
  52882. return;
  52883. }
  52884. }
  52885. this.logger_("seekable updated [" + printableRange(this.seekable_) + "]");
  52886. this.tech_.trigger('seekablechanged');
  52887. }
  52888. /**
  52889. * Update the player duration
  52890. */
  52891. ;
  52892. _proto.updateDuration = function updateDuration(isLive) {
  52893. if (this.updateDuration_) {
  52894. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  52895. this.updateDuration_ = null;
  52896. }
  52897. if (this.mediaSource.readyState !== 'open') {
  52898. this.updateDuration_ = this.updateDuration.bind(this, isLive);
  52899. this.mediaSource.addEventListener('sourceopen', this.updateDuration_);
  52900. return;
  52901. }
  52902. if (isLive) {
  52903. var seekable = this.seekable();
  52904. if (!seekable.length) {
  52905. return;
  52906. } // Even in the case of a live playlist, the native MediaSource's duration should not
  52907. // be set to Infinity (even though this would be expected for a live playlist), since
  52908. // setting the native MediaSource's duration to infinity ends up with consequences to
  52909. // seekable behavior. See https://github.com/w3c/media-source/issues/5 for details.
  52910. //
  52911. // This is resolved in the spec by https://github.com/w3c/media-source/pull/92,
  52912. // however, few browsers have support for setLiveSeekableRange()
  52913. // https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/setLiveSeekableRange
  52914. //
  52915. // Until a time when the duration of the media source can be set to infinity, and a
  52916. // seekable range specified across browsers, the duration should be greater than or
  52917. // equal to the last possible seekable value.
  52918. // MediaSource duration starts as NaN
  52919. // It is possible (and probable) that this case will never be reached for many
  52920. // sources, since the MediaSource reports duration as the highest value without
  52921. // accounting for timestamp offset. For example, if the timestamp offset is -100 and
  52922. // we buffered times 0 to 100 with real times of 100 to 200, even though current
  52923. // time will be between 0 and 100, the native media source may report the duration
  52924. // as 200. However, since we report duration separate from the media source (as
  52925. // Infinity), and as long as the native media source duration value is greater than
  52926. // our reported seekable range, seeks will work as expected. The large number as
  52927. // duration for live is actually a strategy used by some players to work around the
  52928. // issue of live seekable ranges cited above.
  52929. if (isNaN(this.mediaSource.duration) || this.mediaSource.duration < seekable.end(seekable.length - 1)) {
  52930. this.sourceUpdater_.setDuration(seekable.end(seekable.length - 1));
  52931. }
  52932. return;
  52933. }
  52934. var buffered = this.tech_.buffered();
  52935. var duration = Vhs$1.Playlist.duration(this.masterPlaylistLoader_.media());
  52936. if (buffered.length > 0) {
  52937. duration = Math.max(duration, buffered.end(buffered.length - 1));
  52938. }
  52939. if (this.mediaSource.duration !== duration) {
  52940. this.sourceUpdater_.setDuration(duration);
  52941. }
  52942. }
  52943. /**
  52944. * dispose of the MasterPlaylistController and everything
  52945. * that it controls
  52946. */
  52947. ;
  52948. _proto.dispose = function dispose() {
  52949. var _this8 = this;
  52950. this.trigger('dispose');
  52951. this.decrypter_.terminate();
  52952. this.masterPlaylistLoader_.dispose();
  52953. this.mainSegmentLoader_.dispose();
  52954. if (this.loadOnPlay_) {
  52955. this.tech_.off('play', this.loadOnPlay_);
  52956. }
  52957. ['AUDIO', 'SUBTITLES'].forEach(function (type) {
  52958. var groups = _this8.mediaTypes_[type].groups;
  52959. for (var id in groups) {
  52960. groups[id].forEach(function (group) {
  52961. if (group.playlistLoader) {
  52962. group.playlistLoader.dispose();
  52963. }
  52964. });
  52965. }
  52966. });
  52967. this.audioSegmentLoader_.dispose();
  52968. this.subtitleSegmentLoader_.dispose();
  52969. this.sourceUpdater_.dispose();
  52970. this.timelineChangeController_.dispose();
  52971. this.stopABRTimer_();
  52972. if (this.updateDuration_) {
  52973. this.mediaSource.removeEventListener('sourceopen', this.updateDuration_);
  52974. }
  52975. this.mediaSource.removeEventListener('durationchange', this.handleDurationChange_); // load the media source into the player
  52976. this.mediaSource.removeEventListener('sourceopen', this.handleSourceOpen_);
  52977. this.mediaSource.removeEventListener('sourceended', this.handleSourceEnded_);
  52978. this.off();
  52979. }
  52980. /**
  52981. * return the master playlist object if we have one
  52982. *
  52983. * @return {Object} the master playlist object that we parsed
  52984. */
  52985. ;
  52986. _proto.master = function master() {
  52987. return this.masterPlaylistLoader_.master;
  52988. }
  52989. /**
  52990. * return the currently selected playlist
  52991. *
  52992. * @return {Object} the currently selected playlist object that we parsed
  52993. */
  52994. ;
  52995. _proto.media = function media() {
  52996. // playlist loader will not return media if it has not been fully loaded
  52997. return this.masterPlaylistLoader_.media() || this.initialMedia_;
  52998. };
  52999. _proto.areMediaTypesKnown_ = function areMediaTypesKnown_() {
  53000. var usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  53001. var hasMainMediaInfo = !!this.mainSegmentLoader_.getCurrentMediaInfo_(); // if we are not using an audio loader, then we have audio media info
  53002. // otherwise check on the segment loader.
  53003. var hasAudioMediaInfo = !usingAudioLoader ? true : !!this.audioSegmentLoader_.getCurrentMediaInfo_(); // one or both loaders has not loaded sufficently to get codecs
  53004. if (!hasMainMediaInfo || !hasAudioMediaInfo) {
  53005. return false;
  53006. }
  53007. return true;
  53008. };
  53009. _proto.getCodecsOrExclude_ = function getCodecsOrExclude_() {
  53010. var _this9 = this;
  53011. var media = {
  53012. main: this.mainSegmentLoader_.getCurrentMediaInfo_() || {},
  53013. audio: this.audioSegmentLoader_.getCurrentMediaInfo_() || {}
  53014. };
  53015. var playlist = this.mainSegmentLoader_.getPendingSegmentPlaylist() || this.media(); // set "main" media equal to video
  53016. media.video = media.main;
  53017. var playlistCodecs = codecsForPlaylist(this.master(), playlist);
  53018. var codecs = {};
  53019. var usingAudioLoader = !!this.mediaTypes_.AUDIO.activePlaylistLoader;
  53020. if (media.main.hasVideo) {
  53021. codecs.video = playlistCodecs.video || media.main.videoCodec || DEFAULT_VIDEO_CODEC;
  53022. }
  53023. if (media.main.isMuxed) {
  53024. codecs.video += "," + (playlistCodecs.audio || media.main.audioCodec || DEFAULT_AUDIO_CODEC);
  53025. }
  53026. if (media.main.hasAudio && !media.main.isMuxed || media.audio.hasAudio || usingAudioLoader) {
  53027. codecs.audio = playlistCodecs.audio || media.main.audioCodec || media.audio.audioCodec || DEFAULT_AUDIO_CODEC; // set audio isFmp4 so we use the correct "supports" function below
  53028. media.audio.isFmp4 = media.main.hasAudio && !media.main.isMuxed ? media.main.isFmp4 : media.audio.isFmp4;
  53029. } // no codecs, no playback.
  53030. if (!codecs.audio && !codecs.video) {
  53031. this.blacklistCurrentPlaylist({
  53032. playlist: playlist,
  53033. message: 'Could not determine codecs for playlist.',
  53034. blacklistDuration: Infinity
  53035. });
  53036. return;
  53037. } // fmp4 relies on browser support, while ts relies on muxer support
  53038. var supportFunction = function supportFunction(isFmp4, codec) {
  53039. return isFmp4 ? browserSupportsCodec(codec) : muxerSupportsCodec(codec);
  53040. };
  53041. var unsupportedCodecs = {};
  53042. var unsupportedAudio;
  53043. ['video', 'audio'].forEach(function (type) {
  53044. if (codecs.hasOwnProperty(type) && !supportFunction(media[type].isFmp4, codecs[type])) {
  53045. var supporter = media[type].isFmp4 ? 'browser' : 'muxer';
  53046. unsupportedCodecs[supporter] = unsupportedCodecs[supporter] || [];
  53047. unsupportedCodecs[supporter].push(codecs[type]);
  53048. if (type === 'audio') {
  53049. unsupportedAudio = supporter;
  53050. }
  53051. }
  53052. });
  53053. if (usingAudioLoader && unsupportedAudio && playlist.attributes.AUDIO) {
  53054. var audioGroup = playlist.attributes.AUDIO;
  53055. this.master().playlists.forEach(function (variant) {
  53056. var variantAudioGroup = variant.attributes && variant.attributes.AUDIO;
  53057. if (variantAudioGroup === audioGroup && variant !== playlist) {
  53058. variant.excludeUntil = Infinity;
  53059. }
  53060. });
  53061. this.logger_("excluding audio group " + audioGroup + " as " + unsupportedAudio + " does not support codec(s): \"" + codecs.audio + "\"");
  53062. } // if we have any unsupported codecs blacklist this playlist.
  53063. if (Object.keys(unsupportedCodecs).length) {
  53064. var message = Object.keys(unsupportedCodecs).reduce(function (acc, supporter) {
  53065. if (acc) {
  53066. acc += ', ';
  53067. }
  53068. acc += supporter + " does not support codec(s): \"" + unsupportedCodecs[supporter].join(',') + "\"";
  53069. return acc;
  53070. }, '') + '.';
  53071. this.blacklistCurrentPlaylist({
  53072. playlist: playlist,
  53073. internal: true,
  53074. message: message,
  53075. blacklistDuration: Infinity
  53076. });
  53077. return;
  53078. } // check if codec switching is happening
  53079. if (this.sourceUpdater_.hasCreatedSourceBuffers() && !this.sourceUpdater_.canChangeType()) {
  53080. var switchMessages = [];
  53081. ['video', 'audio'].forEach(function (type) {
  53082. var newCodec = (parseCodecs(_this9.sourceUpdater_.codecs[type] || '')[0] || {}).type;
  53083. var oldCodec = (parseCodecs(codecs[type] || '')[0] || {}).type;
  53084. if (newCodec && oldCodec && newCodec.toLowerCase() !== oldCodec.toLowerCase()) {
  53085. switchMessages.push("\"" + _this9.sourceUpdater_.codecs[type] + "\" -> \"" + codecs[type] + "\"");
  53086. }
  53087. });
  53088. if (switchMessages.length) {
  53089. this.blacklistCurrentPlaylist({
  53090. playlist: playlist,
  53091. message: "Codec switching not supported: " + switchMessages.join(', ') + ".",
  53092. blacklistDuration: Infinity,
  53093. internal: true
  53094. });
  53095. return;
  53096. }
  53097. } // TODO: when using the muxer shouldn't we just return
  53098. // the codecs that the muxer outputs?
  53099. return codecs;
  53100. }
  53101. /**
  53102. * Create source buffers and exlude any incompatible renditions.
  53103. *
  53104. * @private
  53105. */
  53106. ;
  53107. _proto.tryToCreateSourceBuffers_ = function tryToCreateSourceBuffers_() {
  53108. // media source is not ready yet or sourceBuffers are already
  53109. // created.
  53110. if (this.mediaSource.readyState !== 'open' || this.sourceUpdater_.hasCreatedSourceBuffers()) {
  53111. return;
  53112. }
  53113. if (!this.areMediaTypesKnown_()) {
  53114. return;
  53115. }
  53116. var codecs = this.getCodecsOrExclude_(); // no codecs means that the playlist was excluded
  53117. if (!codecs) {
  53118. return;
  53119. }
  53120. this.sourceUpdater_.createSourceBuffers(codecs);
  53121. var codecString = [codecs.video, codecs.audio].filter(Boolean).join(',');
  53122. this.excludeIncompatibleVariants_(codecString);
  53123. }
  53124. /**
  53125. * Excludes playlists with codecs that are unsupported by the muxer and browser.
  53126. */
  53127. ;
  53128. _proto.excludeUnsupportedVariants_ = function excludeUnsupportedVariants_() {
  53129. var _this10 = this;
  53130. var playlists = this.master().playlists;
  53131. var ids = []; // TODO: why don't we have a property to loop through all
  53132. // playlist? Why did we ever mix indexes and keys?
  53133. Object.keys(playlists).forEach(function (key) {
  53134. var variant = playlists[key]; // check if we already processed this playlist.
  53135. if (ids.indexOf(variant.id) !== -1) {
  53136. return;
  53137. }
  53138. ids.push(variant.id);
  53139. var codecs = codecsForPlaylist(_this10.master, variant);
  53140. var unsupported = [];
  53141. if (codecs.audio && !muxerSupportsCodec(codecs.audio) && !browserSupportsCodec(codecs.audio)) {
  53142. unsupported.push("audio codec " + codecs.audio);
  53143. }
  53144. if (codecs.video && !muxerSupportsCodec(codecs.video) && !browserSupportsCodec(codecs.video)) {
  53145. unsupported.push("video codec " + codecs.video);
  53146. }
  53147. if (codecs.text && codecs.text === 'stpp.ttml.im1t') {
  53148. unsupported.push("text codec " + codecs.text);
  53149. }
  53150. if (unsupported.length) {
  53151. variant.excludeUntil = Infinity;
  53152. _this10.logger_("excluding " + variant.id + " for unsupported: " + unsupported.join(', '));
  53153. }
  53154. });
  53155. }
  53156. /**
  53157. * Blacklist playlists that are known to be codec or
  53158. * stream-incompatible with the SourceBuffer configuration. For
  53159. * instance, Media Source Extensions would cause the video element to
  53160. * stall waiting for video data if you switched from a variant with
  53161. * video and audio to an audio-only one.
  53162. *
  53163. * @param {Object} media a media playlist compatible with the current
  53164. * set of SourceBuffers. Variants in the current master playlist that
  53165. * do not appear to have compatible codec or stream configurations
  53166. * will be excluded from the default playlist selection algorithm
  53167. * indefinitely.
  53168. * @private
  53169. */
  53170. ;
  53171. _proto.excludeIncompatibleVariants_ = function excludeIncompatibleVariants_(codecString) {
  53172. var _this11 = this;
  53173. var ids = [];
  53174. var playlists = this.master().playlists;
  53175. var codecs = unwrapCodecList(parseCodecs(codecString));
  53176. var codecCount_ = codecCount(codecs);
  53177. var videoDetails = codecs.video && parseCodecs(codecs.video)[0] || null;
  53178. var audioDetails = codecs.audio && parseCodecs(codecs.audio)[0] || null;
  53179. Object.keys(playlists).forEach(function (key) {
  53180. var variant = playlists[key]; // check if we already processed this playlist.
  53181. // or it if it is already excluded forever.
  53182. if (ids.indexOf(variant.id) !== -1 || variant.excludeUntil === Infinity) {
  53183. return;
  53184. }
  53185. ids.push(variant.id);
  53186. var blacklistReasons = []; // get codecs from the playlist for this variant
  53187. var variantCodecs = codecsForPlaylist(_this11.masterPlaylistLoader_.master, variant);
  53188. var variantCodecCount = codecCount(variantCodecs); // if no codecs are listed, we cannot determine that this
  53189. // variant is incompatible. Wait for mux.js to probe
  53190. if (!variantCodecs.audio && !variantCodecs.video) {
  53191. return;
  53192. } // TODO: we can support this by removing the
  53193. // old media source and creating a new one, but it will take some work.
  53194. // The number of streams cannot change
  53195. if (variantCodecCount !== codecCount_) {
  53196. blacklistReasons.push("codec count \"" + variantCodecCount + "\" !== \"" + codecCount_ + "\"");
  53197. } // only exclude playlists by codec change, if codecs cannot switch
  53198. // during playback.
  53199. if (!_this11.sourceUpdater_.canChangeType()) {
  53200. var variantVideoDetails = variantCodecs.video && parseCodecs(variantCodecs.video)[0] || null;
  53201. var variantAudioDetails = variantCodecs.audio && parseCodecs(variantCodecs.audio)[0] || null; // the video codec cannot change
  53202. if (variantVideoDetails && videoDetails && variantVideoDetails.type.toLowerCase() !== videoDetails.type.toLowerCase()) {
  53203. blacklistReasons.push("video codec \"" + variantVideoDetails.type + "\" !== \"" + videoDetails.type + "\"");
  53204. } // the audio codec cannot change
  53205. if (variantAudioDetails && audioDetails && variantAudioDetails.type.toLowerCase() !== audioDetails.type.toLowerCase()) {
  53206. blacklistReasons.push("audio codec \"" + variantAudioDetails.type + "\" !== \"" + audioDetails.type + "\"");
  53207. }
  53208. }
  53209. if (blacklistReasons.length) {
  53210. variant.excludeUntil = Infinity;
  53211. _this11.logger_("blacklisting " + variant.id + ": " + blacklistReasons.join(' && '));
  53212. }
  53213. });
  53214. };
  53215. _proto.updateAdCues_ = function updateAdCues_(media) {
  53216. var offset = 0;
  53217. var seekable = this.seekable();
  53218. if (seekable.length) {
  53219. offset = seekable.start(0);
  53220. }
  53221. updateAdCues(media, this.cueTagsTrack_, offset);
  53222. }
  53223. /**
  53224. * Calculates the desired forward buffer length based on current time
  53225. *
  53226. * @return {number} Desired forward buffer length in seconds
  53227. */
  53228. ;
  53229. _proto.goalBufferLength = function goalBufferLength() {
  53230. var currentTime = this.tech_.currentTime();
  53231. var initial = Config.GOAL_BUFFER_LENGTH;
  53232. var rate = Config.GOAL_BUFFER_LENGTH_RATE;
  53233. var max = Math.max(initial, Config.MAX_GOAL_BUFFER_LENGTH);
  53234. return Math.min(initial + currentTime * rate, max);
  53235. }
  53236. /**
  53237. * Calculates the desired buffer low water line based on current time
  53238. *
  53239. * @return {number} Desired buffer low water line in seconds
  53240. */
  53241. ;
  53242. _proto.bufferLowWaterLine = function bufferLowWaterLine() {
  53243. var currentTime = this.tech_.currentTime();
  53244. var initial = Config.BUFFER_LOW_WATER_LINE;
  53245. var rate = Config.BUFFER_LOW_WATER_LINE_RATE;
  53246. var max = Math.max(initial, Config.MAX_BUFFER_LOW_WATER_LINE);
  53247. var newMax = Math.max(initial, Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE);
  53248. return Math.min(initial + currentTime * rate, this.experimentalBufferBasedABR ? newMax : max);
  53249. };
  53250. _proto.bufferHighWaterLine = function bufferHighWaterLine() {
  53251. return Config.BUFFER_HIGH_WATER_LINE;
  53252. };
  53253. return MasterPlaylistController;
  53254. }(videojs.EventTarget);
  53255. /**
  53256. * Returns a function that acts as the Enable/disable playlist function.
  53257. *
  53258. * @param {PlaylistLoader} loader - The master playlist loader
  53259. * @param {string} playlistID - id of the playlist
  53260. * @param {Function} changePlaylistFn - A function to be called after a
  53261. * playlist's enabled-state has been changed. Will NOT be called if a
  53262. * playlist's enabled-state is unchanged
  53263. * @param {boolean=} enable - Value to set the playlist enabled-state to
  53264. * or if undefined returns the current enabled-state for the playlist
  53265. * @return {Function} Function for setting/getting enabled
  53266. */
  53267. var enableFunction = function enableFunction(loader, playlistID, changePlaylistFn) {
  53268. return function (enable) {
  53269. var playlist = loader.master.playlists[playlistID];
  53270. var incompatible = isIncompatible(playlist);
  53271. var currentlyEnabled = isEnabled(playlist);
  53272. if (typeof enable === 'undefined') {
  53273. return currentlyEnabled;
  53274. }
  53275. if (enable) {
  53276. delete playlist.disabled;
  53277. } else {
  53278. playlist.disabled = true;
  53279. }
  53280. if (enable !== currentlyEnabled && !incompatible) {
  53281. // Ensure the outside world knows about our changes
  53282. changePlaylistFn();
  53283. if (enable) {
  53284. loader.trigger('renditionenabled');
  53285. } else {
  53286. loader.trigger('renditiondisabled');
  53287. }
  53288. }
  53289. return enable;
  53290. };
  53291. };
  53292. /**
  53293. * The representation object encapsulates the publicly visible information
  53294. * in a media playlist along with a setter/getter-type function (enabled)
  53295. * for changing the enabled-state of a particular playlist entry
  53296. *
  53297. * @class Representation
  53298. */
  53299. var Representation = function Representation(vhsHandler, playlist, id) {
  53300. var mpc = vhsHandler.masterPlaylistController_,
  53301. smoothQualityChange = vhsHandler.options_.smoothQualityChange; // Get a reference to a bound version of the quality change function
  53302. var changeType = smoothQualityChange ? 'smooth' : 'fast';
  53303. var qualityChangeFunction = mpc[changeType + "QualityChange_"].bind(mpc); // some playlist attributes are optional
  53304. if (playlist.attributes) {
  53305. var resolution = playlist.attributes.RESOLUTION;
  53306. this.width = resolution && resolution.width;
  53307. this.height = resolution && resolution.height;
  53308. this.bandwidth = playlist.attributes.BANDWIDTH;
  53309. this.frameRate = playlist.attributes['FRAME-RATE'];
  53310. }
  53311. this.codecs = codecsForPlaylist(mpc.master(), playlist);
  53312. this.playlist = playlist; // The id is simply the ordinality of the media playlist
  53313. // within the master playlist
  53314. this.id = id; // Partially-apply the enableFunction to create a playlist-
  53315. // specific variant
  53316. this.enabled = enableFunction(vhsHandler.playlists, playlist.id, qualityChangeFunction);
  53317. };
  53318. /**
  53319. * A mixin function that adds the `representations` api to an instance
  53320. * of the VhsHandler class
  53321. *
  53322. * @param {VhsHandler} vhsHandler - An instance of VhsHandler to add the
  53323. * representation API into
  53324. */
  53325. var renditionSelectionMixin = function renditionSelectionMixin(vhsHandler) {
  53326. // Add a single API-specific function to the VhsHandler instance
  53327. vhsHandler.representations = function () {
  53328. var master = vhsHandler.masterPlaylistController_.master();
  53329. var playlists = isAudioOnly(master) ? vhsHandler.masterPlaylistController_.getAudioTrackPlaylists_() : master.playlists;
  53330. if (!playlists) {
  53331. return [];
  53332. }
  53333. return playlists.filter(function (media) {
  53334. return !isIncompatible(media);
  53335. }).map(function (e, i) {
  53336. return new Representation(vhsHandler, e, e.id);
  53337. });
  53338. };
  53339. };
  53340. /**
  53341. * @file playback-watcher.js
  53342. *
  53343. * Playback starts, and now my watch begins. It shall not end until my death. I shall
  53344. * take no wait, hold no uncleared timeouts, father no bad seeks. I shall wear no crowns
  53345. * and win no glory. I shall live and die at my post. I am the corrector of the underflow.
  53346. * I am the watcher of gaps. I am the shield that guards the realms of seekable. I pledge
  53347. * my life and honor to the Playback Watch, for this Player and all the Players to come.
  53348. */
  53349. var timerCancelEvents = ['seeking', 'seeked', 'pause', 'playing', 'error'];
  53350. /**
  53351. * @class PlaybackWatcher
  53352. */
  53353. var PlaybackWatcher = /*#__PURE__*/function () {
  53354. /**
  53355. * Represents an PlaybackWatcher object.
  53356. *
  53357. * @class
  53358. * @param {Object} options an object that includes the tech and settings
  53359. */
  53360. function PlaybackWatcher(options) {
  53361. var _this = this;
  53362. this.masterPlaylistController_ = options.masterPlaylistController;
  53363. this.tech_ = options.tech;
  53364. this.seekable = options.seekable;
  53365. this.allowSeeksWithinUnsafeLiveWindow = options.allowSeeksWithinUnsafeLiveWindow;
  53366. this.liveRangeSafeTimeDelta = options.liveRangeSafeTimeDelta;
  53367. this.media = options.media;
  53368. this.consecutiveUpdates = 0;
  53369. this.lastRecordedTime = null;
  53370. this.timer_ = null;
  53371. this.checkCurrentTimeTimeout_ = null;
  53372. this.logger_ = logger('PlaybackWatcher');
  53373. this.logger_('initialize');
  53374. var playHandler = function playHandler() {
  53375. return _this.monitorCurrentTime_();
  53376. };
  53377. var canPlayHandler = function canPlayHandler() {
  53378. return _this.monitorCurrentTime_();
  53379. };
  53380. var waitingHandler = function waitingHandler() {
  53381. return _this.techWaiting_();
  53382. };
  53383. var cancelTimerHandler = function cancelTimerHandler() {
  53384. return _this.cancelTimer_();
  53385. };
  53386. var mpc = this.masterPlaylistController_;
  53387. var loaderTypes = ['main', 'subtitle', 'audio'];
  53388. var loaderChecks = {};
  53389. loaderTypes.forEach(function (type) {
  53390. loaderChecks[type] = {
  53391. reset: function reset() {
  53392. return _this.resetSegmentDownloads_(type);
  53393. },
  53394. updateend: function updateend() {
  53395. return _this.checkSegmentDownloads_(type);
  53396. }
  53397. };
  53398. mpc[type + "SegmentLoader_"].on('appendsdone', loaderChecks[type].updateend); // If a rendition switch happens during a playback stall where the buffer
  53399. // isn't changing we want to reset. We cannot assume that the new rendition
  53400. // will also be stalled, until after new appends.
  53401. mpc[type + "SegmentLoader_"].on('playlistupdate', loaderChecks[type].reset); // Playback stalls should not be detected right after seeking.
  53402. // This prevents one segment playlists (single vtt or single segment content)
  53403. // from being detected as stalling. As the buffer will not change in those cases, since
  53404. // the buffer is the entire video duration.
  53405. _this.tech_.on(['seeked', 'seeking'], loaderChecks[type].reset);
  53406. });
  53407. /**
  53408. * We check if a seek was into a gap through the following steps:
  53409. * 1. We get a seeking event and we do not get a seeked event. This means that
  53410. * a seek was attempted but not completed.
  53411. * 2. We run `fixesBadSeeks_` on segment loader appends. This means that we already
  53412. * removed everything from our buffer and appended a segment, and should be ready
  53413. * to check for gaps.
  53414. */
  53415. var setSeekingHandlers = function setSeekingHandlers(fn) {
  53416. ['main', 'audio'].forEach(function (type) {
  53417. mpc[type + "SegmentLoader_"][fn]('appended', _this.seekingAppendCheck_);
  53418. });
  53419. };
  53420. this.seekingAppendCheck_ = function () {
  53421. if (_this.fixesBadSeeks_()) {
  53422. _this.consecutiveUpdates = 0;
  53423. _this.lastRecordedTime = _this.tech_.currentTime();
  53424. setSeekingHandlers('off');
  53425. }
  53426. };
  53427. this.clearSeekingAppendCheck_ = function () {
  53428. return setSeekingHandlers('off');
  53429. };
  53430. this.watchForBadSeeking_ = function () {
  53431. _this.clearSeekingAppendCheck_();
  53432. setSeekingHandlers('on');
  53433. };
  53434. this.tech_.on('seeked', this.clearSeekingAppendCheck_);
  53435. this.tech_.on('seeking', this.watchForBadSeeking_);
  53436. this.tech_.on('waiting', waitingHandler);
  53437. this.tech_.on(timerCancelEvents, cancelTimerHandler);
  53438. this.tech_.on('canplay', canPlayHandler);
  53439. /*
  53440. An edge case exists that results in gaps not being skipped when they exist at the beginning of a stream. This case
  53441. is surfaced in one of two ways:
  53442. 1) The `waiting` event is fired before the player has buffered content, making it impossible
  53443. to find or skip the gap. The `waiting` event is followed by a `play` event. On first play
  53444. we can check if playback is stalled due to a gap, and skip the gap if necessary.
  53445. 2) A source with a gap at the beginning of the stream is loaded programatically while the player
  53446. is in a playing state. To catch this case, it's important that our one-time play listener is setup
  53447. even if the player is in a playing state
  53448. */
  53449. this.tech_.one('play', playHandler); // Define the dispose function to clean up our events
  53450. this.dispose = function () {
  53451. _this.clearSeekingAppendCheck_();
  53452. _this.logger_('dispose');
  53453. _this.tech_.off('waiting', waitingHandler);
  53454. _this.tech_.off(timerCancelEvents, cancelTimerHandler);
  53455. _this.tech_.off('canplay', canPlayHandler);
  53456. _this.tech_.off('play', playHandler);
  53457. _this.tech_.off('seeking', _this.watchForBadSeeking_);
  53458. _this.tech_.off('seeked', _this.clearSeekingAppendCheck_);
  53459. loaderTypes.forEach(function (type) {
  53460. mpc[type + "SegmentLoader_"].off('appendsdone', loaderChecks[type].updateend);
  53461. mpc[type + "SegmentLoader_"].off('playlistupdate', loaderChecks[type].reset);
  53462. _this.tech_.off(['seeked', 'seeking'], loaderChecks[type].reset);
  53463. });
  53464. if (_this.checkCurrentTimeTimeout_) {
  53465. window.clearTimeout(_this.checkCurrentTimeTimeout_);
  53466. }
  53467. _this.cancelTimer_();
  53468. };
  53469. }
  53470. /**
  53471. * Periodically check current time to see if playback stopped
  53472. *
  53473. * @private
  53474. */
  53475. var _proto = PlaybackWatcher.prototype;
  53476. _proto.monitorCurrentTime_ = function monitorCurrentTime_() {
  53477. this.checkCurrentTime_();
  53478. if (this.checkCurrentTimeTimeout_) {
  53479. window.clearTimeout(this.checkCurrentTimeTimeout_);
  53480. } // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
  53481. this.checkCurrentTimeTimeout_ = window.setTimeout(this.monitorCurrentTime_.bind(this), 250);
  53482. }
  53483. /**
  53484. * Reset stalled download stats for a specific type of loader
  53485. *
  53486. * @param {string} type
  53487. * The segment loader type to check.
  53488. *
  53489. * @listens SegmentLoader#playlistupdate
  53490. * @listens Tech#seeking
  53491. * @listens Tech#seeked
  53492. */
  53493. ;
  53494. _proto.resetSegmentDownloads_ = function resetSegmentDownloads_(type) {
  53495. var loader = this.masterPlaylistController_[type + "SegmentLoader_"];
  53496. if (this[type + "StalledDownloads_"] > 0) {
  53497. this.logger_("resetting possible stalled download count for " + type + " loader");
  53498. }
  53499. this[type + "StalledDownloads_"] = 0;
  53500. this[type + "Buffered_"] = loader.buffered_();
  53501. }
  53502. /**
  53503. * Checks on every segment `appendsdone` to see
  53504. * if segment appends are making progress. If they are not
  53505. * and we are still downloading bytes. We blacklist the playlist.
  53506. *
  53507. * @param {string} type
  53508. * The segment loader type to check.
  53509. *
  53510. * @listens SegmentLoader#appendsdone
  53511. */
  53512. ;
  53513. _proto.checkSegmentDownloads_ = function checkSegmentDownloads_(type) {
  53514. var mpc = this.masterPlaylistController_;
  53515. var loader = mpc[type + "SegmentLoader_"];
  53516. var buffered = loader.buffered_();
  53517. var isBufferedDifferent = isRangeDifferent(this[type + "Buffered_"], buffered);
  53518. this[type + "Buffered_"] = buffered; // if another watcher is going to fix the issue or
  53519. // the buffered value for this loader changed
  53520. // appends are working
  53521. if (isBufferedDifferent) {
  53522. this.resetSegmentDownloads_(type);
  53523. return;
  53524. }
  53525. this[type + "StalledDownloads_"]++;
  53526. this.logger_("found #" + this[type + "StalledDownloads_"] + " " + type + " appends that did not increase buffer (possible stalled download)", {
  53527. playlistId: loader.playlist_ && loader.playlist_.id,
  53528. buffered: timeRangesToArray(buffered)
  53529. }); // after 10 possibly stalled appends with no reset, exclude
  53530. if (this[type + "StalledDownloads_"] < 10) {
  53531. return;
  53532. }
  53533. this.logger_(type + " loader stalled download exclusion");
  53534. this.resetSegmentDownloads_(type);
  53535. this.tech_.trigger({
  53536. type: 'usage',
  53537. name: "vhs-" + type + "-download-exclusion"
  53538. });
  53539. if (type === 'subtitle') {
  53540. return;
  53541. } // TODO: should we exclude audio tracks rather than main tracks
  53542. // when type is audio?
  53543. mpc.blacklistCurrentPlaylist({
  53544. message: "Excessive " + type + " segment downloading detected."
  53545. }, Infinity);
  53546. }
  53547. /**
  53548. * The purpose of this function is to emulate the "waiting" event on
  53549. * browsers that do not emit it when they are waiting for more
  53550. * data to continue playback
  53551. *
  53552. * @private
  53553. */
  53554. ;
  53555. _proto.checkCurrentTime_ = function checkCurrentTime_() {
  53556. if (this.tech_.paused() || this.tech_.seeking()) {
  53557. return;
  53558. }
  53559. var currentTime = this.tech_.currentTime();
  53560. var buffered = this.tech_.buffered();
  53561. if (this.lastRecordedTime === currentTime && (!buffered.length || currentTime + SAFE_TIME_DELTA >= buffered.end(buffered.length - 1))) {
  53562. // If current time is at the end of the final buffered region, then any playback
  53563. // stall is most likely caused by buffering in a low bandwidth environment. The tech
  53564. // should fire a `waiting` event in this scenario, but due to browser and tech
  53565. // inconsistencies. Calling `techWaiting_` here allows us to simulate
  53566. // responding to a native `waiting` event when the tech fails to emit one.
  53567. return this.techWaiting_();
  53568. }
  53569. if (this.consecutiveUpdates >= 5 && currentTime === this.lastRecordedTime) {
  53570. this.consecutiveUpdates++;
  53571. this.waiting_();
  53572. } else if (currentTime === this.lastRecordedTime) {
  53573. this.consecutiveUpdates++;
  53574. } else {
  53575. this.consecutiveUpdates = 0;
  53576. this.lastRecordedTime = currentTime;
  53577. }
  53578. }
  53579. /**
  53580. * Cancels any pending timers and resets the 'timeupdate' mechanism
  53581. * designed to detect that we are stalled
  53582. *
  53583. * @private
  53584. */
  53585. ;
  53586. _proto.cancelTimer_ = function cancelTimer_() {
  53587. this.consecutiveUpdates = 0;
  53588. if (this.timer_) {
  53589. this.logger_('cancelTimer_');
  53590. clearTimeout(this.timer_);
  53591. }
  53592. this.timer_ = null;
  53593. }
  53594. /**
  53595. * Fixes situations where there's a bad seek
  53596. *
  53597. * @return {boolean} whether an action was taken to fix the seek
  53598. * @private
  53599. */
  53600. ;
  53601. _proto.fixesBadSeeks_ = function fixesBadSeeks_() {
  53602. var seeking = this.tech_.seeking();
  53603. if (!seeking) {
  53604. return false;
  53605. } // TODO: It's possible that these seekable checks should be moved out of this function
  53606. // and into a function that runs on seekablechange. It's also possible that we only need
  53607. // afterSeekableWindow as the buffered check at the bottom is good enough to handle before
  53608. // seekable range.
  53609. var seekable = this.seekable();
  53610. var currentTime = this.tech_.currentTime();
  53611. var isAfterSeekableRange = this.afterSeekableWindow_(seekable, currentTime, this.media(), this.allowSeeksWithinUnsafeLiveWindow);
  53612. var seekTo;
  53613. if (isAfterSeekableRange) {
  53614. var seekableEnd = seekable.end(seekable.length - 1); // sync to live point (if VOD, our seekable was updated and we're simply adjusting)
  53615. seekTo = seekableEnd;
  53616. }
  53617. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  53618. var seekableStart = seekable.start(0); // sync to the beginning of the live window
  53619. // provide a buffer of .1 seconds to handle rounding/imprecise numbers
  53620. seekTo = seekableStart + ( // if the playlist is too short and the seekable range is an exact time (can
  53621. // happen in live with a 3 segment playlist), then don't use a time delta
  53622. seekableStart === seekable.end(0) ? 0 : SAFE_TIME_DELTA);
  53623. }
  53624. if (typeof seekTo !== 'undefined') {
  53625. this.logger_("Trying to seek outside of seekable at time " + currentTime + " with " + ("seekable range " + printableRange(seekable) + ". Seeking to ") + (seekTo + "."));
  53626. this.tech_.setCurrentTime(seekTo);
  53627. return true;
  53628. }
  53629. var sourceUpdater = this.masterPlaylistController_.sourceUpdater_;
  53630. var buffered = this.tech_.buffered();
  53631. var audioBuffered = sourceUpdater.audioBuffer ? sourceUpdater.audioBuffered() : null;
  53632. var videoBuffered = sourceUpdater.videoBuffer ? sourceUpdater.videoBuffered() : null;
  53633. var media = this.media(); // verify that at least two segment durations or one part duration have been
  53634. // appended before checking for a gap.
  53635. var minAppendedDuration = media.partTargetDuration ? media.partTargetDuration : (media.targetDuration - TIME_FUDGE_FACTOR) * 2; // verify that at least two segment durations have been
  53636. // appended before checking for a gap.
  53637. var bufferedToCheck = [audioBuffered, videoBuffered];
  53638. for (var i = 0; i < bufferedToCheck.length; i++) {
  53639. // skip null buffered
  53640. if (!bufferedToCheck[i]) {
  53641. continue;
  53642. }
  53643. var timeAhead = timeAheadOf(bufferedToCheck[i], currentTime); // if we are less than two video/audio segment durations or one part
  53644. // duration behind we haven't appended enough to call this a bad seek.
  53645. if (timeAhead < minAppendedDuration) {
  53646. return false;
  53647. }
  53648. }
  53649. var nextRange = findNextRange(buffered, currentTime); // we have appended enough content, but we don't have anything buffered
  53650. // to seek over the gap
  53651. if (nextRange.length === 0) {
  53652. return false;
  53653. }
  53654. seekTo = nextRange.start(0) + SAFE_TIME_DELTA;
  53655. this.logger_("Buffered region starts (" + nextRange.start(0) + ") " + (" just beyond seek point (" + currentTime + "). Seeking to " + seekTo + "."));
  53656. this.tech_.setCurrentTime(seekTo);
  53657. return true;
  53658. }
  53659. /**
  53660. * Handler for situations when we determine the player is waiting.
  53661. *
  53662. * @private
  53663. */
  53664. ;
  53665. _proto.waiting_ = function waiting_() {
  53666. if (this.techWaiting_()) {
  53667. return;
  53668. } // All tech waiting checks failed. Use last resort correction
  53669. var currentTime = this.tech_.currentTime();
  53670. var buffered = this.tech_.buffered();
  53671. var currentRange = findRange(buffered, currentTime); // Sometimes the player can stall for unknown reasons within a contiguous buffered
  53672. // region with no indication that anything is amiss (seen in Firefox). Seeking to
  53673. // currentTime is usually enough to kickstart the player. This checks that the player
  53674. // is currently within a buffered region before attempting a corrective seek.
  53675. // Chrome does not appear to continue `timeupdate` events after a `waiting` event
  53676. // until there is ~ 3 seconds of forward buffer available. PlaybackWatcher should also
  53677. // make sure there is ~3 seconds of forward buffer before taking any corrective action
  53678. // to avoid triggering an `unknownwaiting` event when the network is slow.
  53679. if (currentRange.length && currentTime + 3 <= currentRange.end(0)) {
  53680. this.cancelTimer_();
  53681. this.tech_.setCurrentTime(currentTime);
  53682. 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
  53683. this.tech_.trigger({
  53684. type: 'usage',
  53685. name: 'vhs-unknown-waiting'
  53686. });
  53687. this.tech_.trigger({
  53688. type: 'usage',
  53689. name: 'hls-unknown-waiting'
  53690. });
  53691. return;
  53692. }
  53693. }
  53694. /**
  53695. * Handler for situations when the tech fires a `waiting` event
  53696. *
  53697. * @return {boolean}
  53698. * True if an action (or none) was needed to correct the waiting. False if no
  53699. * checks passed
  53700. * @private
  53701. */
  53702. ;
  53703. _proto.techWaiting_ = function techWaiting_() {
  53704. var seekable = this.seekable();
  53705. var currentTime = this.tech_.currentTime();
  53706. if (this.tech_.seeking() || this.timer_ !== null) {
  53707. // Tech is seeking or already waiting on another action, no action needed
  53708. return true;
  53709. }
  53710. if (this.beforeSeekableWindow_(seekable, currentTime)) {
  53711. var livePoint = seekable.end(seekable.length - 1);
  53712. this.logger_("Fell out of live window at time " + currentTime + ". Seeking to " + ("live point (seekable end) " + livePoint));
  53713. this.cancelTimer_();
  53714. this.tech_.setCurrentTime(livePoint); // live window resyncs may be useful for monitoring QoS
  53715. this.tech_.trigger({
  53716. type: 'usage',
  53717. name: 'vhs-live-resync'
  53718. });
  53719. this.tech_.trigger({
  53720. type: 'usage',
  53721. name: 'hls-live-resync'
  53722. });
  53723. return true;
  53724. }
  53725. var sourceUpdater = this.tech_.vhs.masterPlaylistController_.sourceUpdater_;
  53726. var buffered = this.tech_.buffered();
  53727. var videoUnderflow = this.videoUnderflow_({
  53728. audioBuffered: sourceUpdater.audioBuffered(),
  53729. videoBuffered: sourceUpdater.videoBuffered(),
  53730. currentTime: currentTime
  53731. });
  53732. if (videoUnderflow) {
  53733. // Even though the video underflowed and was stuck in a gap, the audio overplayed
  53734. // the gap, leading currentTime into a buffered range. Seeking to currentTime
  53735. // allows the video to catch up to the audio position without losing any audio
  53736. // (only suffering ~3 seconds of frozen video and a pause in audio playback).
  53737. this.cancelTimer_();
  53738. this.tech_.setCurrentTime(currentTime); // video underflow may be useful for monitoring QoS
  53739. this.tech_.trigger({
  53740. type: 'usage',
  53741. name: 'vhs-video-underflow'
  53742. });
  53743. this.tech_.trigger({
  53744. type: 'usage',
  53745. name: 'hls-video-underflow'
  53746. });
  53747. return true;
  53748. }
  53749. var nextRange = findNextRange(buffered, currentTime); // check for gap
  53750. if (nextRange.length > 0) {
  53751. var difference = nextRange.start(0) - currentTime;
  53752. this.logger_("Stopped at " + currentTime + ", setting timer for " + difference + ", seeking " + ("to " + nextRange.start(0)));
  53753. this.cancelTimer_();
  53754. this.timer_ = setTimeout(this.skipTheGap_.bind(this), difference * 1000, currentTime);
  53755. return true;
  53756. } // All checks failed. Returning false to indicate failure to correct waiting
  53757. return false;
  53758. };
  53759. _proto.afterSeekableWindow_ = function afterSeekableWindow_(seekable, currentTime, playlist, allowSeeksWithinUnsafeLiveWindow) {
  53760. if (allowSeeksWithinUnsafeLiveWindow === void 0) {
  53761. allowSeeksWithinUnsafeLiveWindow = false;
  53762. }
  53763. if (!seekable.length) {
  53764. // we can't make a solid case if there's no seekable, default to false
  53765. return false;
  53766. }
  53767. var allowedEnd = seekable.end(seekable.length - 1) + SAFE_TIME_DELTA;
  53768. var isLive = !playlist.endList;
  53769. if (isLive && allowSeeksWithinUnsafeLiveWindow) {
  53770. allowedEnd = seekable.end(seekable.length - 1) + playlist.targetDuration * 3;
  53771. }
  53772. if (currentTime > allowedEnd) {
  53773. return true;
  53774. }
  53775. return false;
  53776. };
  53777. _proto.beforeSeekableWindow_ = function beforeSeekableWindow_(seekable, currentTime) {
  53778. if (seekable.length && // can't fall before 0 and 0 seekable start identifies VOD stream
  53779. seekable.start(0) > 0 && currentTime < seekable.start(0) - this.liveRangeSafeTimeDelta) {
  53780. return true;
  53781. }
  53782. return false;
  53783. };
  53784. _proto.videoUnderflow_ = function videoUnderflow_(_ref) {
  53785. var videoBuffered = _ref.videoBuffered,
  53786. audioBuffered = _ref.audioBuffered,
  53787. currentTime = _ref.currentTime; // audio only content will not have video underflow :)
  53788. if (!videoBuffered) {
  53789. return;
  53790. }
  53791. var gap; // find a gap in demuxed content.
  53792. if (videoBuffered.length && audioBuffered.length) {
  53793. // in Chrome audio will continue to play for ~3s when we run out of video
  53794. // so we have to check that the video buffer did have some buffer in the
  53795. // past.
  53796. var lastVideoRange = findRange(videoBuffered, currentTime - 3);
  53797. var videoRange = findRange(videoBuffered, currentTime);
  53798. var audioRange = findRange(audioBuffered, currentTime);
  53799. if (audioRange.length && !videoRange.length && lastVideoRange.length) {
  53800. gap = {
  53801. start: lastVideoRange.end(0),
  53802. end: audioRange.end(0)
  53803. };
  53804. } // find a gap in muxed content.
  53805. } else {
  53806. var nextRange = findNextRange(videoBuffered, currentTime); // Even if there is no available next range, there is still a possibility we are
  53807. // stuck in a gap due to video underflow.
  53808. if (!nextRange.length) {
  53809. gap = this.gapFromVideoUnderflow_(videoBuffered, currentTime);
  53810. }
  53811. }
  53812. if (gap) {
  53813. this.logger_("Encountered a gap in video from " + gap.start + " to " + gap.end + ". " + ("Seeking to current time " + currentTime));
  53814. return true;
  53815. }
  53816. return false;
  53817. }
  53818. /**
  53819. * Timer callback. If playback still has not proceeded, then we seek
  53820. * to the start of the next buffered region.
  53821. *
  53822. * @private
  53823. */
  53824. ;
  53825. _proto.skipTheGap_ = function skipTheGap_(scheduledCurrentTime) {
  53826. var buffered = this.tech_.buffered();
  53827. var currentTime = this.tech_.currentTime();
  53828. var nextRange = findNextRange(buffered, currentTime);
  53829. this.cancelTimer_();
  53830. if (nextRange.length === 0 || currentTime !== scheduledCurrentTime) {
  53831. return;
  53832. }
  53833. this.logger_('skipTheGap_:', 'currentTime:', currentTime, 'scheduled currentTime:', scheduledCurrentTime, 'nextRange start:', nextRange.start(0)); // only seek if we still have not played
  53834. this.tech_.setCurrentTime(nextRange.start(0) + TIME_FUDGE_FACTOR);
  53835. this.tech_.trigger({
  53836. type: 'usage',
  53837. name: 'vhs-gap-skip'
  53838. });
  53839. this.tech_.trigger({
  53840. type: 'usage',
  53841. name: 'hls-gap-skip'
  53842. });
  53843. };
  53844. _proto.gapFromVideoUnderflow_ = function gapFromVideoUnderflow_(buffered, currentTime) {
  53845. // At least in Chrome, if there is a gap in the video buffer, the audio will continue
  53846. // playing for ~3 seconds after the video gap starts. This is done to account for
  53847. // video buffer underflow/underrun (note that this is not done when there is audio
  53848. // buffer underflow/underrun -- in that case the video will stop as soon as it
  53849. // encounters the gap, as audio stalls are more noticeable/jarring to a user than
  53850. // video stalls). The player's time will reflect the playthrough of audio, so the
  53851. // time will appear as if we are in a buffered region, even if we are stuck in a
  53852. // "gap."
  53853. //
  53854. // Example:
  53855. // video buffer: 0 => 10.1, 10.2 => 20
  53856. // audio buffer: 0 => 20
  53857. // overall buffer: 0 => 10.1, 10.2 => 20
  53858. // current time: 13
  53859. //
  53860. // Chrome's video froze at 10 seconds, where the video buffer encountered the gap,
  53861. // however, the audio continued playing until it reached ~3 seconds past the gap
  53862. // (13 seconds), at which point it stops as well. Since current time is past the
  53863. // gap, findNextRange will return no ranges.
  53864. //
  53865. // To check for this issue, we see if there is a gap that starts somewhere within
  53866. // a 3 second range (3 seconds +/- 1 second) back from our current time.
  53867. var gaps = findGaps(buffered);
  53868. for (var i = 0; i < gaps.length; i++) {
  53869. var start = gaps.start(i);
  53870. var end = gaps.end(i); // gap is starts no more than 4 seconds back
  53871. if (currentTime - start < 4 && currentTime - start > 2) {
  53872. return {
  53873. start: start,
  53874. end: end
  53875. };
  53876. }
  53877. }
  53878. return null;
  53879. };
  53880. return PlaybackWatcher;
  53881. }();
  53882. var defaultOptions = {
  53883. errorInterval: 30,
  53884. getSource: function getSource(next) {
  53885. var tech = this.tech({
  53886. IWillNotUseThisInPlugins: true
  53887. });
  53888. var sourceObj = tech.currentSource_ || this.currentSource();
  53889. return next(sourceObj);
  53890. }
  53891. };
  53892. /**
  53893. * Main entry point for the plugin
  53894. *
  53895. * @param {Player} player a reference to a videojs Player instance
  53896. * @param {Object} [options] an object with plugin options
  53897. * @private
  53898. */
  53899. var initPlugin = function initPlugin(player, options) {
  53900. var lastCalled = 0;
  53901. var seekTo = 0;
  53902. var localOptions = videojs.mergeOptions(defaultOptions, options);
  53903. player.ready(function () {
  53904. player.trigger({
  53905. type: 'usage',
  53906. name: 'vhs-error-reload-initialized'
  53907. });
  53908. player.trigger({
  53909. type: 'usage',
  53910. name: 'hls-error-reload-initialized'
  53911. });
  53912. });
  53913. /**
  53914. * Player modifications to perform that must wait until `loadedmetadata`
  53915. * has been triggered
  53916. *
  53917. * @private
  53918. */
  53919. var loadedMetadataHandler = function loadedMetadataHandler() {
  53920. if (seekTo) {
  53921. player.currentTime(seekTo);
  53922. }
  53923. };
  53924. /**
  53925. * Set the source on the player element, play, and seek if necessary
  53926. *
  53927. * @param {Object} sourceObj An object specifying the source url and mime-type to play
  53928. * @private
  53929. */
  53930. var setSource = function setSource(sourceObj) {
  53931. if (sourceObj === null || sourceObj === undefined) {
  53932. return;
  53933. }
  53934. seekTo = player.duration() !== Infinity && player.currentTime() || 0;
  53935. player.one('loadedmetadata', loadedMetadataHandler);
  53936. player.src(sourceObj);
  53937. player.trigger({
  53938. type: 'usage',
  53939. name: 'vhs-error-reload'
  53940. });
  53941. player.trigger({
  53942. type: 'usage',
  53943. name: 'hls-error-reload'
  53944. });
  53945. player.play();
  53946. };
  53947. /**
  53948. * Attempt to get a source from either the built-in getSource function
  53949. * or a custom function provided via the options
  53950. *
  53951. * @private
  53952. */
  53953. var errorHandler = function errorHandler() {
  53954. // Do not attempt to reload the source if a source-reload occurred before
  53955. // 'errorInterval' time has elapsed since the last source-reload
  53956. if (Date.now() - lastCalled < localOptions.errorInterval * 1000) {
  53957. player.trigger({
  53958. type: 'usage',
  53959. name: 'vhs-error-reload-canceled'
  53960. });
  53961. player.trigger({
  53962. type: 'usage',
  53963. name: 'hls-error-reload-canceled'
  53964. });
  53965. return;
  53966. }
  53967. if (!localOptions.getSource || typeof localOptions.getSource !== 'function') {
  53968. videojs.log.error('ERROR: reloadSourceOnError - The option getSource must be a function!');
  53969. return;
  53970. }
  53971. lastCalled = Date.now();
  53972. return localOptions.getSource.call(player, setSource);
  53973. };
  53974. /**
  53975. * Unbind any event handlers that were bound by the plugin
  53976. *
  53977. * @private
  53978. */
  53979. var cleanupEvents = function cleanupEvents() {
  53980. player.off('loadedmetadata', loadedMetadataHandler);
  53981. player.off('error', errorHandler);
  53982. player.off('dispose', cleanupEvents);
  53983. };
  53984. /**
  53985. * Cleanup before re-initializing the plugin
  53986. *
  53987. * @param {Object} [newOptions] an object with plugin options
  53988. * @private
  53989. */
  53990. var reinitPlugin = function reinitPlugin(newOptions) {
  53991. cleanupEvents();
  53992. initPlugin(player, newOptions);
  53993. };
  53994. player.on('error', errorHandler);
  53995. player.on('dispose', cleanupEvents); // Overwrite the plugin function so that we can correctly cleanup before
  53996. // initializing the plugin
  53997. player.reloadSourceOnError = reinitPlugin;
  53998. };
  53999. /**
  54000. * Reload the source when an error is detected as long as there
  54001. * wasn't an error previously within the last 30 seconds
  54002. *
  54003. * @param {Object} [options] an object with plugin options
  54004. */
  54005. var reloadSourceOnError = function reloadSourceOnError(options) {
  54006. initPlugin(this, options);
  54007. };
  54008. var version$4 = "2.16.2";
  54009. var version$3 = "6.0.1";
  54010. var version$2 = "0.22.1";
  54011. var version$1 = "4.8.0";
  54012. var version = "3.1.3";
  54013. var Vhs = {
  54014. PlaylistLoader: PlaylistLoader,
  54015. Playlist: Playlist,
  54016. utils: utils,
  54017. STANDARD_PLAYLIST_SELECTOR: lastBandwidthSelector,
  54018. INITIAL_PLAYLIST_SELECTOR: lowestBitrateCompatibleVariantSelector,
  54019. lastBandwidthSelector: lastBandwidthSelector,
  54020. movingAverageBandwidthSelector: movingAverageBandwidthSelector,
  54021. comparePlaylistBandwidth: comparePlaylistBandwidth,
  54022. comparePlaylistResolution: comparePlaylistResolution,
  54023. xhr: xhrFactory()
  54024. }; // Define getter/setters for config properties
  54025. Object.keys(Config).forEach(function (prop) {
  54026. Object.defineProperty(Vhs, prop, {
  54027. get: function get() {
  54028. videojs.log.warn("using Vhs." + prop + " is UNSAFE be sure you know what you are doing");
  54029. return Config[prop];
  54030. },
  54031. set: function set(value) {
  54032. videojs.log.warn("using Vhs." + prop + " is UNSAFE be sure you know what you are doing");
  54033. if (typeof value !== 'number' || value < 0) {
  54034. videojs.log.warn("value of Vhs." + prop + " must be greater than or equal to 0");
  54035. return;
  54036. }
  54037. Config[prop] = value;
  54038. }
  54039. });
  54040. });
  54041. var LOCAL_STORAGE_KEY = 'videojs-vhs';
  54042. /**
  54043. * Updates the selectedIndex of the QualityLevelList when a mediachange happens in vhs.
  54044. *
  54045. * @param {QualityLevelList} qualityLevels The QualityLevelList to update.
  54046. * @param {PlaylistLoader} playlistLoader PlaylistLoader containing the new media info.
  54047. * @function handleVhsMediaChange
  54048. */
  54049. var handleVhsMediaChange = function handleVhsMediaChange(qualityLevels, playlistLoader) {
  54050. var newPlaylist = playlistLoader.media();
  54051. var selectedIndex = -1;
  54052. for (var i = 0; i < qualityLevels.length; i++) {
  54053. if (qualityLevels[i].id === newPlaylist.id) {
  54054. selectedIndex = i;
  54055. break;
  54056. }
  54057. }
  54058. qualityLevels.selectedIndex_ = selectedIndex;
  54059. qualityLevels.trigger({
  54060. selectedIndex: selectedIndex,
  54061. type: 'change'
  54062. });
  54063. };
  54064. /**
  54065. * Adds quality levels to list once playlist metadata is available
  54066. *
  54067. * @param {QualityLevelList} qualityLevels The QualityLevelList to attach events to.
  54068. * @param {Object} vhs Vhs object to listen to for media events.
  54069. * @function handleVhsLoadedMetadata
  54070. */
  54071. var handleVhsLoadedMetadata = function handleVhsLoadedMetadata(qualityLevels, vhs) {
  54072. vhs.representations().forEach(function (rep) {
  54073. qualityLevels.addQualityLevel(rep);
  54074. });
  54075. handleVhsMediaChange(qualityLevels, vhs.playlists);
  54076. }; // HLS is a source handler, not a tech. Make sure attempts to use it
  54077. // as one do not cause exceptions.
  54078. Vhs.canPlaySource = function () {
  54079. return videojs.log.warn('HLS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  54080. };
  54081. var emeKeySystems = function emeKeySystems(keySystemOptions, mainPlaylist, audioPlaylist) {
  54082. if (!keySystemOptions) {
  54083. return keySystemOptions;
  54084. }
  54085. var codecs = {};
  54086. if (mainPlaylist && mainPlaylist.attributes && mainPlaylist.attributes.CODECS) {
  54087. codecs = unwrapCodecList(parseCodecs(mainPlaylist.attributes.CODECS));
  54088. }
  54089. if (audioPlaylist && audioPlaylist.attributes && audioPlaylist.attributes.CODECS) {
  54090. codecs.audio = audioPlaylist.attributes.CODECS;
  54091. }
  54092. var videoContentType = getMimeForCodec(codecs.video);
  54093. var audioContentType = getMimeForCodec(codecs.audio); // upsert the content types based on the selected playlist
  54094. var keySystemContentTypes = {};
  54095. for (var keySystem in keySystemOptions) {
  54096. keySystemContentTypes[keySystem] = {};
  54097. if (audioContentType) {
  54098. keySystemContentTypes[keySystem].audioContentType = audioContentType;
  54099. }
  54100. if (videoContentType) {
  54101. keySystemContentTypes[keySystem].videoContentType = videoContentType;
  54102. } // Default to using the video playlist's PSSH even though they may be different, as
  54103. // videojs-contrib-eme will only accept one in the options.
  54104. //
  54105. // This shouldn't be an issue for most cases as early intialization will handle all
  54106. // unique PSSH values, and if they aren't, then encrypted events should have the
  54107. // specific information needed for the unique license.
  54108. if (mainPlaylist.contentProtection && mainPlaylist.contentProtection[keySystem] && mainPlaylist.contentProtection[keySystem].pssh) {
  54109. keySystemContentTypes[keySystem].pssh = mainPlaylist.contentProtection[keySystem].pssh;
  54110. } // videojs-contrib-eme accepts the option of specifying: 'com.some.cdm': 'url'
  54111. // so we need to prevent overwriting the URL entirely
  54112. if (typeof keySystemOptions[keySystem] === 'string') {
  54113. keySystemContentTypes[keySystem].url = keySystemOptions[keySystem];
  54114. }
  54115. }
  54116. return videojs.mergeOptions(keySystemOptions, keySystemContentTypes);
  54117. };
  54118. /**
  54119. * @typedef {Object} KeySystems
  54120. *
  54121. * keySystems configuration for https://github.com/videojs/videojs-contrib-eme
  54122. * Note: not all options are listed here.
  54123. *
  54124. * @property {Uint8Array} [pssh]
  54125. * Protection System Specific Header
  54126. */
  54127. /**
  54128. * Goes through all the playlists and collects an array of KeySystems options objects
  54129. * containing each playlist's keySystems and their pssh values, if available.
  54130. *
  54131. * @param {Object[]} playlists
  54132. * The playlists to look through
  54133. * @param {string[]} keySystems
  54134. * The keySystems to collect pssh values for
  54135. *
  54136. * @return {KeySystems[]}
  54137. * An array of KeySystems objects containing available key systems and their
  54138. * pssh values
  54139. */
  54140. var getAllPsshKeySystemsOptions = function getAllPsshKeySystemsOptions(playlists, keySystems) {
  54141. return playlists.reduce(function (keySystemsArr, playlist) {
  54142. if (!playlist.contentProtection) {
  54143. return keySystemsArr;
  54144. }
  54145. var keySystemsOptions = keySystems.reduce(function (keySystemsObj, keySystem) {
  54146. var keySystemOptions = playlist.contentProtection[keySystem];
  54147. if (keySystemOptions && keySystemOptions.pssh) {
  54148. keySystemsObj[keySystem] = {
  54149. pssh: keySystemOptions.pssh
  54150. };
  54151. }
  54152. return keySystemsObj;
  54153. }, {});
  54154. if (Object.keys(keySystemsOptions).length) {
  54155. keySystemsArr.push(keySystemsOptions);
  54156. }
  54157. return keySystemsArr;
  54158. }, []);
  54159. };
  54160. /**
  54161. * Returns a promise that waits for the
  54162. * [eme plugin](https://github.com/videojs/videojs-contrib-eme) to create a key session.
  54163. *
  54164. * Works around https://bugs.chromium.org/p/chromium/issues/detail?id=895449 in non-IE11
  54165. * browsers.
  54166. *
  54167. * As per the above ticket, this is particularly important for Chrome, where, if
  54168. * unencrypted content is appended before encrypted content and the key session has not
  54169. * been created, a MEDIA_ERR_DECODE will be thrown once the encrypted content is reached
  54170. * during playback.
  54171. *
  54172. * @param {Object} player
  54173. * The player instance
  54174. * @param {Object[]} sourceKeySystems
  54175. * The key systems options from the player source
  54176. * @param {Object} [audioMedia]
  54177. * The active audio media playlist (optional)
  54178. * @param {Object[]} mainPlaylists
  54179. * The playlists found on the master playlist object
  54180. *
  54181. * @return {Object}
  54182. * Promise that resolves when the key session has been created
  54183. */
  54184. var waitForKeySessionCreation = function waitForKeySessionCreation(_ref) {
  54185. var player = _ref.player,
  54186. sourceKeySystems = _ref.sourceKeySystems,
  54187. audioMedia = _ref.audioMedia,
  54188. mainPlaylists = _ref.mainPlaylists;
  54189. if (!player.eme.initializeMediaKeys) {
  54190. return Promise.resolve();
  54191. } // TODO should all audio PSSH values be initialized for DRM?
  54192. //
  54193. // All unique video rendition pssh values are initialized for DRM, but here only
  54194. // the initial audio playlist license is initialized. In theory, an encrypted
  54195. // event should be fired if the user switches to an alternative audio playlist
  54196. // where a license is required, but this case hasn't yet been tested. In addition, there
  54197. // may be many alternate audio playlists unlikely to be used (e.g., multiple different
  54198. // languages).
  54199. var playlists = audioMedia ? mainPlaylists.concat([audioMedia]) : mainPlaylists;
  54200. var keySystemsOptionsArr = getAllPsshKeySystemsOptions(playlists, Object.keys(sourceKeySystems));
  54201. var initializationFinishedPromises = [];
  54202. var keySessionCreatedPromises = []; // Since PSSH values are interpreted as initData, EME will dedupe any duplicates. The
  54203. // only place where it should not be deduped is for ms-prefixed APIs, but the early
  54204. // return for IE11 above, and the existence of modern EME APIs in addition to
  54205. // ms-prefixed APIs on Edge should prevent this from being a concern.
  54206. // initializeMediaKeys also won't use the webkit-prefixed APIs.
  54207. keySystemsOptionsArr.forEach(function (keySystemsOptions) {
  54208. keySessionCreatedPromises.push(new Promise(function (resolve, reject) {
  54209. player.tech_.one('keysessioncreated', resolve);
  54210. }));
  54211. initializationFinishedPromises.push(new Promise(function (resolve, reject) {
  54212. player.eme.initializeMediaKeys({
  54213. keySystems: keySystemsOptions
  54214. }, function (err) {
  54215. if (err) {
  54216. reject(err);
  54217. return;
  54218. }
  54219. resolve();
  54220. });
  54221. }));
  54222. }); // The reasons Promise.race is chosen over Promise.any:
  54223. //
  54224. // * Promise.any is only available in Safari 14+.
  54225. // * None of these promises are expected to reject. If they do reject, it might be
  54226. // better here for the race to surface the rejection, rather than mask it by using
  54227. // Promise.any.
  54228. return Promise.race([// If a session was previously created, these will all finish resolving without
  54229. // creating a new session, otherwise it will take until the end of all license
  54230. // requests, which is why the key session check is used (to make setup much faster).
  54231. Promise.all(initializationFinishedPromises), // Once a single session is created, the browser knows DRM will be used.
  54232. Promise.race(keySessionCreatedPromises)]);
  54233. };
  54234. /**
  54235. * If the [eme](https://github.com/videojs/videojs-contrib-eme) plugin is available, and
  54236. * there are keySystems on the source, sets up source options to prepare the source for
  54237. * eme.
  54238. *
  54239. * @param {Object} player
  54240. * The player instance
  54241. * @param {Object[]} sourceKeySystems
  54242. * The key systems options from the player source
  54243. * @param {Object} media
  54244. * The active media playlist
  54245. * @param {Object} [audioMedia]
  54246. * The active audio media playlist (optional)
  54247. *
  54248. * @return {boolean}
  54249. * Whether or not options were configured and EME is available
  54250. */
  54251. var setupEmeOptions = function setupEmeOptions(_ref2) {
  54252. var player = _ref2.player,
  54253. sourceKeySystems = _ref2.sourceKeySystems,
  54254. media = _ref2.media,
  54255. audioMedia = _ref2.audioMedia;
  54256. var sourceOptions = emeKeySystems(sourceKeySystems, media, audioMedia);
  54257. if (!sourceOptions) {
  54258. return false;
  54259. }
  54260. player.currentSource().keySystems = sourceOptions; // eme handles the rest of the setup, so if it is missing
  54261. // do nothing.
  54262. if (sourceOptions && !player.eme) {
  54263. videojs.log.warn('DRM encrypted source cannot be decrypted without a DRM plugin');
  54264. return false;
  54265. }
  54266. return true;
  54267. };
  54268. var getVhsLocalStorage = function getVhsLocalStorage() {
  54269. if (!window.localStorage) {
  54270. return null;
  54271. }
  54272. var storedObject = window.localStorage.getItem(LOCAL_STORAGE_KEY);
  54273. if (!storedObject) {
  54274. return null;
  54275. }
  54276. try {
  54277. return JSON.parse(storedObject);
  54278. } catch (e) {
  54279. // someone may have tampered with the value
  54280. return null;
  54281. }
  54282. };
  54283. var updateVhsLocalStorage = function updateVhsLocalStorage(options) {
  54284. if (!window.localStorage) {
  54285. return false;
  54286. }
  54287. var objectToStore = getVhsLocalStorage();
  54288. objectToStore = objectToStore ? videojs.mergeOptions(objectToStore, options) : options;
  54289. try {
  54290. window.localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(objectToStore));
  54291. } catch (e) {
  54292. // Throws if storage is full (e.g., always on iOS 5+ Safari private mode, where
  54293. // storage is set to 0).
  54294. // https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#Exceptions
  54295. // No need to perform any operation.
  54296. return false;
  54297. }
  54298. return objectToStore;
  54299. };
  54300. /**
  54301. * Parses VHS-supported media types from data URIs. See
  54302. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
  54303. * for information on data URIs.
  54304. *
  54305. * @param {string} dataUri
  54306. * The data URI
  54307. *
  54308. * @return {string|Object}
  54309. * The parsed object/string, or the original string if no supported media type
  54310. * was found
  54311. */
  54312. var expandDataUri = function expandDataUri(dataUri) {
  54313. if (dataUri.toLowerCase().indexOf('data:application/vnd.videojs.vhs+json,') === 0) {
  54314. return JSON.parse(dataUri.substring(dataUri.indexOf(',') + 1));
  54315. } // no known case for this data URI, return the string as-is
  54316. return dataUri;
  54317. };
  54318. /**
  54319. * Whether the browser has built-in HLS support.
  54320. */
  54321. Vhs.supportsNativeHls = function () {
  54322. if (!document || !document.createElement) {
  54323. return false;
  54324. }
  54325. var video = document.createElement('video'); // native HLS is definitely not supported if HTML5 video isn't
  54326. if (!videojs.getTech('Html5').isSupported()) {
  54327. return false;
  54328. } // HLS manifests can go by many mime-types
  54329. var canPlay = [// Apple santioned
  54330. 'application/vnd.apple.mpegurl', // Apple sanctioned for backwards compatibility
  54331. 'audio/mpegurl', // Very common
  54332. 'audio/x-mpegurl', // Very common
  54333. 'application/x-mpegurl', // Included for completeness
  54334. 'video/x-mpegurl', 'video/mpegurl', 'application/mpegurl'];
  54335. return canPlay.some(function (canItPlay) {
  54336. return /maybe|probably/i.test(video.canPlayType(canItPlay));
  54337. });
  54338. }();
  54339. Vhs.supportsNativeDash = function () {
  54340. if (!document || !document.createElement || !videojs.getTech('Html5').isSupported()) {
  54341. return false;
  54342. }
  54343. return /maybe|probably/i.test(document.createElement('video').canPlayType('application/dash+xml'));
  54344. }();
  54345. Vhs.supportsTypeNatively = function (type) {
  54346. if (type === 'hls') {
  54347. return Vhs.supportsNativeHls;
  54348. }
  54349. if (type === 'dash') {
  54350. return Vhs.supportsNativeDash;
  54351. }
  54352. return false;
  54353. };
  54354. /**
  54355. * HLS is a source handler, not a tech. Make sure attempts to use it
  54356. * as one do not cause exceptions.
  54357. */
  54358. Vhs.isSupported = function () {
  54359. return videojs.log.warn('HLS is no longer a tech. Please remove it from ' + 'your player\'s techOrder.');
  54360. };
  54361. var Component = videojs.getComponent('Component');
  54362. /**
  54363. * The Vhs Handler object, where we orchestrate all of the parts
  54364. * of HLS to interact with video.js
  54365. *
  54366. * @class VhsHandler
  54367. * @extends videojs.Component
  54368. * @param {Object} source the soruce object
  54369. * @param {Tech} tech the parent tech object
  54370. * @param {Object} options optional and required options
  54371. */
  54372. var VhsHandler = /*#__PURE__*/function (_Component) {
  54373. inheritsLoose(VhsHandler, _Component);
  54374. function VhsHandler(source, tech, options) {
  54375. var _this;
  54376. _this = _Component.call(this, tech, videojs.mergeOptions(options.hls, options.vhs)) || this;
  54377. if (options.hls && Object.keys(options.hls).length) {
  54378. videojs.log.warn('Using hls options is deprecated. Please rename `hls` to `vhs` in your options object.');
  54379. } // if a tech level `initialBandwidth` option was passed
  54380. // use that over the VHS level `bandwidth` option
  54381. if (typeof options.initialBandwidth === 'number') {
  54382. _this.options_.bandwidth = options.initialBandwidth;
  54383. }
  54384. _this.logger_ = logger('VhsHandler'); // tech.player() is deprecated but setup a reference to HLS for
  54385. // backwards-compatibility
  54386. if (tech.options_ && tech.options_.playerId) {
  54387. var _player = videojs(tech.options_.playerId);
  54388. if (!_player.hasOwnProperty('hls')) {
  54389. Object.defineProperty(_player, 'hls', {
  54390. get: function get() {
  54391. videojs.log.warn('player.hls is deprecated. Use player.tech().vhs instead.');
  54392. tech.trigger({
  54393. type: 'usage',
  54394. name: 'hls-player-access'
  54395. });
  54396. return assertThisInitialized(_this);
  54397. },
  54398. configurable: true
  54399. });
  54400. }
  54401. if (!_player.hasOwnProperty('vhs')) {
  54402. Object.defineProperty(_player, 'vhs', {
  54403. get: function get() {
  54404. videojs.log.warn('player.vhs is deprecated. Use player.tech().vhs instead.');
  54405. tech.trigger({
  54406. type: 'usage',
  54407. name: 'vhs-player-access'
  54408. });
  54409. return assertThisInitialized(_this);
  54410. },
  54411. configurable: true
  54412. });
  54413. }
  54414. if (!_player.hasOwnProperty('dash')) {
  54415. Object.defineProperty(_player, 'dash', {
  54416. get: function get() {
  54417. videojs.log.warn('player.dash is deprecated. Use player.tech().vhs instead.');
  54418. return assertThisInitialized(_this);
  54419. },
  54420. configurable: true
  54421. });
  54422. }
  54423. _this.player_ = _player;
  54424. }
  54425. _this.tech_ = tech;
  54426. _this.source_ = source;
  54427. _this.stats = {};
  54428. _this.ignoreNextSeekingEvent_ = false;
  54429. _this.setOptions_();
  54430. if (_this.options_.overrideNative && tech.overrideNativeAudioTracks && tech.overrideNativeVideoTracks) {
  54431. tech.overrideNativeAudioTracks(true);
  54432. tech.overrideNativeVideoTracks(true);
  54433. } else if (_this.options_.overrideNative && (tech.featuresNativeVideoTracks || tech.featuresNativeAudioTracks)) {
  54434. // overriding native HLS only works if audio tracks have been emulated
  54435. // error early if we're misconfigured
  54436. throw new Error('Overriding native HLS requires emulated tracks. ' + 'See https://git.io/vMpjB');
  54437. } // listen for fullscreenchange events for this player so that we
  54438. // can adjust our quality selection quickly
  54439. _this.on(document, ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'], function (event) {
  54440. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  54441. if (fullscreenElement && fullscreenElement.contains(_this.tech_.el())) {
  54442. _this.masterPlaylistController_.fastQualityChange_();
  54443. } else {
  54444. // When leaving fullscreen, since the in page pixel dimensions should be smaller
  54445. // than full screen, see if there should be a rendition switch down to preserve
  54446. // bandwidth.
  54447. _this.masterPlaylistController_.checkABR_();
  54448. }
  54449. });
  54450. _this.on(_this.tech_, 'seeking', function () {
  54451. if (this.ignoreNextSeekingEvent_) {
  54452. this.ignoreNextSeekingEvent_ = false;
  54453. return;
  54454. }
  54455. this.setCurrentTime(this.tech_.currentTime());
  54456. });
  54457. _this.on(_this.tech_, 'error', function () {
  54458. // verify that the error was real and we are loaded
  54459. // enough to have mpc loaded.
  54460. if (this.tech_.error() && this.masterPlaylistController_) {
  54461. this.masterPlaylistController_.pauseLoading();
  54462. }
  54463. });
  54464. _this.on(_this.tech_, 'play', _this.play);
  54465. return _this;
  54466. }
  54467. var _proto = VhsHandler.prototype;
  54468. _proto.setOptions_ = function setOptions_() {
  54469. var _this2 = this; // defaults
  54470. this.options_.withCredentials = this.options_.withCredentials || false;
  54471. this.options_.handleManifestRedirects = this.options_.handleManifestRedirects === false ? false : true;
  54472. this.options_.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions === false ? false : true;
  54473. this.options_.useDevicePixelRatio = this.options_.useDevicePixelRatio || false;
  54474. this.options_.smoothQualityChange = this.options_.smoothQualityChange || false;
  54475. this.options_.useBandwidthFromLocalStorage = typeof this.source_.useBandwidthFromLocalStorage !== 'undefined' ? this.source_.useBandwidthFromLocalStorage : this.options_.useBandwidthFromLocalStorage || false;
  54476. this.options_.useNetworkInformationApi = this.options_.useNetworkInformationApi || false;
  54477. this.options_.useDtsForTimestampOffset = this.options_.useDtsForTimestampOffset || false;
  54478. this.options_.customTagParsers = this.options_.customTagParsers || [];
  54479. this.options_.customTagMappers = this.options_.customTagMappers || [];
  54480. this.options_.cacheEncryptionKeys = this.options_.cacheEncryptionKeys || false;
  54481. if (typeof this.options_.blacklistDuration !== 'number') {
  54482. this.options_.blacklistDuration = 5 * 60;
  54483. }
  54484. if (typeof this.options_.bandwidth !== 'number') {
  54485. if (this.options_.useBandwidthFromLocalStorage) {
  54486. var storedObject = getVhsLocalStorage();
  54487. if (storedObject && storedObject.bandwidth) {
  54488. this.options_.bandwidth = storedObject.bandwidth;
  54489. this.tech_.trigger({
  54490. type: 'usage',
  54491. name: 'vhs-bandwidth-from-local-storage'
  54492. });
  54493. this.tech_.trigger({
  54494. type: 'usage',
  54495. name: 'hls-bandwidth-from-local-storage'
  54496. });
  54497. }
  54498. if (storedObject && storedObject.throughput) {
  54499. this.options_.throughput = storedObject.throughput;
  54500. this.tech_.trigger({
  54501. type: 'usage',
  54502. name: 'vhs-throughput-from-local-storage'
  54503. });
  54504. this.tech_.trigger({
  54505. type: 'usage',
  54506. name: 'hls-throughput-from-local-storage'
  54507. });
  54508. }
  54509. }
  54510. } // if bandwidth was not set by options or pulled from local storage, start playlist
  54511. // selection at a reasonable bandwidth
  54512. if (typeof this.options_.bandwidth !== 'number') {
  54513. this.options_.bandwidth = Config.INITIAL_BANDWIDTH;
  54514. } // If the bandwidth number is unchanged from the initial setting
  54515. // then this takes precedence over the enableLowInitialPlaylist option
  54516. this.options_.enableLowInitialPlaylist = this.options_.enableLowInitialPlaylist && this.options_.bandwidth === Config.INITIAL_BANDWIDTH; // grab options passed to player.src
  54517. ['withCredentials', 'useDevicePixelRatio', 'limitRenditionByPlayerDimensions', 'bandwidth', 'smoothQualityChange', 'customTagParsers', 'customTagMappers', 'handleManifestRedirects', 'cacheEncryptionKeys', 'playlistSelector', 'initialPlaylistSelector', 'experimentalBufferBasedABR', 'liveRangeSafeTimeDelta', 'experimentalLLHLS', 'useNetworkInformationApi', 'useDtsForTimestampOffset', 'experimentalExactManifestTimings', 'experimentalLeastPixelDiffSelector'].forEach(function (option) {
  54518. if (typeof _this2.source_[option] !== 'undefined') {
  54519. _this2.options_[option] = _this2.source_[option];
  54520. }
  54521. });
  54522. this.limitRenditionByPlayerDimensions = this.options_.limitRenditionByPlayerDimensions;
  54523. this.useDevicePixelRatio = this.options_.useDevicePixelRatio;
  54524. }
  54525. /**
  54526. * called when player.src gets called, handle a new source
  54527. *
  54528. * @param {Object} src the source object to handle
  54529. */
  54530. ;
  54531. _proto.src = function src(_src, type) {
  54532. var _this3 = this; // do nothing if the src is falsey
  54533. if (!_src) {
  54534. return;
  54535. }
  54536. this.setOptions_(); // add master playlist controller options
  54537. this.options_.src = expandDataUri(this.source_.src);
  54538. this.options_.tech = this.tech_;
  54539. this.options_.externVhs = Vhs;
  54540. this.options_.sourceType = simpleTypeFromSourceType(type); // Whenever we seek internally, we should update the tech
  54541. this.options_.seekTo = function (time) {
  54542. _this3.tech_.setCurrentTime(time);
  54543. };
  54544. if (this.options_.smoothQualityChange) {
  54545. videojs.log.warn('smoothQualityChange is deprecated and will be removed in the next major version');
  54546. }
  54547. this.masterPlaylistController_ = new MasterPlaylistController(this.options_);
  54548. var playbackWatcherOptions = videojs.mergeOptions({
  54549. liveRangeSafeTimeDelta: SAFE_TIME_DELTA
  54550. }, this.options_, {
  54551. seekable: function seekable() {
  54552. return _this3.seekable();
  54553. },
  54554. media: function media() {
  54555. return _this3.masterPlaylistController_.media();
  54556. },
  54557. masterPlaylistController: this.masterPlaylistController_
  54558. });
  54559. this.playbackWatcher_ = new PlaybackWatcher(playbackWatcherOptions);
  54560. this.masterPlaylistController_.on('error', function () {
  54561. var player = videojs.players[_this3.tech_.options_.playerId];
  54562. var error = _this3.masterPlaylistController_.error;
  54563. if (typeof error === 'object' && !error.code) {
  54564. error.code = 3;
  54565. } else if (typeof error === 'string') {
  54566. error = {
  54567. message: error,
  54568. code: 3
  54569. };
  54570. }
  54571. player.error(error);
  54572. });
  54573. var defaultSelector = this.options_.experimentalBufferBasedABR ? Vhs.movingAverageBandwidthSelector(0.55) : Vhs.STANDARD_PLAYLIST_SELECTOR; // `this` in selectPlaylist should be the VhsHandler for backwards
  54574. // compatibility with < v2
  54575. this.masterPlaylistController_.selectPlaylist = this.selectPlaylist ? this.selectPlaylist.bind(this) : defaultSelector.bind(this);
  54576. this.masterPlaylistController_.selectInitialPlaylist = Vhs.INITIAL_PLAYLIST_SELECTOR.bind(this); // re-expose some internal objects for backwards compatibility with < v2
  54577. this.playlists = this.masterPlaylistController_.masterPlaylistLoader_;
  54578. this.mediaSource = this.masterPlaylistController_.mediaSource; // Proxy assignment of some properties to the master playlist
  54579. // controller. Using a custom property for backwards compatibility
  54580. // with < v2
  54581. Object.defineProperties(this, {
  54582. selectPlaylist: {
  54583. get: function get() {
  54584. return this.masterPlaylistController_.selectPlaylist;
  54585. },
  54586. set: function set(selectPlaylist) {
  54587. this.masterPlaylistController_.selectPlaylist = selectPlaylist.bind(this);
  54588. }
  54589. },
  54590. throughput: {
  54591. get: function get() {
  54592. return this.masterPlaylistController_.mainSegmentLoader_.throughput.rate;
  54593. },
  54594. set: function set(throughput) {
  54595. this.masterPlaylistController_.mainSegmentLoader_.throughput.rate = throughput; // By setting `count` to 1 the throughput value becomes the starting value
  54596. // for the cumulative average
  54597. this.masterPlaylistController_.mainSegmentLoader_.throughput.count = 1;
  54598. }
  54599. },
  54600. bandwidth: {
  54601. get: function get() {
  54602. var playerBandwidthEst = this.masterPlaylistController_.mainSegmentLoader_.bandwidth;
  54603. var networkInformation = window.navigator.connection || window.navigator.mozConnection || window.navigator.webkitConnection;
  54604. var tenMbpsAsBitsPerSecond = 10e6;
  54605. if (this.options_.useNetworkInformationApi && networkInformation) {
  54606. // downlink returns Mbps
  54607. // https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/downlink
  54608. var networkInfoBandwidthEstBitsPerSec = networkInformation.downlink * 1000 * 1000; // downlink maxes out at 10 Mbps. In the event that both networkInformationApi and the player
  54609. // estimate a bandwidth greater than 10 Mbps, use the larger of the two estimates to ensure that
  54610. // high quality streams are not filtered out.
  54611. if (networkInfoBandwidthEstBitsPerSec >= tenMbpsAsBitsPerSecond && playerBandwidthEst >= tenMbpsAsBitsPerSecond) {
  54612. playerBandwidthEst = Math.max(playerBandwidthEst, networkInfoBandwidthEstBitsPerSec);
  54613. } else {
  54614. playerBandwidthEst = networkInfoBandwidthEstBitsPerSec;
  54615. }
  54616. }
  54617. return playerBandwidthEst;
  54618. },
  54619. set: function set(bandwidth) {
  54620. this.masterPlaylistController_.mainSegmentLoader_.bandwidth = bandwidth; // setting the bandwidth manually resets the throughput counter
  54621. // `count` is set to zero that current value of `rate` isn't included
  54622. // in the cumulative average
  54623. this.masterPlaylistController_.mainSegmentLoader_.throughput = {
  54624. rate: 0,
  54625. count: 0
  54626. };
  54627. }
  54628. },
  54629. /**
  54630. * `systemBandwidth` is a combination of two serial processes bit-rates. The first
  54631. * is the network bitrate provided by `bandwidth` and the second is the bitrate of
  54632. * the entire process after that - decryption, transmuxing, and appending - provided
  54633. * by `throughput`.
  54634. *
  54635. * Since the two process are serial, the overall system bandwidth is given by:
  54636. * sysBandwidth = 1 / (1 / bandwidth + 1 / throughput)
  54637. */
  54638. systemBandwidth: {
  54639. get: function get() {
  54640. var invBandwidth = 1 / (this.bandwidth || 1);
  54641. var invThroughput;
  54642. if (this.throughput > 0) {
  54643. invThroughput = 1 / this.throughput;
  54644. } else {
  54645. invThroughput = 0;
  54646. }
  54647. var systemBitrate = Math.floor(1 / (invBandwidth + invThroughput));
  54648. return systemBitrate;
  54649. },
  54650. set: function set() {
  54651. videojs.log.error('The "systemBandwidth" property is read-only');
  54652. }
  54653. }
  54654. });
  54655. if (this.options_.bandwidth) {
  54656. this.bandwidth = this.options_.bandwidth;
  54657. }
  54658. if (this.options_.throughput) {
  54659. this.throughput = this.options_.throughput;
  54660. }
  54661. Object.defineProperties(this.stats, {
  54662. bandwidth: {
  54663. get: function get() {
  54664. return _this3.bandwidth || 0;
  54665. },
  54666. enumerable: true
  54667. },
  54668. mediaRequests: {
  54669. get: function get() {
  54670. return _this3.masterPlaylistController_.mediaRequests_() || 0;
  54671. },
  54672. enumerable: true
  54673. },
  54674. mediaRequestsAborted: {
  54675. get: function get() {
  54676. return _this3.masterPlaylistController_.mediaRequestsAborted_() || 0;
  54677. },
  54678. enumerable: true
  54679. },
  54680. mediaRequestsTimedout: {
  54681. get: function get() {
  54682. return _this3.masterPlaylistController_.mediaRequestsTimedout_() || 0;
  54683. },
  54684. enumerable: true
  54685. },
  54686. mediaRequestsErrored: {
  54687. get: function get() {
  54688. return _this3.masterPlaylistController_.mediaRequestsErrored_() || 0;
  54689. },
  54690. enumerable: true
  54691. },
  54692. mediaTransferDuration: {
  54693. get: function get() {
  54694. return _this3.masterPlaylistController_.mediaTransferDuration_() || 0;
  54695. },
  54696. enumerable: true
  54697. },
  54698. mediaBytesTransferred: {
  54699. get: function get() {
  54700. return _this3.masterPlaylistController_.mediaBytesTransferred_() || 0;
  54701. },
  54702. enumerable: true
  54703. },
  54704. mediaSecondsLoaded: {
  54705. get: function get() {
  54706. return _this3.masterPlaylistController_.mediaSecondsLoaded_() || 0;
  54707. },
  54708. enumerable: true
  54709. },
  54710. mediaAppends: {
  54711. get: function get() {
  54712. return _this3.masterPlaylistController_.mediaAppends_() || 0;
  54713. },
  54714. enumerable: true
  54715. },
  54716. mainAppendsToLoadedData: {
  54717. get: function get() {
  54718. return _this3.masterPlaylistController_.mainAppendsToLoadedData_() || 0;
  54719. },
  54720. enumerable: true
  54721. },
  54722. audioAppendsToLoadedData: {
  54723. get: function get() {
  54724. return _this3.masterPlaylistController_.audioAppendsToLoadedData_() || 0;
  54725. },
  54726. enumerable: true
  54727. },
  54728. appendsToLoadedData: {
  54729. get: function get() {
  54730. return _this3.masterPlaylistController_.appendsToLoadedData_() || 0;
  54731. },
  54732. enumerable: true
  54733. },
  54734. timeToLoadedData: {
  54735. get: function get() {
  54736. return _this3.masterPlaylistController_.timeToLoadedData_() || 0;
  54737. },
  54738. enumerable: true
  54739. },
  54740. buffered: {
  54741. get: function get() {
  54742. return timeRangesToArray(_this3.tech_.buffered());
  54743. },
  54744. enumerable: true
  54745. },
  54746. currentTime: {
  54747. get: function get() {
  54748. return _this3.tech_.currentTime();
  54749. },
  54750. enumerable: true
  54751. },
  54752. currentSource: {
  54753. get: function get() {
  54754. return _this3.tech_.currentSource_;
  54755. },
  54756. enumerable: true
  54757. },
  54758. currentTech: {
  54759. get: function get() {
  54760. return _this3.tech_.name_;
  54761. },
  54762. enumerable: true
  54763. },
  54764. duration: {
  54765. get: function get() {
  54766. return _this3.tech_.duration();
  54767. },
  54768. enumerable: true
  54769. },
  54770. master: {
  54771. get: function get() {
  54772. return _this3.playlists.master;
  54773. },
  54774. enumerable: true
  54775. },
  54776. playerDimensions: {
  54777. get: function get() {
  54778. return _this3.tech_.currentDimensions();
  54779. },
  54780. enumerable: true
  54781. },
  54782. seekable: {
  54783. get: function get() {
  54784. return timeRangesToArray(_this3.tech_.seekable());
  54785. },
  54786. enumerable: true
  54787. },
  54788. timestamp: {
  54789. get: function get() {
  54790. return Date.now();
  54791. },
  54792. enumerable: true
  54793. },
  54794. videoPlaybackQuality: {
  54795. get: function get() {
  54796. return _this3.tech_.getVideoPlaybackQuality();
  54797. },
  54798. enumerable: true
  54799. }
  54800. });
  54801. this.tech_.one('canplay', this.masterPlaylistController_.setupFirstPlay.bind(this.masterPlaylistController_));
  54802. this.tech_.on('bandwidthupdate', function () {
  54803. if (_this3.options_.useBandwidthFromLocalStorage) {
  54804. updateVhsLocalStorage({
  54805. bandwidth: _this3.bandwidth,
  54806. throughput: Math.round(_this3.throughput)
  54807. });
  54808. }
  54809. });
  54810. this.masterPlaylistController_.on('selectedinitialmedia', function () {
  54811. // Add the manual rendition mix-in to VhsHandler
  54812. renditionSelectionMixin(_this3);
  54813. });
  54814. this.masterPlaylistController_.sourceUpdater_.on('createdsourcebuffers', function () {
  54815. _this3.setupEme_();
  54816. }); // the bandwidth of the primary segment loader is our best
  54817. // estimate of overall bandwidth
  54818. this.on(this.masterPlaylistController_, 'progress', function () {
  54819. this.tech_.trigger('progress');
  54820. }); // In the live case, we need to ignore the very first `seeking` event since
  54821. // that will be the result of the seek-to-live behavior
  54822. this.on(this.masterPlaylistController_, 'firstplay', function () {
  54823. this.ignoreNextSeekingEvent_ = true;
  54824. });
  54825. this.setupQualityLevels_(); // do nothing if the tech has been disposed already
  54826. // this can occur if someone sets the src in player.ready(), for instance
  54827. if (!this.tech_.el()) {
  54828. return;
  54829. }
  54830. this.mediaSourceUrl_ = window.URL.createObjectURL(this.masterPlaylistController_.mediaSource);
  54831. this.tech_.src(this.mediaSourceUrl_);
  54832. };
  54833. _proto.createKeySessions_ = function createKeySessions_() {
  54834. var _this4 = this;
  54835. var audioPlaylistLoader = this.masterPlaylistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  54836. this.logger_('waiting for EME key session creation');
  54837. waitForKeySessionCreation({
  54838. player: this.player_,
  54839. sourceKeySystems: this.source_.keySystems,
  54840. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media(),
  54841. mainPlaylists: this.playlists.master.playlists
  54842. }).then(function () {
  54843. _this4.logger_('created EME key session');
  54844. _this4.masterPlaylistController_.sourceUpdater_.initializedEme();
  54845. })["catch"](function (err) {
  54846. _this4.logger_('error while creating EME key session', err);
  54847. _this4.player_.error({
  54848. message: 'Failed to initialize media keys for EME',
  54849. code: 3
  54850. });
  54851. });
  54852. };
  54853. _proto.handleWaitingForKey_ = function handleWaitingForKey_() {
  54854. // If waitingforkey is fired, it's possible that the data that's necessary to retrieve
  54855. // the key is in the manifest. While this should've happened on initial source load, it
  54856. // may happen again in live streams where the keys change, and the manifest info
  54857. // reflects the update.
  54858. //
  54859. // Because videojs-contrib-eme compares the PSSH data we send to that of PSSH data it's
  54860. // already requested keys for, we don't have to worry about this generating extraneous
  54861. // requests.
  54862. this.logger_('waitingforkey fired, attempting to create any new key sessions');
  54863. this.createKeySessions_();
  54864. }
  54865. /**
  54866. * If necessary and EME is available, sets up EME options and waits for key session
  54867. * creation.
  54868. *
  54869. * This function also updates the source updater so taht it can be used, as for some
  54870. * browsers, EME must be configured before content is appended (if appending unencrypted
  54871. * content before encrypted content).
  54872. */
  54873. ;
  54874. _proto.setupEme_ = function setupEme_() {
  54875. var _this5 = this;
  54876. var audioPlaylistLoader = this.masterPlaylistController_.mediaTypes_.AUDIO.activePlaylistLoader;
  54877. var didSetupEmeOptions = setupEmeOptions({
  54878. player: this.player_,
  54879. sourceKeySystems: this.source_.keySystems,
  54880. media: this.playlists.media(),
  54881. audioMedia: audioPlaylistLoader && audioPlaylistLoader.media()
  54882. });
  54883. this.player_.tech_.on('keystatuschange', function (e) {
  54884. if (e.status !== 'output-restricted') {
  54885. return;
  54886. }
  54887. var masterPlaylist = _this5.masterPlaylistController_.master();
  54888. if (!masterPlaylist || !masterPlaylist.playlists) {
  54889. return;
  54890. }
  54891. var excludedHDPlaylists = []; // Assume all HD streams are unplayable and exclude them from ABR selection
  54892. masterPlaylist.playlists.forEach(function (playlist) {
  54893. if (playlist && playlist.attributes && playlist.attributes.RESOLUTION && playlist.attributes.RESOLUTION.height >= 720) {
  54894. if (!playlist.excludeUntil || playlist.excludeUntil < Infinity) {
  54895. playlist.excludeUntil = Infinity;
  54896. excludedHDPlaylists.push(playlist);
  54897. }
  54898. }
  54899. });
  54900. if (excludedHDPlaylists.length) {
  54901. var _videojs$log;
  54902. (_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
  54903. _this5.masterPlaylistController_.fastQualityChange_();
  54904. }
  54905. });
  54906. this.handleWaitingForKey_ = this.handleWaitingForKey_.bind(this);
  54907. this.player_.tech_.on('waitingforkey', this.handleWaitingForKey_); // In IE11 this is too early to initialize media keys, and IE11 does not support
  54908. // promises.
  54909. if (videojs.browser.IE_VERSION === 11 || !didSetupEmeOptions) {
  54910. // If EME options were not set up, we've done all we could to initialize EME.
  54911. this.masterPlaylistController_.sourceUpdater_.initializedEme();
  54912. return;
  54913. }
  54914. this.createKeySessions_();
  54915. }
  54916. /**
  54917. * Initializes the quality levels and sets listeners to update them.
  54918. *
  54919. * @method setupQualityLevels_
  54920. * @private
  54921. */
  54922. ;
  54923. _proto.setupQualityLevels_ = function setupQualityLevels_() {
  54924. var _this6 = this;
  54925. var player = videojs.players[this.tech_.options_.playerId]; // if there isn't a player or there isn't a qualityLevels plugin
  54926. // or qualityLevels_ listeners have already been setup, do nothing.
  54927. if (!player || !player.qualityLevels || this.qualityLevels_) {
  54928. return;
  54929. }
  54930. this.qualityLevels_ = player.qualityLevels();
  54931. this.masterPlaylistController_.on('selectedinitialmedia', function () {
  54932. handleVhsLoadedMetadata(_this6.qualityLevels_, _this6);
  54933. });
  54934. this.playlists.on('mediachange', function () {
  54935. handleVhsMediaChange(_this6.qualityLevels_, _this6.playlists);
  54936. });
  54937. }
  54938. /**
  54939. * return the version
  54940. */
  54941. ;
  54942. VhsHandler.version = function version$5() {
  54943. return {
  54944. '@videojs/http-streaming': version$4,
  54945. 'mux.js': version$3,
  54946. 'mpd-parser': version$2,
  54947. 'm3u8-parser': version$1,
  54948. 'aes-decrypter': version
  54949. };
  54950. }
  54951. /**
  54952. * return the version
  54953. */
  54954. ;
  54955. _proto.version = function version() {
  54956. return this.constructor.version();
  54957. };
  54958. _proto.canChangeType = function canChangeType() {
  54959. return SourceUpdater.canChangeType();
  54960. }
  54961. /**
  54962. * Begin playing the video.
  54963. */
  54964. ;
  54965. _proto.play = function play() {
  54966. this.masterPlaylistController_.play();
  54967. }
  54968. /**
  54969. * a wrapper around the function in MasterPlaylistController
  54970. */
  54971. ;
  54972. _proto.setCurrentTime = function setCurrentTime(currentTime) {
  54973. this.masterPlaylistController_.setCurrentTime(currentTime);
  54974. }
  54975. /**
  54976. * a wrapper around the function in MasterPlaylistController
  54977. */
  54978. ;
  54979. _proto.duration = function duration() {
  54980. return this.masterPlaylistController_.duration();
  54981. }
  54982. /**
  54983. * a wrapper around the function in MasterPlaylistController
  54984. */
  54985. ;
  54986. _proto.seekable = function seekable() {
  54987. return this.masterPlaylistController_.seekable();
  54988. }
  54989. /**
  54990. * Abort all outstanding work and cleanup.
  54991. */
  54992. ;
  54993. _proto.dispose = function dispose() {
  54994. if (this.playbackWatcher_) {
  54995. this.playbackWatcher_.dispose();
  54996. }
  54997. if (this.masterPlaylistController_) {
  54998. this.masterPlaylistController_.dispose();
  54999. }
  55000. if (this.qualityLevels_) {
  55001. this.qualityLevels_.dispose();
  55002. }
  55003. if (this.player_) {
  55004. delete this.player_.vhs;
  55005. delete this.player_.dash;
  55006. delete this.player_.hls;
  55007. }
  55008. if (this.tech_ && this.tech_.vhs) {
  55009. delete this.tech_.vhs;
  55010. } // don't check this.tech_.hls as it will log a deprecated warning
  55011. if (this.tech_) {
  55012. delete this.tech_.hls;
  55013. }
  55014. if (this.mediaSourceUrl_ && window.URL.revokeObjectURL) {
  55015. window.URL.revokeObjectURL(this.mediaSourceUrl_);
  55016. this.mediaSourceUrl_ = null;
  55017. }
  55018. if (this.tech_) {
  55019. this.tech_.off('waitingforkey', this.handleWaitingForKey_);
  55020. }
  55021. _Component.prototype.dispose.call(this);
  55022. };
  55023. _proto.convertToProgramTime = function convertToProgramTime(time, callback) {
  55024. return getProgramTime({
  55025. playlist: this.masterPlaylistController_.media(),
  55026. time: time,
  55027. callback: callback
  55028. });
  55029. } // the player must be playing before calling this
  55030. ;
  55031. _proto.seekToProgramTime = function seekToProgramTime$1(programTime, callback, pauseAfterSeek, retryCount) {
  55032. if (pauseAfterSeek === void 0) {
  55033. pauseAfterSeek = true;
  55034. }
  55035. if (retryCount === void 0) {
  55036. retryCount = 2;
  55037. }
  55038. return seekToProgramTime({
  55039. programTime: programTime,
  55040. playlist: this.masterPlaylistController_.media(),
  55041. retryCount: retryCount,
  55042. pauseAfterSeek: pauseAfterSeek,
  55043. seekTo: this.options_.seekTo,
  55044. tech: this.options_.tech,
  55045. callback: callback
  55046. });
  55047. };
  55048. return VhsHandler;
  55049. }(Component);
  55050. /**
  55051. * The Source Handler object, which informs video.js what additional
  55052. * MIME types are supported and sets up playback. It is registered
  55053. * automatically to the appropriate tech based on the capabilities of
  55054. * the browser it is running in. It is not necessary to use or modify
  55055. * this object in normal usage.
  55056. */
  55057. var VhsSourceHandler = {
  55058. name: 'videojs-http-streaming',
  55059. VERSION: version$4,
  55060. canHandleSource: function canHandleSource(srcObj, options) {
  55061. if (options === void 0) {
  55062. options = {};
  55063. }
  55064. var localOptions = videojs.mergeOptions(videojs.options, options);
  55065. return VhsSourceHandler.canPlayType(srcObj.type, localOptions);
  55066. },
  55067. handleSource: function handleSource(source, tech, options) {
  55068. if (options === void 0) {
  55069. options = {};
  55070. }
  55071. var localOptions = videojs.mergeOptions(videojs.options, options);
  55072. tech.vhs = new VhsHandler(source, tech, localOptions);
  55073. if (!videojs.hasOwnProperty('hls')) {
  55074. Object.defineProperty(tech, 'hls', {
  55075. get: function get() {
  55076. videojs.log.warn('player.tech().hls is deprecated. Use player.tech().vhs instead.');
  55077. return tech.vhs;
  55078. },
  55079. configurable: true
  55080. });
  55081. }
  55082. tech.vhs.xhr = xhrFactory();
  55083. tech.vhs.src(source.src, source.type);
  55084. return tech.vhs;
  55085. },
  55086. canPlayType: function canPlayType(type, options) {
  55087. var simpleType = simpleTypeFromSourceType(type);
  55088. if (!simpleType) {
  55089. return '';
  55090. }
  55091. var overrideNative = VhsSourceHandler.getOverrideNative(options);
  55092. var supportsTypeNatively = Vhs.supportsTypeNatively(simpleType);
  55093. var canUseMsePlayback = !supportsTypeNatively || overrideNative;
  55094. return canUseMsePlayback ? 'maybe' : '';
  55095. },
  55096. getOverrideNative: function getOverrideNative(options) {
  55097. if (options === void 0) {
  55098. options = {};
  55099. }
  55100. var _options = options,
  55101. _options$vhs = _options.vhs,
  55102. vhs = _options$vhs === void 0 ? {} : _options$vhs,
  55103. _options$hls = _options.hls,
  55104. hls = _options$hls === void 0 ? {} : _options$hls;
  55105. var defaultOverrideNative = !(videojs.browser.IS_ANY_SAFARI || videojs.browser.IS_IOS);
  55106. var _vhs$overrideNative = vhs.overrideNative,
  55107. overrideNative = _vhs$overrideNative === void 0 ? defaultOverrideNative : _vhs$overrideNative;
  55108. var _hls$overrideNative = hls.overrideNative,
  55109. legacyOverrideNative = _hls$overrideNative === void 0 ? false : _hls$overrideNative;
  55110. return legacyOverrideNative || overrideNative;
  55111. }
  55112. };
  55113. /**
  55114. * Check to see if the native MediaSource object exists and supports
  55115. * an MP4 container with both H.264 video and AAC-LC audio.
  55116. *
  55117. * @return {boolean} if native media sources are supported
  55118. */
  55119. var supportsNativeMediaSources = function supportsNativeMediaSources() {
  55120. return browserSupportsCodec('avc1.4d400d,mp4a.40.2');
  55121. }; // register source handlers with the appropriate techs
  55122. if (supportsNativeMediaSources()) {
  55123. videojs.getTech('Html5').registerSourceHandler(VhsSourceHandler, 0);
  55124. }
  55125. videojs.VhsHandler = VhsHandler;
  55126. Object.defineProperty(videojs, 'HlsHandler', {
  55127. get: function get() {
  55128. videojs.log.warn('videojs.HlsHandler is deprecated. Use videojs.VhsHandler instead.');
  55129. return VhsHandler;
  55130. },
  55131. configurable: true
  55132. });
  55133. videojs.VhsSourceHandler = VhsSourceHandler;
  55134. Object.defineProperty(videojs, 'HlsSourceHandler', {
  55135. get: function get() {
  55136. videojs.log.warn('videojs.HlsSourceHandler is deprecated. ' + 'Use videojs.VhsSourceHandler instead.');
  55137. return VhsSourceHandler;
  55138. },
  55139. configurable: true
  55140. });
  55141. videojs.Vhs = Vhs;
  55142. Object.defineProperty(videojs, 'Hls', {
  55143. get: function get() {
  55144. videojs.log.warn('videojs.Hls is deprecated. Use videojs.Vhs instead.');
  55145. return Vhs;
  55146. },
  55147. configurable: true
  55148. });
  55149. if (!videojs.use) {
  55150. videojs.registerComponent('Hls', Vhs);
  55151. videojs.registerComponent('Vhs', Vhs);
  55152. }
  55153. videojs.options.vhs = videojs.options.vhs || {};
  55154. videojs.options.hls = videojs.options.hls || {};
  55155. if (!videojs.getPlugin || !videojs.getPlugin('reloadSourceOnError')) {
  55156. var registerPlugin = videojs.registerPlugin || videojs.plugin;
  55157. registerPlugin('reloadSourceOnError', reloadSourceOnError);
  55158. }
  55159. return videojs;
  55160. })));